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

2511 lines
3.9 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-09-01 12:32:47 +08:00
var ewr=Object.create;var e6=Object.defineProperty;var twr=Object.getOwnPropertyDescriptor;var rwr=Object.getOwnPropertyNames;var nwr=Object.getPrototypeOf,owr=Object.prototype.hasOwnProperty;var wGe=t=>{throw TypeError(t)};var iwr=(t,e,r)=>e in t?e6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var x=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),os=(t,e)=>{for(var r in e)e6(t,r,{get:e[r],enumerable:!0})},xGe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rwr(e))!owr.call(t,o)&&o!==r&&e6(t,o,{get:()=>e[o],enumerable:!(n=twr(e,o))||n.enumerable});return t};var j=(t,e,r)=>(r=t!=null?ewr(nwr(t)):{},xGe(e||!t||!t.__esModule?e6(r,"default",{value:t,enumerable:!0}):r,t)),Nc=t=>xGe(e6({},"__esModule",{value:!0}),t);var bd=(t,e,r)=>iwr(t,typeof e!="symbol"?e+"":e,r),awr=(t,e,r)=>e.has(t)||wGe("Cannot "+r);var bwe=(t,e,r)=>e.has(t)?wGe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var SGe=(t,e,r)=>(awr(t,e,"access private method"),r);function _we(){if(!OX&&(OX=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!OX))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return OX(swr)}var OX,swr,CGe=b(()=>{swr=new Uint8Array(16)});function OGe(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]]}var _d,EGe=b(()=>{_d=[];for(let t=0;t<256;++t)_d.push((t+256).toString(16).slice(1))});var uwr,vwe,PGe=b(()=>{uwr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),vwe={randomUUID:uwr}});function lwr(t,e,r){if(vwe.randomUUID&&!e&&!t)return vwe.randomUUID();t=t||{};let n=t.random||(t.rng||_we)();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 OGe(n)}var dm,TGe=b(()=>{PGe();CGe();EGe();dm=lwr});var zN=b(()=>{TGe()});var Gn,wwe,yt,gv,t6=b(()=>{(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})(Gn||(Gn={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(wwe||(wwe={}));yt=Gn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gv=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 Ue,cwr,fm,EX=b(()=>{t6();Ue=Gn.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
2025-08-12 16:40:13 +08:00
2025-09-01 12:32:47 +08:00
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function zX(t){return typeof t=="function"&&"langsmith:traceable"in t}var jwe,Nwe,L0r,Dwe,F0r,KJn,sJe=b(()=>{jwe=class{getStore(){}run(e,r){return r()}},Nwe=Symbol.for("ls:tracing_async_local_storage"),L0r=new jwe,Dwe=class{getInstance(){return globalThis[Nwe]??L0r}initializeGlobalInstance(e){globalThis[Nwe]===void 0&&(globalThis[Nwe]=e)}},F0r=new Dwe;KJn=Symbol.for("langsmith:traceable:root")});var Lwe=b(()=>{sJe()});function qX(t,e){return k0r.call(t,e)}function HX(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)qX(t,r)&&e.push(r);return e}function Sf(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function VX(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 _v(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function a6(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function UX(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(UX(t[r]))return!0}else if(typeof t=="object"){let r=HX(t),n=r.length;for(var e=0;e<n;e++)if(UX(t[r[e]]))return!0}}return!1}function uJe(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 k0r,aj,s6=b(()=>{k0r=Object.prototype.hasOwnProperty;aj=class extends Error{constructor(e,r,n,o,i){super(uJe(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=uJe(e,{name:r,index:n,operation:o,tree:i})}}});var Fwe={};os(Fwe,{JsonPatchError:()=>Rs,_areEquals:()=>u6,applyOperation:()=>sj,applyPatch:()=>LA,applyReducer:()=>z0r,deepClone:()=>$0r,getValueByPointer:()=>WX,validate:()=>lJe,validator:()=>KX});function WX(t,e){if(e=="")return t;var r={op:"_get",path:e};return sj(t,r),r.value}function sj(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):KX(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=WX(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=u6(t,e.value),a.test===!1)throw new Rs("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 Rs("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Sf(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=KX;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=a6(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&&!VX(f))throw new Rs("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);VX(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Rs("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let h=B0r[e.op].call(e,u,f,t);if(h.test===!1)throw new Rs("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}}else if(l>=c){let h=hB[e.op].call(e,u,f,t);if(h.test===!1)throw new Rs("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return h}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Rs("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function LA(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Rs("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Sf(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=sj(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function z0r(t,e,r){let n=sj(t,e);if(n.test===!1)throw new Rs("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function KX(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Rs("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(hB[t.op]){if(typeof t.path!="string")throw new Rs("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Rs('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 Rs("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}`:""}`),wQ("[Unserializable]");nc("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=lOr()),N0e(t,"",0,[],void 0,0,o);let a;try{bB.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,dOr(r),n)}catch{return wQ("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;xQ.length!==0;){let s=xQ.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return wQ(a)}}function R0e(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),xQ.push([n,r,e,o])):bB.push([e,r,t]):(n[r]=t,xQ.push([n,r,e]))}function N0e(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){R0e(sOr,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){R0e(nYe,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){R0e(nYe,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)N0e(t[s],s,s,n,t,i,a);else{t=oYe(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];N0e(t[l],l,s,n,t,i,a)}}n.pop()}}function dOr(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(bB.length>0)for(var n=0;n<bB.length;n++){var o=bB[n];if(o[1]===e&&o[0]===r){r=o[2],bB.splice(n,1);break}}return t.call(this,e,r)}}var nYe,sOr,xQ,bB,uOr,iYe=b(()=>{cE();nYe="[...]",sOr={result:"[Circular]"},xQ=[],bB=[],uOr=new TextEncoder});function aYe(t){let e=QX(),r=HJe(),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 mOr(t){let e=[];for await(let r of t)e.push(r);return e}function j0e(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function sYe(t){return typeof t=="number"?Number(t.toFixed(4)):t}function lYe(t){return"dataset_id"in t||"dataset_name"in t}var fOr,pOr,hOr,D0e,gOr,yOr,uYe,uj,Vwe=b(()=>{ij();GJe();r0e();i7e();a7e();cE();XX();s7e();d0e();eYe();M0e();ZX();iYe();fOr=t=>{let e=t?.toString()??nc("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},pOr=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};hOr=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};D0e=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=gm(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())]}},gOr=20971520,yOr=2500,uYe="https://api.smith.langchain.com",uj=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-09-01 12:32:47 +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=tQ(),r=WJe();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=aYe(i);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let s=await this.caller.call(Jt(this.debug),`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,body:gm(a,`Creating run with id: ${a.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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(gm(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(Jt(this.debug),`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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,h)=>(h.id&&(p[h.id]=h),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:h,outputs:m,events:g,attachments:y,..._}=p,w={inputs:h,outputs:m,events:g},S=gm(_,`Serializing for multipart ingestion of run with id: ${_.id}`);c.push({name:`${d}.${_.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[C,E]of Object.entries(
2025-08-12 16:40:13 +08:00
`])),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
2025-09-01 12:32:47 +08:00
`),i.close()}})}async _sendMultipartRequest(e,r,n){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=UJe(),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(Jt(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)!==uYe&&(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 fn(l,"ingest multipart runs",!0)}catch(l){console.warn(`${l.message.trim()}
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
Context: ${r}`)}}async updateRun(e,r,n){an(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(Jt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,body:gm(r,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(a,"update run",!0)}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){an(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:nc("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 mOr(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:h,traceFilter:m,treeFilter:g,limit:y,select:_,order:w}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let T=Array.isArray(n)?n:[n],I=await Promise.all(T.map(N=>this.readProject({projectName:N}).then(M=>M.id)));S.push(...I)}let C=["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:h,trace_filter:m,tree_filter:g,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:y,trace:i,select:_||C,is_root:l,order:w},P=0;for await(let T of this._getCursorPaginatedList("/runs/query",E))if(y){if(P>=y)break;if(T.length+P>y){yield*T.slice(0,y-P);break}P+=T.length,yield*T}else yield*T}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",h=`${this.apiUrl}${p}`;for(;;){let m={...d,offset:f},g=Object.fromEntries(Object.entries(m).filter(([C,E])=>E!==void 0)),y=await this.caller.call(Jt(),h,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(g),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(`
2025-09-01 12:32:47 +08:00
`):"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(Jt(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 fn(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(Jt(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 fn(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)an(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(Jt(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)an(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,an(n);let o=await this.caller.call(Jt(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;an(i);let a=await this.caller.call(Jt(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 fn(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;an(a);let s=await this.caller.call(Jt(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 fn(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)an(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Jt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await fn(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),an(o);let i={tag:n},a=await this.caller.call(Jt(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 fn(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),an(r);let a=await this.caller.call(Jt(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 fn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(lYe(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;lYe(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]??Ms())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let _=e,w=_[0].dataset_id,S=_[0].dataset_name;if(w===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==void 0&&S!==void 0)throw new
2025-07-05 20:48:33 +08:00
Current tenant: ${n.tenant_handle}
2025-09-01 12:32:47 +08:00
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let r=await this.caller.call(Jt(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}
${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]=pE(e),a=await this.caller.call(Jt(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 fn(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(e){let[r,n,o]=pE(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]=pE(e),i=await this.caller.call(Jt(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 fn(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-09-01 12:32:47 +08:00
https://smith.langchain.com/prompts`);let[o,i,a]=pE(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(Jt(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 fn(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]=pE(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(Jt(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 fn(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=gm(l,`Serializing body for example with id: ${u}`),d=new Blob([c],{type:"application/json"});if(n.append(u,d),s.inputs){let f=gm(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=gm(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 h,m;Array.isArray(p)?[h,m]=p:(h=p.mimeType,m=p.data);let g=new Blob([m],{type:`${h}; length=${m.byteLength}`});n.append(`${u}.attachment.${f}`,g)}if(s.attachments_operations){let f=gm(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(Jt(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??Ms()).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=gm(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=gm(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=gm(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,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${s}.attachment.${d}`,m)}}let o=
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:n}=L0e(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=H0e(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=q0e(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=q0e(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=q0e(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-09-01 12:32:47 +08:00
`,t}var w6=b(()=>{});function $A(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function kYe(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 mj,PQ=b(()=>{mj=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 W0e(t,e=vB){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-09-01 12:32:47 +08:00
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function vB(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 K0e=b(()=>{});function Ib(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 $Ye(t){return Ib(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function BYe(t){return Ib(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function zYe(t){if(Ib(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 G0e(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 wB({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 x6(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 J0e=b(()=>{});function Ug(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>Ib(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?S6(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Ib(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function UYe(t,e){return t==="error"||e==="error"?"error":"success"}function $Or(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 Zs(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]=Zs(r[n],o);else if(Array.isArray(r[n]))r[n]=S6(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 S6(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-09-01 12:32:47 +08:00
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return S6(t,e);if(typeof t=="object"&&typeof e=="object")return Zs(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-09-01 12:32:47 +08:00
Right ${e}`)}function HYe(t){return typeof t.role=="string"}function qg(t){return typeof t?._getType=="function"}function Z0e(t){return qg(t)&&typeof t.concat=="function"}var oc,_m,Hg=b(()=>{cj();J0e();oc=class extends ym{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=$Or(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};_m=class extends oc{}});function VYe(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function WYe(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 mE,Vg,xB=b(()=>{Hg();mE=class extends oc{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}}},Vg=class t extends _m{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:Ug(this.content,e.content),additional_kwargs:Zs(this.additional_kwargs,e.a
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +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]=WYe(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}}};Sr=class t extends _m{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=vB(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:Ug(this.content,e.content),additional_kwargs:Zs(this.additional_kwargs,e.additional_kwargs),response_metadata:Zs(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=S6(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-09-01 12:32:47 +08:00
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Mb(t){if(typeof t=="string")return new Xs(t);if(qg(t))return t;if(Array.isArray(t)){let[e,r]=t;return X0e({type:e,content:r})}else if(HYe(t)){let{role:e,...r}=t;return X0e({...r,type:e})}else return X0e(t)}function Op(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 Q0e(t){let e=t._getType();if(e==="human")return new Cp({...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 Sr({...r})}else{if(e==="system")return new Ef({...t});if(e==="function")return new Eh({...t});if(Ys.isInstance(t))return new Sp({...t});throw new Error("Unknown message type.")}}var BA=b(()=>{w6();PQ();hj();Hg();TQ();AQ();C6();IQ();xB()});var MQ=b(()=>{XX()});var exe,txe,rxe=b(()=>{MQ();dj();txe=()=>{if(exe===void 0){let t=lt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};exe=new uj(t)}return exe}});var SB,KYe=b(()=>{MQ();OQ();Lwe();pj();rxe();SB=class t extends Bg{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??l6(),this.replicas=i,this.exampleId=r,this.client=o??txe();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 Ab({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return aJe(!0)}catch{return}}}});var GYe,gj,JYe,zA,O6=b(()=>{GYe=Symbol.for("ls:tracing_async_local_storage"),gj=Symbol.for("lc:context_variables"),JYe=t=>{globalThis[GYe]=t},zA=()=>globalThis[GYe]});function qOr(){let t="default"in RQ.default?RQ.default.default:RQ.default;return new t({autoStart:!0,concurrency:1})}function HOr(){return typeof E6>"u"&&(E6=qOr()),E6}async function Qs(t,e){if(e===!0){let r=zA();r!==void 0?await r.run(void 0,async()=>t()):await t()}else E6=HOr(),E6.add(async()=>{let r=zA();r!==void 0?await r.run(void 0,async()=>t()):await t()})}var RQ,E6,ZYe=b(()=>{RQ=j(sQ(),1);O6();rxe()});var YYe=b(()=>{ZYe()});var XYe,QYe=b(()=>{dj();XYe=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>lt(r)==="true")});function nxe(t){let e=zA();return e===void 0?void 0:e.getStore()?.[gj]?.[t]}var VOr,eXe,tXe=b(()=>{OQ();O6();VOr=Symbol("lc:configure_hooks"),eXe=()=>nxe(VOr)||[]});function T6(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function P6(t){return"name"in t?t:fj.fromMethods(t)}var oxe,CB,ixe,NQ,axe,sxe,gu,UA=b(()=>{ij();_6();FYe();BA();dj();KYe();YYe();QYe();pj();tXe();oxe=class{setHandler(e){return this.setHandlers([e])}},CB=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 pXe(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
2025-08-12 16:40:13 +08:00
graph TD;
`:`graph TD;
2025-09-01 12:32:47 +08:00
`;if(a){let p="default",h={[p]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[m,g]of Object.entries(t)){let y=g.name.split(":").pop()??"",w=YOr.some(C=>y.startsWith(C)&&y.endsWith(C))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([C,E])=>`${C} = ${E}`).join(`
`)}</em></small>`);let S=(h[m]??h[p]).replace("{0}",fxe(m)).replace("{1}",w);l+=` ${S}
2025-08-30 08:29:39 +08:00
`}}let c={};for(let p of e){let h=p.source.split(":"),m=p.target.split(":"),g=h.filter((y,_)=>y===m[_]).join(":");c[g]||(c[g]=[]),c[g].push(p)}let d=new Set;function f(p,h){let m=p.length===1&&p[0].source===p[0].target;if(h&&!m){let g=h.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- 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(g),l+=` subgraph ${g}
2025-09-01 12:32:47 +08:00
`}for(let g of p){let{source:y,target:_,data:w,conditional:S}=g,C="";if(w!==void 0){let E=w,P=E.split(" ");P.length>u&&(E=Array.from({length:Math.ceil(P.length/u)},(T,I)=>P.slice(I*u,(I+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),C=S?` -. &nbsp;${E}&nbsp; .-> `:` -- &nbsp;${E}&nbsp; --> `}else C=S?" -.-> ":" --> ";l+=` ${fxe(y)}${C}${fxe(_)};
2025-08-30 08:29:39 +08:00
`}for(let g in c)g.startsWith(`${h}:`)&&g!==h&&f(c[g],g);h&&!m&&(l+=` end
2025-09-01 12:32:47 +08:00
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=XOr(i??{})),l}async function mXe(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 YOr,hXe=b(()=>{YOr=["*","_","`"]});function TB(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 AB(t){return t&&Object.assign(pxe,t),pxe}var aQn,sQn,qA,pxe,j6=b(()=>{aQn=Object.freeze({status:"aborted"});sQn=Symbol("zod_brand"),qA=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},pxe={}});function mxe(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 yXe(t,e){return typeof e=="bigint"?e.toString():e}function bXe(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function IB(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function _Xe(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 zQ(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function BQ(t){return typeof t=="string"?t:t?.message}function MB(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=BQ(t.inst?._zod.def?.error?.(t))??BQ(e?.error?.(t))??BQ(r.customError?.(t))??BQ(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}var hxe,QOr,uQn,HA=b(()=>{hxe=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{},QOr=bXe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});uQn={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 vXe,wXe,D6,gxe=b(()=>{j6();HA();vXe=(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,yXe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wXe=TB("$ZodError",vXe),D6=TB("$ZodError",vXe,{Parent:Error})});var tEr,UQ,rEr,xXe,nEr,SXe,oEr,CXe,yxe=b(()=>{j6();gxe();HA();tEr=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 qA;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>MB(u,i,AB())));throw hxe(s,o?.callee),s}return a.value},UQ=tEr(D6),rEr=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=>MB(u,i,AB())));throw hxe(s,o?.callee),s}return a.value},xXe=rEr(D6),nEr=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 qA;return i.issues.length?{success:!1,error:new(t??wXe)(i.issues.map(a=>MB(a,o,AB())))}:{success:!0,data:i.value}},SXe=nEr(D6),oEr=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
2025-08-12 16:40:13 +08:00
2025-09-01 12:32:47 +08:00
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,h={...p};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){s(m,d);let g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,h))}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 LXe=b(()=>{});var HQ=b(()=>{j6();yxe();gxe();IXe();EXe();bxe();HA();OXe();MXe();_xe();PXe();jXe();NXe();DXe();LXe()});var kXe,FXe,$Xe,VQ=b(()=>{kXe=Symbol("Let zodToJsonSchema decide on which parser to use"),FXe={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"},$Xe=t=>typeof t=="string"?{...FXe,name:t}:{...FXe,...t}});var BXe,vxe=b(()=>{VQ();BXe=t=>{let e=$Xe(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 wxe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function fo(t,e,r,n,o){t[e]=r,wxe(t,e,n,o)}var VA=b(()=>{});var xd=b(()=>{i6();i6()});function zXe(){return{}}var xxe=b(()=>{});function UXe(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==re.ZodAny&&(r.items=Or(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&fo(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&fo(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(fo(r,"minItems",t.exactLength.value,t.exactLength.message,e),fo(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Sxe=b(()=>{xd();VA();yu()});function qXe(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?fo(r,"minimum",n.value,n.message,e):fo(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fo(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fo(r,"maximum",n.value,n.message,e):fo(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fo(r,"maximum",n.value,n.message,e));break;case"multipleOf":fo(r,"multipleOf",n.value,n.message,e);break}return r}var Cxe=b(()=>{VA()});function HXe(){return{type:"boolean"}}var Oxe=b(()=>{});function WQ(t,e){return Or(t.type._def,e)}var KQ=b(()=>{yu()});var VXe,Exe=b(()=>{yu();VXe=(t,e)=>Or(t.innerType._def,e)});function Pxe(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Pxe(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-09-01 12:32:47 +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 jxe,Nb,fEr,JQ=b(()=>{VA();Nb={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:()=>(jxe===void 0&&(jxe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),jxe),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-_]*$/};fEr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function ZQ(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]:Or(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Or(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}=GQ(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}=WQ(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var YQ=b(()=>{xd();yu();JQ();KQ()});function XXe(t,e){if(e.mapStrategy==="record")return ZQ(t,e);let r=Or(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Or(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 Lxe=b(()=>{yu();YQ()});function QXe(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 Fxe=b(()=>{});function eQe(){return{not:{}}}var kxe
2025-08-12 16:40:13 +08:00
Known schemas:
- ${Object.keys(n).join(`
2025-09-01 12:32:47 +08:00
- `)}`,new Error(be)}let ne=`${s}/$ref`,fe=va(t,le,r,n,o,i,a,ne,u);if(fe.valid||Me.push({instanceLocation:a,keyword:"$ref",keywordLocation:ne,error:"A subschema had errors."},...fe.errors),r==="4"||r==="7")return{valid:Me.length===0,errors:Me}}if(Array.isArray(h)){let je=h.length,le=!1;for(let ne=0;ne<je;ne++)if(c===h[ne]||h[ne]==="integer"&&c==="number"&&t%1===0&&t===t){le=!0;break}le||Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(c!=="number"||t%1||t!==t)&&Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`}):h!==void 0&&c!==h&&Me.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`});if(m!==void 0&&(c==="object"||c==="array"?yE(t,m)||Me.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):t!==m&&Me.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),g!==void 0&&(c==="object"||c==="array"?g.some(je=>yE(t,je))||Me.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(je=>t===je)||Me.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),_!==void 0){let je=`${s}/not`;va(t,_,r,n,o,i,a,je).valid&&Me.push({instanceLocation:a,keyword:"not",keywordLocation:je,error:'Instance matched "not" schema.'})}let Ze=[];if(w!==void 0){let je=`${s}/anyOf`,le=Me.length,ne=!1;for(let fe=0;fe<w.length;fe++){let be=w[fe],ye=Object.create(u),ze=va(t,be,r,n,o,p===!0?i:null,a,`${je}/${fe}`,ye);Me.push(...ze.errors),ne=ne||ze.valid,ze.valid&&Ze.push(ye)}ne?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:je,error:"Instance does not match any subschemas."})}if(S!==void 0){let je=`${s}/allOf`,le=Me.length,ne=!0;for(let fe=0;fe<S.length;fe++){let be=S[fe],ye=Object.create(u),ze=va(t,be,r,n,o,p===!0?i:null,a,`${je}/${fe}`,ye);Me.push(...ze.errors),ne=ne&&ze.valid,ze.valid&&Ze.push(ye)}ne?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"allOf",keywordLocation:je,error:"Instance does not match every subschema."})}if(C!==void 0){let je=`${s}/oneOf`,le=Me.length,ne=C.filter((fe,be)=>{let ye=Object.create(u),ze=va(t,fe,r,n,o,p===!0?i:null,a,`${je}/${be}`,ye);return Me.push(...ze.errors),ze.valid&&Ze.push(ye),ze.valid}).length;ne===1?Me.length=le:Me.splice(le,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:je,error:`Instance does not match exactly one subschema (${ne} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Ze),E!==void 0){let je=`${s}/if`;if(va(t,E,r,n,o,i,a,je,u).valid){if(P!==void 0){let ne=va(t,P,r,n,o,i,a,`${s}/then`,u);ne.valid||Me.push({instanceLocation:a,keyword:"if",keywordLocation:je,error:'Instance does not match "then" schema.'},...ne.errors)}}else if(T!==void 0){let ne=va(t,T,r,n,o,i,a,`${s}/else`,u);ne.valid||Me.push({instanceLocation:a,keyword:"if",keywordLocation:je,error:'Instance does not match "else" schema.'},...ne.errors)}}if(c==="object"){if(y!==void 0)for(let fe of y)fe in t||Me.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${fe}".`});let je=Object.keys(t);if(F!==void 0&&je.length<F&&Me.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${F} properties.`}),K!==void 0&&je.length>K&&Me.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${K} properties.`}),U!==void 0){let fe=`${s}/propertyNames`;for(let be in t){let ye=`${a}/${Th(be)}`,ze=va(be,U,r,n,o,i,ye,fe);ze.valid||Me.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:fe,error:`Property name "${be}" does not
2025-07-05 20:48:33 +08:00
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
2025-09-01 12:32:47 +08:00
`)),n.close()}});return Pf.fromReadableStream(r)}var PQe=b(()=>{xv()});function oSe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function ree(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*iSe(t,e){for(;;){let{value:r,done:n}=Ep.runWithConfig(Wg(t),e.next.bind(e),!0);if(n)break;yield r}}async function*nee(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Ep.runWithConfig(Wg(t),r.next.bind(e),!0);if(o)break;yield n}}var TQe,AQe=b(()=>{yj();vv();TQe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function ac(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function rPr(t){if(zX(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function _E(t){if(typeof t=="function")return new Tp({func:t});if(Un.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=_E(n);return new KA({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function nPr(t,e){let r=e.name??t.getName(),n=e.description??bj(e.schema);return nSe(e.schema)?new U6({name:r,description:n,schema:dt.object({input:dt.string()}).transform(o=>o.input),bound:t}):new U6({name:r,description:n,schema:e.schema,bound:t})}var aSe,Un,Ov,oee,z6,Li,KA,sSe,Tp,iee,LB,aee,U6,Tf=b(()=>{NX();aSe=j(LX(),1);ij();Lwe();uXe();cXe();cj();xv();lxe();vv();PB();fXe();dxe();yj();OQe();PQe();AQe();PQ();bE();Un=class extends ym{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 Ov({bound:this,kwargs:e,config:{}})}map(){return new oee({bound:this})}withRetry(e){return new z6({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Ov({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new iee({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(In);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)=>In(i===0?e:n))}return Array.from({length:r},()=>In(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new Ph({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=In(r),o=new gE({generator:this._streamIterator(e,n),config:n});return await o.setup,Pf.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=In(e):r=In({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=In(n),a=await(await vm(o))?.handleChainStart(this.toJSON(),ac(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 wv(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ac(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(vm)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),ac(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 wv(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(ac(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=In(n),l=await vm(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=jc(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await oXe(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(lXe),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let m=d?.handlers.find(sXe);m!==void 0&&d!==void 0&&(h=m.tapOutputIterable(d.runId,h));for await(let g of h)if(yield g
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-09-01 12:32:47 +08:00
${JSON.stringify(Cm(this.schema))}
2025-07-05 20:48:33 +08:00
\`\`\`
2025-09-01 12:32:47 +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 DB(this.schema,JSON.parse(n))}catch(r){throw new Mh(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var cSe=b(()=>{kwe()});var Cd,dSe=b(()=>{GA();cSe();K0e();Cd=class extends Cj{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?JX(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return W0e(e[0].text)}async parse(e){return W0e(e,JSON.parse)}getFormatInstructions(){return""}}});var kQe=b(()=>{});var $Qe=b(()=>{GA();cSe();kQe()});var BQe=b(()=>{FB();jQe();DQe();LQe();FQe();GA();dSe();$Qe()});var Db=b(()=>{BQe()});var q6,kB,$B,lee,H6=b(()=>{cj();C6();BA();q6=class extends ym{},kB=class extends q6{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 Xs(this.value)]}},$B=class extends q6{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 Op(this.messages)}toChatMessages(){return this.messages}},lee=class extends q6{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 Xs({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var vE,V6=b(()=>{H6();BB();vE=class extends Ev{async formatPromptValue(e){let r=await this.format(e);return new kB(r)}}});function pSe(t){return typeof t=="function"}function iPr(t){return UB(t)?"array":typeof t}function fSe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function zQe(t,e){return t!=null&&typeof t=="object"&&e in t}function aPr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function uPr(t,e){return sPr.call(t,e)}function cPr(t){return!uPr(lPr,t)}function fPr(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return dPr[r]})}function yPr(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 h(T){if(typeof T=="string"&&(T=T.split(mPr,2)),!UB(T)||T.length!==2)throw new Error("Invalid tags: "+T);d=new RegExp(fSe(T[0])+"\\s*"),f=new RegExp("\\s*"+fSe(T[1])),p=new RegExp("\\s*"+fSe("}"+T[1]))}h(e||Gg.tags);for(var m=new K6(t),g,y,_,w,S,C;!m.eos();){if(g=m.pos,_=m.scanUntil(d),_)for(var E=0,P=_.length;E<P;++E)w=_.charAt(E),cPr(w)?(i.push(o.length),u+=w):(s=!0,r=!0,u+=" "),o.push(["text",w,g,g+1]),g+=1,w===`
`&&(c(),u="",l=0,r=!1);if(!m.scan(d))break;if(a=!0,y=m.scan(gPr)||"name",m.scan(pPr),y==="="?(_=m.scanUntil(UQe),m.scan(UQe),m.scanUntil(f)):y==="{"?(_=m.scanUntil(p),m.scan(hPr),m.scanUntil(f),y="&"):_=m.scanUntil(f),!m.scan(f))throw new Error("Unclosed tag at "+m.pos);if(y==">"?S=[y,_,g,m.pos,u,l,r]:S=[y,_,g,m.pos],l++,o.push(S),y==="#"||y==="^")n.push(S);else if(y==="/"){if(C=n.pop(),!C)throw new Error('Unopened section "'+_+'" at '+g);if(C[1]!==_)throw new Error('Unclosed section "'+C[1]+'" at '+g)}else y==="name"||y==="{"||y==="&"?s=!0:y==="="&&h(_)}if(c(),C=n.pop(),C)throw new Error('Unclosed section "'+C[1]+'" at '+m.pos);return _Pr(bPr(o))}function bPr(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 _Pr(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 K6(t){this.string=t,this.tail=t,this.pos=0}function zB(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Ap(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var oPr,UB,sPr,lPr,dPr,pPr,mPr,UQe,hPr,gPr,Gg,W6,cee,qQe=b(()=>{oPr=Object.prototype.toString,UB=Array.isArray||function(e){return oPr.call(e)==="[object Array]"};sPr=RegExp.prototype.test;lPr=/\S/;dPr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};pPr=/\s*/,mPr=/\s+/,UQe=/\s*=/,hPr=/\s*\}/,gPr=/#|\^|\/|>|\{|&|=|!/;K6.prototype.eos=function(){return this.tail===""};K6.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};K6.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};zB.prototype.push=function(e){return new zB(e,this)};zB.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=zQe(i,a[s])||aPr(i,a[s])),i=i[a[s++]];else i=o.view[e],u=zQe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return pSe(n)&&(n=n.call(this.view)),n};Ap.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Ap.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Gg.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=yPr(e,r),i&&n.set(o,a)),a};Ap.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof zB?r:new zB(r,void 0);return this.renderTokens(a,s,n,e,o)};Ap.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};Ap.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(UB(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(pSe(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}};Ap.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||UB(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};Ap.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-09-01 12:32:47 +08:00
`)};Ap.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=pSe(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)}}};Ap.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Ap.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Gg.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Gg.escape?String(i):o(i)};Ap.prototype.rawValue=function(e){return e[1]};Ap.prototype.getConfigTags=function(e){return UB(e)?e:e&&typeof e=="object"?e.tags:void 0};Ap.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!UB(e))return e.escape};Gg={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){W6.templateCache=t},get templateCache(){return W6.templateCache}},W6=new Ap;Gg.clearCache=function(){return W6.clearCache()};Gg.parse=function(e,r){return W6.parse(e,r)};Gg.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+iPr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return W6.render(e,r,n,o)};Gg.escape=fPr;Gg.Scanner=K6;Gg.Context=zB;Gg.Writer=Ap;cee=Gg});function HQe(){cee.escape=t=>t}var G6,VQe,dee,vPr,wPr,mSe,xPr,Om,J6,Oj,Ej=b(()=>{qQe();w6();G6=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},VQe=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=VQe(r[4]);e.push(...n)}}else e.push({type:"literal",text:r[1]});return e},dee=t=>{HQe();let e=cee.parse(t);return VQe(e)},vPr=(t,e)=>G6(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},""),wPr=(t,e)=>(HQe(),cee.render(t,e)),mSe={"f-string":vPr,mustache:wPr},xPr={"f-string":G6,mustache:dee},Om=(t,e,r)=>{try{return mSe[e](t,r)}catch(n){throw kA(n,"INVALID_PROMPT_INPUT")}},J6=(t,e)=>xPr[e](t),Oj=(t,e,r)=>{if(!(e in mSe)){let n=Object.keys(mSe);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")Om(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Om(o.image_url,e,n);else{let i=o.image_url.url;Om(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Om(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var hSe={};os(hSe,{PromptTemplate:()=>Af});var Af,qB=b(()=>{V6();Ej();Af=class t extends vE{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))),Oj(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Om(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +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 J6(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 HB,gSe=b(()=>{H6();BB();Ej();HB=class t extends Ev{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))),Oj([{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]=Om(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 lee(r)}}});function ySe(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")J6(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?J6(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...ySe(o,e));else typeof n=="object"&&n!==null&&r.push(...ySe(n,e));return Array.from(new Set(r))}function bSe(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Om(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Om(s,r,e)):typeof s=="object"&&a.push(bSe(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=bSe(i,e,r):n[o]=i;return n}var Z6,_Se=b(()=>{Tf();Ej();Z6=class extends Un{static lc_name(){return"DictPromptTemplate"}constructor(e){let r=e.templateFormat??"f-string",n=ySe(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 bSe(this.template,e,this.templat
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},vSe=class extends Y6{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)]}},X6=class extends Ev{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let r=await this.formatMessages(e);return new $B(r)}},wSe=class extends vSe{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 Ys(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(Af.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};Q6=class extends Y6{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(Af.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(Af.fromTemplate(o,r));else if(o!==null)if(SPr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(Af.fromTemplate(i,a))}else if(CPr(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=dee(i):u=G6(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-09-01 12:32:47 +08:00
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new HB({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=dee(i.url):u=G6(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new HB({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 Z6({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof vE){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 vE){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof HB){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 Z6){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)]}},Tv=class extends Q6{static _messageClass(){return Xs}static lc_name(){return"HumanMessagePromptTemplate"}},xSe=class extends Q6{static _messageClass(){return kn}static lc_name(){return"AIMessagePromptTemplate"}},JA=class extends Q6{static _messageClass(){return hE}static lc_name(){return"SystemMessagePromptTemplate"}};Em=class t extends X6{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 oc))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 Af.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 oc)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(PPr(o)&&o.optional))throw kA(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=Af.fromTemplate(e,r),o=new Tv({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[EPr(s,r)]),[
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +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))),Oj(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 Om(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 Af.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})}},CSe=class t extends X6{_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-09-01 12:32:47 +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))),Oj(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 Om(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 Ev,BB=b(()=>{Tf();Ev=class extends Un{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(()=>(qB(),hSe));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(qB(),hSe));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(OSe(),WQe));return r.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var KQe=b(()=>{BB();e8()});var GQe=b(()=>{});var JQe=b(()=>{Tf();e8()});var ZQe=b(()=>{BB();e8();OSe();KQe();qB();GQe();V6();Ej();gSe();JQe();_Se()});var ZA=b(()=>{ZQe()});var Pm=b(()=>{lSe()});var ESe,PSe=b(()=>{ESe=t=>t.map(e=>e.pageContent).join(`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
`)});var YQe=b(()=>{PSe()});function Rh(t,e){let r=`atom${++TPr}`,n={toString(){return($a.env?$a.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=APr,n.write=IPr),e&&(n.write=e),n}function APr(t){return t(this)}function IPr(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var $a,TPr,XQe,TSe,ASe,pee,MSe,MPr,RPr,RSe,QQe,fee,ret,eet,VB,ISe,NPr,jPr,tet,YA,net,WB,t8,oet,NSe=b(()=>{$a={},TPr=0;XQe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,TSe=t=>"init"in t,ASe=t=>!!t.write,pee=new WeakMap,MSe=t=>{var e;return RSe(t)&&!((e=pee.get(t))!=null&&e[1])},MPr=(t,e)=>{let r=pee.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if(($a.env?$a.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},RPr=t=>{if(pee.has(t))return;let e=[new Set,!1];pee.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},RSe=t=>typeof t?.then=="function",QQe=t=>"v"in t||"e"in t,fee=t=>{if("e"in t)throw t.e;if(($a.env?$a.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},ret=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},eet=(t,e,r,n,o)=>{var i;if(($a.env?$a.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),MSe(r.v)&&ret(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&NPr(t,n,e)},VB=()=>[new Map,new Map,new Set],ISe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},NPr=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},jPr=(t,e)=>t[0].get(e),tet=(t,e)=>{t[2].add(e)},YA=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},net=(...[t,e,r,n])=>{let o;($a.env?$a.env.MODE:void 0)!=="production"&&(o=new Set);let i=(w,S,C)=>{let E="v"in S,P=S.v,T=MSe(S.v)?S.v:null;if(RSe(C)){RPr(C);for(let I of S.d.keys())ret(w,C,t(I));S.v=C,delete S.e}else S.v=C,delete S.e;(!E||!Object.is(P,S.v))&&(++S.n,T&&MPr(T,C))},a=(w,S,C)=>{var E;let P=t(S);if(QQe(P)&&(P.m&&!C?.has(S)||Array.from(P.d).every(([k,F])=>a(w,k,C).n===F)))return P;P.d.clear();let T=!0,I=k=>{if(XQe(S,k)){let K=t(k);if(!QQe(K))if(TSe(k))i(k,K,k.init);else throw new Error("no atom init");return fee(K)}let F=a(w,k,C);try{return fee(F)}finally{if(T)eet(w,S,P,k,F);else{let K=VB();eet(K,S,P,k,F),p(K,S,P),YA(K)}}},N,M,D={get signal(){return N||(N=new AbortController),N.signal},get setSelf(){return($a.env?$a.env.MODE:void 0)!=="production"&&!ASe(S)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&ASe(S)&&(M=(...k)=>{if(($a.env?$a.env.MODE:void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)return f(S,...k)}),M}};try{let k=e(S,I,D);if(i(S,P,k),RSe(k)){(E=k.onCancel)==null||E.call(k,()=>N?.abort());let F=()=>{if(P.m){let K=VB();p(K,S,P),YA(K)}};k.then(F,F)}return P}catch(k){return delete P.v,P.e=k,++P.n,P}finally{T=!1}},s=w=>fee(a(void 0,w)),u=(w,S,C)=>{var E,P;let T=new Map;for(let I of((E=C.m)==null?void 0:E.t)||[])T.set(I,t(I));for(let I of C.p)T.set(I,t(I));return(P=jPr(w,S))==null||P.forEach(I=>{T.set(I,t(I))}),T};function l(w,S,C){let E=[],P=new Set,T=new Set,I=[[S,C]];for(;I.length>0;){let[N,M]=I[I.length-1];if(T.has(N)){I.pop();continue}if(P.has(N)){E.push([N,M,M.n]),T.add(N),I.pop();continue}P.add(N);for(let[D,k]of u(w,N,M))N!==D&&!P.has(D)&&I.push([D,k])}return[E,T]}let c=(w,S,C)=>{let[E,P]=l(w,S,C),T=new Set([S]);for(let I=E.length-1;I>=0;--I){let[N,M,D]=E[I],k=!1;for(let F of M.d.keys())if(F!==N&&T.has(F)){k=!0;break}k&&(a(w,N,P),p(w,N,M),D!==M.n&&(ISe(w,N,M),T.add(N))),P.delete(N)}},d=(w,S,...C)=>{let E=!0,P=I=>fee(a(w,I)),T=(I,...N)=>{let M=t(I);try{if(XQe(S,I)){if(!TSe(I))throw new Error("atom not writable");let D=M.n,k=N[0];i(I,M,k),p(w,I,M),D!==M.n&&(ISe(w,I,M),c(w,I,M));return}else return d(w,I,...N)}finally{E||YA(w)}};try{return r(S,P,T,...C)}finally{E=!1}},f=(w,...S)=>{l
2025-07-05 20:48:33 +08:00
<user_custom_instructions>
${t}
2025-09-01 12:32:47 +08:00
</user_custom_instructions>`:e}function QPr(t){return t.activeModels=xet(t.activeModels,Av),t.activeEmbeddingModels=xet(t.activeEmbeddingModels,Pj),t}function tn(t){return`${t.name}|${t.provider}`}function xet(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(tn(n),{...n})}),t.forEach(n=>{let o=tn(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 Ki,XA,bt=b(()=>{o8();zN();or();Ki=WB(),XA=Rh(bu)});function B(...t){oe().debug&&console.log(...t)}function ie(...t){oe().debug&&console.error(...t)}function Bt(...t){oe().debug&&console.warn(...t)}var Gt=b(()=>{bt()});var Oet=x((qSe,JB)=>{(function(t,e){typeof qSe=="object"&&typeof JB<"u"?JB.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(qSe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(v){t=v}function n(v){return v instanceof Array||Object.prototype.toString.call(v)==="[object Array]"}function o(v){return v!=null&&Object.prototype.toString.call(v)==="[object Object]"}function i(v,O){return Object.prototype.hasOwnProperty.call(v,O)}function a(v){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(v).length===0;var O;for(O in v)if(i(v,O))return!1;return!0}function s(v){return v===void 0}function u(v){return typeof v=="number"||Object.prototype.toString.call(v)==="[object Number]"}function l(v){return v instanceof Date||Object.prototype.toString.call(v)==="[object Date]"}function c(v,O){var A=[],R,$=v.length;for(R=0;R<$;++R)A.push(O(v[R],R));return A}function d(v,O){for(var A in O)i(O,A)&&(v[A]=O[A]);return i(O,"toString")&&(v.toString=O.toString),i(O,"valueOf")&&(v.valueOf=O.valueOf),v}function f(v,O,A,R){return QKe(v,O,A,R,!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 h(v){return v._pf==null&&(v._pf=p()),v._pf}var m;Array.prototype.some?m=Array.prototype.some:m=function(v){var O=Object(this),A=O.length>>>0,R;for(R=0;R<A;R++)if(R in O&&v.call(this,O[R],R,O))return!0;return!1};function g(v){if(v._isValid==null){var O=h(v),A=m.call(O.parsedDateParts,function($){return $!=null}),R=!isNaN(v._d.getTime())&&O.overflow<0&&!O.empty&&!O.invalidEra&&!O.invalidMonth&&!O.invalidWeekday&&!O.weekdayMismatch&&!O.nullInput&&!O.invalidFormat&&!O.userInvalidated&&(!O.meridiem||O.meridiem&&A);if(v._strict&&(R=R&&O.charsLeftOver===0&&O.unusedTokens.length===0&&O.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(v))v._isValid=R;else return R}return v._isValid}function y(v){var O=f(NaN);return v!=null?d(h(O),v):h(O).userInvalidated=!0,O}var _=e.momentProperties=[],w=!1;function S(v,O){var A,R,$,te=_.length;if(s(O._isAMomentObject)||(v._isAMomentObject=O._isAMomentObject),s(O._i)||(v._i=O._i),s(O._f)||(v._f=O._f),s(O._l)||(v._l=O._l),s(O._strict)||(v._strict=O._strict),s(O._tzm)||(v._tzm=O._tzm),s(O._isUTC)||(v._isUTC=O._isUTC),s(O._offset)||(v._offset=O._offset),s(O._pf)||(v._pf=h(O)),s(O._locale)||(v._locale=O._locale),te>0)for(A=0;A<te;A++)R=_[A],$=O[R],s($)||(v[R]=$);return v}function C(v){S(this,v),this._d=new Date(v._d!=null?v._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),w===!1&&(w=!0,e.updateOffset(this),w=!1)}function E(v){return v instanceof C||v!=null&&v._isAMomentObject!=null}function P(v){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+v)}function T(v,O){var A=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,v),A){var R=[],$,te,we,pr=arguments.length;for(te=0;te<pr;te++){if($="",typeof arguments[te]=="object"){$+=`
2025-08-30 08:29:39 +08:00
[`+te+"] ";for(we in arguments[0])i(arguments[0],we)&&($+=we+": "+arguments[0][we]+", ");$=$.slice(0,-2)}else $=arguments[te];R.push($)}P(v+`
Arguments: `+Array.prototype.slice.call(R).join("")+`
2025-09-01 12:32:47 +08:00
`+new Error().stack),A=!1}return O.apply(this,arguments)},O)}var I={};function N(v,O){e.deprecationHandler!=null&&e.deprecationHandler(v,O),I[v]||(P(O),I[v]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function M(v){return typeof Function<"u"&&v instanceof Function||Object.prototype.toString.call(v)==="[object Function]"}function D(v){var O,A;for(A in v)i(v,A)&&(O=v[A],M(O)?this[A]=O:this["_"+A]=O);this._config=v,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function k(v,O){var A=d({},v),R;for(R in O)i(O,R)&&(o(v[R])&&o(O[R])?(A[R]={},d(A[R],v[R]),d(A[R],O[R])):O[R]!=null?A[R]=O[R]:delete A[R]);for(R in v)i(v,R)&&!i(O,R)&&o(v[R])&&(A[R]=d({},A[R]));return A}function F(v){v!=null&&this.set(v)}var K;Object.keys?K=Object.keys:K=function(v){var O,A=[];for(O in v)i(v,O)&&A.push(O);return A};var U={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function X(v,O,A){var R=this._calendar[v]||this._calendar.sameElse;return M(R)?R.call(O,A):R}function ee(v,O,A){var R=""+Math.abs(v),$=O-R.length,te=v>=0;return(te?A?"+":"":"-")+Math.pow(10,Math.max(0,$)).toString().substr(1)+R}var L=/(\[[^\[]*\])|(\\)?([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,Q=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,z={},W={};function V(v,O,A,R){var $=R;typeof R=="string"&&($=function(){return this[R]()}),v&&(W[v]=$),O&&(W[O[0]]=function(){return ee($.apply(this,arguments),O[1],O[2])}),A&&(W[A]=function(){return this.localeData().ordinal($.apply(this,arguments),v)})}function q(v){return v.match(/\[[\s\S]/)?v.replace(/^\[|\]$/g,""):v.replace(/\\/g,"")}function H(v){var O=v.match(L),A,R;for(A=0,R=O.length;A<R;A++)W[O[A]]?O[A]=W[O[A]]:O[A]=q(O[A]);return function($){var te="",we;for(we=0;we<R;we++)te+=M(O[we])?O[we].call($,v):O[we];return te}}function G(v,O){return v.isValid()?(O=Z(O,v.localeData()),z[O]=z[O]||H(O),z[O](v)):v.localeData().invalidDate()}function Z(v,O){var A=5;function R($){return O.longDateFormat($)||$}for(Q.lastIndex=0;A>=0&&Q.test(v);)v=v.replace(Q,R),Q.lastIndex=0,A-=1;return v}var de={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 pe(v){var O=this._longDateFormat[v],A=this._longDateFormat[v.toUpperCase()];return O||!A?O:(this._longDateFormat[v]=A.match(L).map(function(R){return R==="MMMM"||R==="MM"||R==="DD"||R==="dddd"?R.slice(1):R}).join(""),this._longDateFormat[v])}var ae="Invalid date";function Te(){return this._invalidDate}var Ae="%d",ke=/\d{1,2}/;function Ot(v){return this._ordinal.replace("%d",v)}var jr={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 Mr(v,O,A,R){var $=this._relativeTime[A];return M($)?$(v,O,A,R):$.replace(/%d/i,v)}function Vn(v,O){var A=this._relativeTime[v>0?"future":"past"];return M(A)?A(O):A.replace(/%s/i,O)}var Xr={};function Cr(v,O){var A=v.toLowerCase();Xr[A]=Xr[A+"s"]=Xr[O]=v}function Me(v){return typeof v=="string"?Xr[v]||Xr[v.toLowerCase()]:void 0}function Ze(v){var O={},A,R;for(R in v)i(v,R)&&(A=Me(R),A&&(O[A]=v[R]));return O}var je={};function le(v,O){je[v]=O}function ne(v){var O=[],A;for(A in v)i(v,A)&&O.push({unit:A,priority:je[A]});return O.sort(function(R,$){return R.priority-$.priority}),O}function fe(v){return v%4===0&&v%100!==0||v%400===0}function be(v){return v<0?Math.ceil(v)||0:Math.floor(v)}function ye(v){var O=+v,A=0;return O!==0&&isFinite(O)&&(A=be(O)),A}function ze(v,O){return function(A){return A!=null?(Ii(this,v,A),e.updateOffset(this,O),this):hr(this,v)}}function hr(v,O){return v.isValid()?v._d["get"+(v._isUTC?"UTC":"")+O]():NaN}function Ii(v,O,A){v.isValid()&&!isNaN(A)&&(O==="FullYear"&&fe(v.ye
2025-07-05 20:48:33 +08:00
${t?.cause?"more message: "+t.cause.message:""}
2025-09-01 12:32:47 +08:00
${e?t.stack:""}`:JSON.stringify(t)}function s8(t,e){let r={...t};return e.forEach(n=>{delete r[n]}),r}function vee(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 SE(t){let e=rz[t];return{...e,label:e.label||t}}function Mp(t,e){let r=rz[t]?.label||t;return r+(e?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}function wee(t){let e=t;return e=Aj(e),e=e.replace(/```xml\s*[\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?```/g,""),e=e.replace(/<writeToFile>[\s\S]*?<\/writeToFile>/g,""),e=e.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,""),e=e.replace(/\n{3,}/g,`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`),e=e.trim(),e}async function u8(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new Nh.Notice("No active leaf found.");return}if(r.view instanceof Nh.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof Nh.MarkdownView)){new Nh.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=wee(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new Nh.Notice("Message inserted into the active note.")}function xee(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function See(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 Det(){try{return{version:(await(0,Nh.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 l8(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 oTr(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function ez(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=l8(e),n=oTr(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function eI(t,e="system"){return l8(t)?"human":e}function QSe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(rz).filter(([e])=>!t.includes(e)).map(([e])=>e)}function tz(t,e){let r=!!QSe().find(i=>i===t.provider),n=OE[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 iTr(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function Aj(t){let r=iTr(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function Let(){return crypto.randomUUID()}async function Od(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}}async function Cee(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(xE(),Eet)),o=new AbortController,i=setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((a,s)=>{o.signal.addEventListener("abort",()=>{s(new n(r,e))})})])}finally{clearTimeout(i)}}function eCe(){let t=app.workspace.getActiveViewOfType(Nh.MarkdownView);return t?t.getState().source===!0:!0}var WSe,Nh,HSe,KSe,tTr,rTr,Iet,tu,YSe,ir=b(()=>{vu();or();Gt();WSe=j(Oet()),Nh=require("obsidian"),HSe={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}`};KSe=(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})};tTr=t=>t.last.bound.modelName||t.last.bound.model,rTr=t=>t.last.bound.retriever!==void 0,Iet=t=>tTr(t)||rTr(t),tu=(t,e="local")=>{let r=(0,WSe.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};YSe=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var nz,tCe,c8,vu=b(()=>{Db();ZA();Pm();YQe();ir();nz=class nz{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.bind({signal:i?.signal}),s=Li.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return nz.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=nz.instances.get("llm_chain");return r||(r=nz.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=Af.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-09-01 12:32:47 +08:00
Standalone question:`),c=Af.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}
2025-08-30 08:29:39 +08:00
`),d=g=>g.map(_=>`Human: ${_[0]}
Assistant: ${_[1]}`).join(`
2025-09-01 12:32:47 +08:00
`),f=Li.from([{question:g=>(n&&console.log("Input Question: ",g.question),g.question),chat_history:g=>{let y=d(g.chat_history);return n&&console.log("Formatted Chat History: ",y),y}},u,o,new uee,g=>{let y=Aj(g);return n&&console.log("Standalone Question: ",y),y}]),p=async g=>(r(g),ESe(g)),h=Li.from([{context:i.pipe(p),question:new Lo,system_message:()=>a},c,o]);return f.pipe(h)}};nz.instances=new Map;tCe=nz,c8=tCe});var d8=b(()=>{});var tI,Ns,Fo,Zg,Fet,ket,Cet,Bet,f8,Tm,p8,Ij,m8,rCe,Mj,nCe,oCe,oz,Iv,EE,Rf,CE,rI,Av,QA,Pj,VSe,rz,OE,zet,pn,Oee,Yg,iz,bu,Xg,or=b(()=>{zN();vu();d8();tI="https://api.brevilabs.com/v1",Ns="copilot-chat-view",Fo="user",Zg="ai",Fet="copilot-conversations",ket="copilot-custom-prompts",Cet=`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 \` \`.
2025-08-30 08:29:39 +08:00
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
2025-07-05 20:48:33 +08:00
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-30 08:29:39 +08:00
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
2025-09-01 12:32:47 +08:00
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.`,Bet=`Return the new note content or canvas JSON in <writeToFile> tags.
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.
2025-08-30 08:29:39 +08:00
# Examples
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Input: Add a new section to note A
Output:
<writeToFile>
<path>path/to/file.md</path>
<content>The FULL CONTENT of the note A with added section goes here</content>
</writeToFile>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Input: Create a new canvas with "Hello, world!"
Output:
<writeToFile>
<path>path/to/file.canvas</path>
<content>
2025-07-05 20:48:33 +08:00
{
2025-08-30 08:29:39 +08:00
"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"
}
]
2025-07-05 20:48:33 +08:00
}
2025-08-30 08:29:39 +08:00
</content>
</writeToFile>
2025-07-05 20:48:33 +08:00
# Important
2025-08-30 08:29:39 +08:00
# The content within the <content> tags for canvas files is in JSON format.
2025-07-05 20:48:33 +08:00
* For canvas files, both 'nodes' and 'edges' arrays must be properly closed with ]
* 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
2025-08-30 08:29:39 +08:00
* When generating changes on multiple files, output multiple <writeToFile> tags
2025-07-05 20:48:33 +08:00
* 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-30 08:29:39 +08:00
- Edge fromNode and toNode must reference existing node IDs.
2025-09-01 12:32:47 +08:00
`,f8="note_context",Tm="selected_text",p8="variable",Ij="variable_note",m8="embedded_pdf",rCe="retrieved_document",Mj=6e3,nCe=.4,oCe=448e3,oz=3e4,Iv={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},EE={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Rf={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},CE=(h=>(h.OPENAI="openai",h.OPENAI_FORMAT="3rd party (openai-format)",h.AZURE_OPENAI="azure openai",h.ANTHROPIC="anthropic",h.COHEREAI="cohereai",h.GOOGLE="google",h.XAI="xai",h.OPENROUTERAI="openrouterai",h.GROQ="groq",h.OLLAMA="ollama",h.LM_STUDIO="lm-studio",h.COPILOT_PLUS="copilot-plus",h.MISTRAL="mistralai",h.DEEPSEEK="deepseek",h))(CE||{}),rI={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Av=[{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",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-flash-lite",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"]}],QA=(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))(QA||{}),Pj=[{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,isBuiltI
`+NCe+t}var jCe=!1;function DCe(t,e){if(!t||jCe)return"";jCe=!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-09-01 12:32:47 +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{jCe=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?A8(t):""}function WTr(t){switch(t.tag){case 5:return A8(t.type);case 16:return A8("Lazy");case 13:return A8("Suspense");case 19:return A8("SuspenseList");case 0:case 2:case 15:return t=DCe(t.type,!1),t;case 11:return t=DCe(t.type.render,!1),t;case 1:return t=DCe(t.type,!0),t;default:return""}}function iOe(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 mz:return"Fragment";case pz:return"Portal";case rOe:return"Profiler";case ZOe:return"StrictMode";case nOe:return"Suspense";case oOe:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case qrt:return(t.displayName||"Context")+".Consumer";case Urt:return(t._context.displayName||"Context")+".Provider";case YOe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case XOe:return e=t.displayName||null,e!==null?e:iOe(t.type)||"Memo";case sI:e=t._payload,t=t._init;try{return iOe(t(e))}catch{}}return null}function KTr(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 iOe(e);case 8:return e===ZOe?"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 wI(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Vrt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function GTr(t){var e=Vrt(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 Hee(t){t._valueTracker||(t._valueTracker=GTr(t))}function Wrt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=Vrt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function bte(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 aOe(t,e){var r=e.checked;return us({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function Ftt(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=wI(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 Krt(t,e){e=e.checked,e!=null&&JOe(t,"checked",e,!1)}function sOe(t,e){Krt(t,e);var r=wI(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")?uOe(t,e.type,r):e.hasOwnProperty("defaultValue")&&uOe(t,e.type,wI(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function
`).replace(rIr,"")}function rte(t,e,r){if(e=urt(e),urt(t)!==e&&r)throw Error(We(425))}function Ete(){}var xOe=null,SOe=null;function COe(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 OOe=typeof setTimeout=="function"?setTimeout:void 0,nIr=typeof clearTimeout=="function"?clearTimeout:void 0,lrt=typeof Promise=="function"?Promise:void 0,oIr=typeof queueMicrotask=="function"?queueMicrotask:typeof lrt<"u"?function(t){return lrt.resolve(null).then(t).catch(iIr)}:OOe;function iIr(t){setTimeout(function(){throw t})}function VCe(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),K8(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);K8(e)}function gI(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 crt(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 $z=Math.random().toString(36).slice(2),Fv="__reactFiber$"+$z,X8="__reactProps$"+$z,DE="__reactContainer$"+$z,EOe="__reactEvents$"+$z,aIr="__reactListeners$"+$z,sIr="__reactHandles$"+$z;function Uj(t){var e=t[Fv];if(e)return e;for(var r=t.parentNode;r;){if(e=r[DE]||r[Fv]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=crt(t);t!==null;){if(r=t[Fv])return r;t=crt(t)}return e}t=r,r=t.parentNode}return null}function s5(t){return t=t[Fv]||t[DE],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function bz(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(We(33))}function Wte(t){return t[X8]||null}var POe=[],_z=-1;function CI(t){return{current:t}}function Sa(t){0>_z||(t.current=POe[_z],POe[_z]=null,_z--)}function ca(t,e){_z++,POe[_z]=t.current,t.current=e}var xI={},Ff=CI(xI),Nm=CI(!1),Kj=xI;function Rz(t,e){var r=t.type.contextTypes;if(!r)return xI;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 jm(t){return t=t.childContextTypes,t!=null}function Pte(){Sa(Nm),Sa(Ff)}function drt(t,e,r){if(Ff.current!==xI)throw Error(We(168));ca(Ff,e),ca(Nm,r)}function Dnt(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(We(108,KTr(t)||"Unknown",o));return us({},r,n)}function Tte(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||xI,Kj=Ff.current,ca(Ff,t),ca(Nm,Nm.current),!0}function frt(t,e,r){var n=t.stateNode;if(!n)throw Error(We(169));r?(t=Dnt(t,e,Kj),n.__reactInternalMemoizedMergedChildContext=t,Sa(Nm),Sa(Ff),ca(Ff,t)):Sa(Nm),ca(Nm,r)}var IE=null,Kte=!1,WCe=!1;function Lnt(t){IE===null?IE=[t]:IE.push(t)}function uIr(t){Kte=!0,Lnt(t)}function OI(){if(!WCe&&IE!==null){WCe=!0;var t=0,e=Fi;try{var r=IE;for(Fi=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}IE=null,Kte=!1}catch(o){throw IE!==null&&(IE=IE.slice(t+1)),snt(eEe,OI),o}finally{Fi=e,WCe=!1}}return null}var vz=[],wz=0,Ate=null,Ite=0,ry=[],ny=0,Gj=null,ME=1,RE="";function Bj(t,e){vz[wz++]=Ite,vz[wz++]=Ate,Ate=t,Ite=e}function Fnt(t,e,r){ry[ny++]=ME,ry[ny++]=RE,ry[ny++]=Gj,Gj=t;var n=ME;t=RE;var o=32-zb(n)-1;n&=~(1<<o),r+=1;var i=32-zb(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,ME=1<<32-zb(e)+o|r<<o|n,RE=i+t}else ME=1<<i|r<<o|n,RE=t}function lEe(t){t.return!==null&&(Bj(t,1),Fnt(t,1,0))}function cEe(t){for(;t===Ate;)Ate=vz[--wz],vz[wz]=null,Ite=vz[--wz],vz[wz]=null;for(;t===Gj;)Gj=ry[--ny],ry[ny]=null,RE=ry[--ny],ry[ny]=null,ME=ry[--ny],ry[ny]=null}var Fh=null,Lh=null,Ba=!1,Bb=null;function knt(t,e){var r=oy(5,null,n
2025-07-05 20:48:33 +08:00
Error generating stack: `+i.message+`
2025-09-01 12:32:47 +08:00
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function YCe(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function NOe(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var yIr=typeof WeakMap=="function"?WeakMap:Map;function fot(t,e,r){r=NE(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){kte||(kte=!0,qOe=n),NOe(t,e)},r}function pot(t,e,r){r=NE(-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(){NOe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){NOe(t,e),typeof n!="function"&&(bI===null?bI=new Set([this]):bI.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function xrt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new yIr;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=MIr.bind(null,t,e,r),e.then(t,t))}function Srt(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 Crt(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=NE(-1,1),e.tag=2,yI(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var bIr=kE.ReactCurrentOwner,Rm=!1;function Np(t,e,r,n){e.child=t===null?Vnt(e,null,r,n):jz(e,t.child,r,n)}function Ort(t,e,r,n,o){r=r.render;var i=e.ref;return Az(e,o),n=wEe(t,e,r,n,i,o),r=xEe(),t!==null&&!Rm?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,FE(t,e,o)):(Ba&&r&&lEe(e),e.flags|=1,Np(t,e,n,o),e.child)}function Ert(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!REe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,mot(t,e,i,n,o)):(t=yte(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:J8,r(a,n)&&t.ref===e.ref)return FE(t,e,o)}return e.flags|=1,t=vI(i,n),t.ref=e.ref,t.return=e,e.child=t}function mot(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(J8(i,n)&&t.ref===e.ref)if(Rm=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Rm=!0);else return e.lanes=t.lanes,FE(t,e,o)}return jOe(t,e,r,n,o)}function hot(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},ca(Cz,Dh),Dh|=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,ca(Cz,Dh),Dh|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,ca(Cz,Dh),Dh|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,ca(Cz,Dh),Dh|=n;return Np(t,e,o,r),e.child}function got(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function jOe(t,e,r,n,o){var i=jm(r)?Kj:Ff.current;return i=Rz(e,i),Az(e,o),r=wEe(t,e,r,n,i,o),n=xEe(),t!==null&&!Rm?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,FE(t,e,o)):(Ba&&n&&lEe(e),e.flags|=1,Np(t,e,r,o),e.child)}function Prt(t,e,r,n,o){if(jm(r)){var i=!0;Tte(e)}else i=!1;if(Az(e,o),e.stateNode===null)mte(t,e),qnt(e,r,n),ROe(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=ay(l):(l=jm(r)?Kj:Ff.current,l=Rz(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)&&brt(e,a,n,l),uI=!1;var f=e.memoizedState;a.state=f,Nte(e,n,a,o),u=e.memoizedState,s!==n||f!==u||Nm.current||uI?(typeof c=="function"&&(MOe(e,r,c,n),u=e.memoizedState),(s=uI||yrt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!=
`)}});var fmt=x(Vre=>{"use strict";Object.defineProperty(Vre,"__esModule",{value:!0});Vre.CohereTimeoutError=void 0;var tPe=class t extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,t.prototype)}};Vre.CohereTimeoutError=tPe});var ou=x(Zz=>{"use strict";Object.defineProperty(Zz,"__esModule",{value:!0});Zz.CohereTimeoutError=Zz.CohereError=void 0;var pRr=dmt();Object.defineProperty(Zz,"CohereError",{enumerable:!0,get:function(){return pRr.CohereError}});var mRr=fmt();Object.defineProperty(Zz,"CohereTimeoutError",{enumerable:!0,get:function(){return mRr.CohereTimeoutError}})});var pmt=x(Kv=>{"use strict";var hRr=Kv&&Kv.__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]}),gRr=Kv&&Kv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yRr=Kv&&Kv.__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)&&hRr(e,t,r);return gRr(e,t),e};Object.defineProperty(Kv,"__esModule",{value:!0});Kv.BadRequestError=void 0;var bRr=yRr(ou()),rPe=class t extends bRr.CohereError{constructor(e){super({message:"BadRequestError",statusCode:400,body:e}),Object.setPrototypeOf(this,t.prototype)}};Kv.BadRequestError=rPe});var mmt=x(Gv=>{"use strict";var _Rr=Gv&&Gv.__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]}),vRr=Gv&&Gv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wRr=Gv&&Gv.__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)&&_Rr(e,t,r);return vRr(e,t),e};Object.defineProperty(Gv,"__esModule",{value:!0});Gv.UnauthorizedError=void 0;var xRr=wRr(ou()),nPe=class t extends xRr.CohereError{constructor(e){super({message:"UnauthorizedError",statusCode:401,body:e}),Object.setPrototypeOf(this,t.prototype)}};Gv.UnauthorizedError=nPe});var hmt=x(Jv=>{"use strict";var SRr=Jv&&Jv.__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]}),CRr=Jv&&Jv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ORr=Jv&&Jv.__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)&&SRr(e,t,r);return CRr(e,t),e};Object.defineProperty(Jv,"__esModule",{value:!0});Jv.ForbiddenError=void 0;var ERr=ORr(ou()),oPe=class t extends ERr.CohereError{constructor(e){super({message:"ForbiddenError",statusCode:403,body:e}),Object.setPrototypeOf(this,t.prototype)}};Jv.ForbiddenError=oPe});var gmt=x(Zv=>{"use strict";var PRr=Zv&&Zv.__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]}),TRr=Zv&&Zv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ARr=Zv&&Zv.__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)&&PRr(e,t,
`));return r(o)}});var qbt,xNr,SNr,CNr,ONr,ENr,Hbt=b(()=>{qbt=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),ENr(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ONr(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},xNr=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,SNr=/(\d+\.){3}\d+/,CNr=/\.\./,ONr=t=>xNr.test(t)&&!SNr.test(t)&&!CNr.test(t),ENr=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 Vbt=b(()=>{Hbt()});var Wbt,Kbt=b(()=>{Wbt=(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 Gbt,Jbt=b(()=>{Gbt=async t=>{}});function Zbt(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 Ybt=b(()=>{});var BI,Nne=b(()=>{Ybt();BI=t=>{if(typeof t=="string")return BI(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=Zbt(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var jne,Dne=b(()=>{Nne();jne=t=>typeof t=="object"?"url"in t?BI(t.url):t:BI(t)});var Xbt,PNr,ZPe=b(()=>{Vbt();Kbt();Jbt();Dne();Xbt=async(t,e,r,n)=>{if(!r.endpoint){let a=await Gbt(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(jne(a)))}let o=await PNr(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},PNr=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 Wbt(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 qbt(n),n}});var Qbt=b(()=>{ZPe();Dne()});var e_t,YPe=b(()=>{Jb();ZPe();e_t=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await Xbt(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=aw(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 t_t,XPe=b(()=>{t_t=(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 r_t,QPe=b(()=>{r_t=(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 zt(t,e,r){return{applyToStack:n=>{n.add(t_t(t,r),TNr),n.add(r_t(t,e),W5)}}}var TNr,W5,n_t=b(()=>{XPe();QPe();TNr={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},W5={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var Co=b(()=>{XPe();n_t();QPe()});var eTe,Ut,o_t=b(()=>{Co();YPe();eTe={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:W5.name},Ut=(t,e)=>({applyToStack:r=>{r.addRelativeTo(e_t({config:t,instructions:e}),eTe)}})});var Lne,i_t=b(()=>{Jb();Dne();Lne=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>jne(await Bf(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:Bf(t.useDualstackEndpoint??!1),useFipsEndpoint:Bf(t.useFipsEndpoint??!1)}}});var a_t=b(()=>{});var mo=b(()=>{Qbt();YPe();o_t();i_t();a_t()});var ANr,Fne,s_t=b(()=>{mo();Rne();ANr={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:eTe.name},Fne=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(JPe(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),ANr)}})});var OSo,u_t=b(()=>{Co();Rne();OSo={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:W5.name}});var l_t=b(()=>{Rne();s_t();u_t()});var c_t=b(()=>{});var d_t=b(()=>{c_t()});var f_t=b(()=>{Su()});var p_t=b(()=>{});var m_t=b(()=>{});function INr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var yD,h_t=b(()=>{yD=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=INr(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 g_t=b(()=>{});var y_t=b(()=>{});var b_t=b(()=>{});var K5=b(()=>{d_t();f_t();p_t();m_t();h_t();g_t();y_t();b_t()});var MNr,RNr,__t,tTe=b(()=>{K5();Su();Jb();MNr=t=>e=>{throw e},RNr=(t,e)=>{},__t=t=>(e,r)=>async n=>{if(!yD.isInstance(n.request))return e(n);let i=aw(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||MNr)(a));return(u.successHandler||RNr)(l.response,a),l}});var Zb,sw,G5,kne=b(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Zb||(Zb={}));sw=3,G5=Zb.STANDARD});var v_t,w_t,x_t,S_t,C_t=b(()=>{v_t=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],w_t=["TimeoutError","RequestTimeout","RequestTimeoutException"],x_t=[500,502,503,504],S_t=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var NNr,rU,$ne,O_t,J5=b(()=>{C_t();NNr=t=>t.$metadata?.clockSkewCorrected,rU=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 VI(i);if(o==="hex")return Ivt(i);if(o===void 0||o==="utf8"||o==="utf-8")return Kne(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(Rvt);if(e=!0,Nvt(t))return n(t);if(vTe(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},Nvt=t=>typeof Blob=="function"&&t instanceof Blob});var Lvt=b(()=>{});var Fvt=b(()=>{});var xTe=b(()=>{yTe();dvt();Dvt();Lvt();Fvt();wTe()});var KI,kvt=b(()=>{xTe();KI=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return XE.mutate(t);if(!t)return XE.mutate(new Uint8Array);let r=e.streamCollector(t);return XE.mutate(await r)}});var Mt,STe,$vt=b(()=>{cTe();Su();Mt=class{constructor(){this.middlewareStack=aU()}static classBuilder(){return new STe}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let g of o.bind(this)(d,e,r,n))this.middlewareStack.use(g);let f=e.concat(this.middlewareStack),{logger:p}=r,h={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[eU]:{commandInstance:this,...l},...c},{requestHandler:m}=r;return f.resolve(g=>m.handle(g.request,n||{}),h)}},STe=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 Mt{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 Jne,Bvt=b(()=>{Jne="***SensitiveInformation***"});var Zne,zvt=b(()=>{Zne=(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 SD,BNr,Uvt,zNr,qvt,Hvt,Vvt,CTe,UNr,lU,Mn,Wvt,Kvt,qNr,eW,tW,OTe,Gvt,Jvt,Zvt,ETe=b(()=>{SD=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Zvt.warn(Jvt(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},BNr=Math.ceil(34028234663852886e22),Uvt=t=>{let e=SD(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>BNr)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},zNr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},qvt=t=>CTe(t,32),Hvt=t=>CTe(t,
2025-07-05 20:48:33 +08:00
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
2025-09-01 12:32:47 +08:00
`),Zvt={warn:console.warn}});var HNr,VNr,Yvt,WNr,Xvt,_Po,vPo,wPo,Yne,Qvt,xPo,KNr,GNr,JNr,CD,ZNr,YNr,PTe,ewt=b(()=>{ETe();HNr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],VNr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Yvt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=VNr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=OTe(PTe(n)),d=CD(o,"month",1,12),f=CD(i,"day",1,31);return Qvt(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},WNr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Xvt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=WNr.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=OTe(PTe(n)),f=CD(o,"month",1,12),p=CD(i,"day",1,31),h=Qvt(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&h.setTime(h.getTime()-YNr(c)),h},_Po=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$/),vPo=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$/),wPo=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})$/),Yne=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Wvt(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))},Qvt=(t,e,r,n)=>{let o=e-1;return GNr(t,o,r),new Date(Date.UTC(t,o,r,CD(n.hours,"hour",0,23),CD(n.minutes,"minute",0,59),CD(n.seconds,"seconds",0,60),ZNr(n.fractionalMilliseconds)))},xPo=50*365*24*60*60*1e3,KNr=[31,28,31,30,31,30,31,31,30,31,30,31],GNr=(t,e,r)=>{let n=KNr[e];if(e===1&&JNr(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${HNr[e]} in ${t}: ${r}`)},JNr=t=>t%4===0&&(t%100!==0||t%400===0),CD=(t,e,r,n)=>{let o=Gvt(PTe(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},ZNr=t=>t==null?0:Kvt("0."+t)*1e3,YNr=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},PTe=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var cU,ds,TTe=b(()=>{cU=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}},ds=(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 XNr,Xne,QNr,twt=b(()=>{TTe();XNr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=QNr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw ds(a,e)},Xne=t=>({output:e,parsedBody:r,errorCode:n})=>{XNr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},QNr=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 Qne,rwt=b(()=>{Qne=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region
`);return this.signString(h,{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}=goe(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(ZI(e)),Yb(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=hoe(e),{longDate:c,shortDate:d}=goe(r),f=foe(d,u,a??this.service);l.headers[VTe]=c,s.sessionToken&&(l.headers[C0t]=s.sessionToken);let p=await lW(l,this.sha256);!$0t(uW,l.headers)&&this.applyChecksum&&(l.headers[uW]=p);let h=poe(l,o,n),m=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,h,p));return l.headers[HTe]=`${coe} Credential=${s.accessKeyId}/${f}, SignedHeaders=${q0t(h)}, Signature=${m}`,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-09-01 12:32:47 +08:00
${ZTe(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-09-01 12:32:47 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(ZI(n));let i=await o.digest();return`${coe}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-09-01 12:32:47 +08:00
${Yb(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 my(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(ZI(i)),Yb(await a.digest())}getSigningKey(e,r,n,o){return N0t(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")}},goe=t=>{let e=z0t(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},q0t=t=>Object.keys(t).sort().join(";")});var V0t=b(()=>{H0t();JTe();YTe();XTe();tAe();rAe();GTe()});var yoe,W0t=b(()=>{GI();V0t();yoe=t=>{let e;t.credentials&&(e=Mwt(t.credentials,Iwt,NTe)),e||(t.credentialDefaultProvider?e=pU(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=pU(t.signer):t.regionInfoProvider?i=()=>pU(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||cW;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await pU(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||cW;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var K0t=b(()=>{f0t();p0t();W0t()});var G0t=b(()=>{K0t()});var J0t=b(()=>{});var Z0t=b(()=>{yr()});var boe,nAe=b(()=>{yr();boe=(t,e)=>KI(t,e).then(r=>e.utf8Encoder(r))});var iu,Y0t,X0t,Q0t=b(()=>{nAe();iu=(t,e)=>boe(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{}}),Y0t=async(t,e)=>{let r=await iu(t,e);return r.message=r.message??r.Message,r},X0t=(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 _oe=x(QE=>{"use strict";var ext=":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",_jr=ext+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",txt="["+ext+"]["+_jr+"]*",vjr=new RegExp("^"+txt+"$"),wjr=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},xjr=function(t){let e=vjr.exec(t);return!(e===null||typeof e>"u")};QE.isExist=function(t){return typeof t<"u"};QE.isEmptyObject=function(t){return Object.keys(t).length===0};QE.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]]}};QE.getValue=function(t){return QE.isExist(t)?t:""};QE.isName=xjr;QE.getAllMatches=wjr;QE.nameRegexp=txt});var iAe=x(axt=>{"use strict";var oAe=_oe(),Sjr={allowBooleanAttributes:!1,unpairedTags:[]};axt.validate=function(t,e){e=Object.assign({},Sjr,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--),!Mjr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",au("InvalidTag",d,Fp(t,i))}let l=Ejr(t,i);if(l===!1)return au("InvalidAttr","Attributes for '"+u+"' have open quote.",Fp(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=ixt(c,e);if(f===!0)n=!0;else return au(f.err.code,f.err.msg,Fp(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return au("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",Fp(t,a));if(r.length===0)return au("InvalidTag","Closing tag '"+u+"' has not been opened.",Fp(t,a));{let d=r.pop();if(u!==d.tagName){let f=Fp(t,d.tagStartPos);return au("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",Fp(t,a))}r.length==0&&(o=!0)}}else return au("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",Fp(t,i));else{let d=ixt(c,e);if(d!==!0)return au(d.err.code,d.err.msg,Fp(t,i-c.length+d.err.line));if(o===!0)return au("InvalidXml","Multiple possible root nodes found.",Fp(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=oxt(t,i);continue}else if(t[i+1]==="?"){if(i=nxt(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Ajr(t,i);if(d==-1)return au("InvalidChar","char '&' is not expected.",Fp(t,i));i=d}else if(o===!0&&!rxt(t[i]))return au("InvalidXml","Extra text at the end",Fp(t,i));t[i]==="<"&&i--}}else{if(rxt(t[i]))continue;return au("InvalidChar","char '"+t[i]+"' is not expected.",Fp(t,i))}if(n){if(r.length==1)return au("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",Fp(t,r[0].tagStartPos));if(r.length>0)return au("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return au("InvalidXml","Start tag expected.",1);return!0};function rxt(t){return t===" "||t===" "||t===`
`||t==="\r"}function nxt(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 au("InvalidXml","XML declaration allowed only at the start of the document.",Fp(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function oxt(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 Cjr='"',Ojr="'";function Ejr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Cjr||t[e]===Ojr)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 Pjr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function ixt(t,e){let r=oAe.getAllMatches(t,Pjr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return au("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",dW(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return au("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",dW(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return au("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",dW(r[o]));let i=r[o][2];if(!Ijr(i))return au("InvalidAttr","Attribute '"+i+"' is an invalid name.",dW(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return au("InvalidAttr","Attribute '"+i+"' is repeated.",dW(r[o]))}return!0}function Tjr(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 Ajr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Tjr(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 au(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Ijr(t){return oAe.isName(t)}function Mjr(t){return oAe.isName(t)}function Fp(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function dW(t){return t.startIndex+t[1].length}});var uxt=x(aAe=>{var sxt={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}},Rjr=function(t){return Object.assign({},sxt,t)};aAe.buildOptions=Rjr;aAe.defaultOptions=sxt});var cxt=x((WMo,lxt)=>{"use strict";var sAe=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})}};lxt.exports=sAe});var fxt=x((KMo,dxt)=>{var Njr=_oe();function jjr(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&&Fjr(t,e))e+=7,[entityName,val,e]=Djr(t,e+1),val.indexOf("&")===-1&&(r[zjr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&kjr(t,e))e+=8;else if(o&&$jr(t,e))e+=8;else if(o&&Bjr(t,e))e+=9;else if(Ljr)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 fW("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=PD(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=lAe(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 fW(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=PD(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=Kjr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=PD(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=lAe(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 h="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let g=this.readStopNodeData(t,l,f+1);if(!g)throw new Error(`Unexpected end of ${l}`);i=g.i,h=g.tagContent}let m=new fW(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),h&&(h=this.parseTextData(h,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),m.add(this.options.textNodeName,h),this.addChild(r,m,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let h=new fW(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),o=o.substr(0,o.lastIndexOf("."))}else{let h=new fW(u);this.tagsNodeStack.push(r),u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),r=h}n="",i=f}}else n+=t[i];return e.child};function tDr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var rDr=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 nDr(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 oDr(t,e,r){let n="*
`;function gDr(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=hDr),Cxt(t,e,"",r)}function Cxt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=yDr(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let h=s[u];bDr(l,e)||(h=e.tagValueProcessor(u,h),h=Oxt(h,e)),i&&(o+=n),o+=h,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 h=Sxt(s[":@"],e),m=u==="?xml"?"":n,g=s[u][0][e.textNodeName];g=g.length!==0?" "+g:"",o+=m+`<${u}${g}${h}?>`,i=!0;continue}let c=n;c!==""&&(c+=e.indentBy);let d=Sxt(s[":@"],e),f=n+`<${u}${d}`,p=Cxt(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 yDr(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 Sxt(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=Oxt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function bDr(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 Oxt(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}Ext.exports=gDr});var Axt=x((QMo,Txt)=>{"use strict";var _Dr=Pxt(),vDr={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 YI(t){this.options=Object.assign({},vDr,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=SDr),this.processTextOrObjNode=wDr,this.options.format?(this.indentate=xDr,this.tagEndChar=`>
2025-07-05 20:48:33 +08:00
`,this.newLine=`
2025-09-01 12:32:47 +08:00
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}YI.prototype.build=function(t){return this.options.preserveOrder?_Dr(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};YI.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}};YI.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 wDr(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)}YI.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}};YI.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};YI.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}};YI.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 xDr(t){return this.options.indentBy.repeat(t)}function SDr(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}Txt.exports=YI});var Mxt=x((eRo,Ixt)=>{"use strict";var CDr=iAe(),ODr=xxt(),EDr=Axt();Ixt.exports={XMLParser:ODr,XMLValidator:CDr,XMLBuilder:EDr}});v
2025-07-05 20:48:33 +08:00
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
2025-09-01 12:32:47 +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]),ITe(s)}return{}}),Nxt=async(t,e)=>{let r=await lw(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var Dxt=b(()=>{J0t();Z0t();Q0t();jxt()});var TD=b(()=>{Zwt();G0t();Dxt()});function PDr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function voe(t){return{schemeId:"smithy.api#noAuth"}}var Lxt,Fxt,kxt,fAe=b(()=>{TD();Jb();Lxt=async(t,e,r)=>({operation:aw(e).operation,region:await Bf(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});Fxt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(voe(t));break}case"GetId":{e.push(voe(t));break}case"GetOpenIdToken":{e.push(voe(t));break}case"UnlinkIdentity":{e.push(voe(t));break}default:e.push(PDr(t))}return e},kxt=t=>({...yoe(t)})});var $xt,Hr,Oa=b(()=>{$xt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),Hr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var zxt,Bxt=b(()=>{zxt={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-09-01 12:32:47 +08:00
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var aOt=b(()=>{});var sOt=b(()=>{aOt()});var uOt=b(()=>{Su()});var lOt=b(()=>{});var cOt=b(()=>{});function dLr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var fie,dOt=b(()=>{fie=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=dLr(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 fOt=b(()=>{});var pOt=b(()=>{});var mOt=b(()=>{});var hOt=b(()=>{sOt();uOt();lOt();cOt();dOt();fOt();pOt();mOt()});function gOt(t){return new fie({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 yOt(t,e){let n=await jvt(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 cc("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:Yvt(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new cc(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new cc(`Server responded with status: ${t.statusCode}`,{logger:e})}var bOt=b(()=>{GE();hOt();yr();xTe()});var _Ot,vOt=b(()=>{_Ot=(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 sIe,wOt=b(()=>{Q5();GE();iOt();bOt();vOt();sIe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new cc("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);oOt(n,t.logger);let o=new WI;return _Ot(async()=>{let i=gOt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return yOt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var xOt=b(()=>{wOt()});function fLr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function SOt(t){return{schemeId:"smithy.api#noAuth"}}var COt,OOt,pLr,EOt,uIe=b(()=>{TD();Jb();gW();COt=async(t,e,r)=>({operation:aw(e).operation,region:await Bf(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});OOt=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(SOt(t));break}case"AssumeRoleWithWebIdentity":{e.push(SOt(t));break}default:e.push(fLr(t))}return e},pLr=t=>({...t,stsClientCtor:hy}),EOt=t=>{let e=pLr(t);return{...yoe(e)}}});var POt,Uf,pw=b(()=>{POt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Uf={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 AOt,TOt=b(()=>{AOt={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js, Br
`);return this.signString(h,{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}=cae(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,BW.toUint8Array)(e)),(0,uae.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,PIt.prepareRequest)(e),{longDate:c,shortDate:d}=cae(r),f=(0,lae.createScope)(d,u,a??this.service);l.headers[Nd.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[Nd.TOKEN_HEADER]=s.sessionToken);let p=await(0,KMe.getPayloadHash)(l,this.sha256);!(0,M$r.hasHeader)(Nd.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[Nd.SHA256_HEADER]=p);let h=(0,EIt.getCanonicalHeaders)(l,o,n),m=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,h,p));return l.headers[Nd.AUTH_HEADER]=`${Nd.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${TIt(h)}, Signature=${m}`,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-09-01 12:32:47 +08:00
${(0,I$r.getCanonicalQuery)(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-09-01 12:32:47 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update((0,BW.toUint8Array)(n));let i=await o.digest();return`${Nd.ALGORITHM_IDENTIFIER}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-09-01 12:32:47 +08:00
${(0,uae.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,BW.toUint8Array)(i)),(0,uae.toHex)(await a.digest())}getSigningKey(e,r,n,o){return(0,lae.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")}};dae.SignatureV4=GMe;var cae=t=>{let e=(0,N$r.iso8601)(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},TIt=t=>Object.keys(t).sort().join(";")});var MIt=x($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});$m.prepareRequest=$m.moveHeadersToQuery=$m.getPayloadHash=$m.getCanonicalQuery=$m.getCanonicalHeaders=void 0;var IIt=(DD(),Nc(jD));IIt.__exportStar(AIt(),$m);var j$r=BMe();Object.defineProperty($m,"getCanonicalHeaders",{enumerable:!0,get:function(){return j$r.getCanonicalHeaders}});var D$r=UMe();Object.defineProperty($m,"getCanonicalQuery",{enumerable:!0,get:function(){return D$r.getCanonicalQuery}});var L$r=qMe();Object.defineProperty($m,"getPayloadHash",{enumerable:!0,get:function(){return L$r.getPayloadHash}});var F$r=VMe();Object.defineProperty($m,"moveHeadersToQuery",{enumerable:!0,get:function(){return F$r.moveHeadersToQuery}});var k$r=WMe();Object.defineProperty($m,"prepareRequest",{enumerable:!0,get:function(){return k$r.prepareRequest}});IIt.__exportStar(kMe(),$m)});var RIt=x(JMe=>{"use strict";Object.defineProperty(JMe,"__esModule",{value:!0});var $$r=(DD(),Nc(jD));$$r.__exportStar(MIt(),JMe)});var hs=x((Zqo,NIt)=>{"use strict";NIt.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 BU=x((Yqo,fae)=>{"use strict";var{AbortController:jIt,AbortSignal:B$r}=typeof self<"u"?self:typeof window<"u"?window:void 0;fae.exports=jIt;fae.exports.AbortSignal=B$r;fae.exports.default=jIt});var zW=x((Xqo,ZMe)=>{"use strict";var zU=typeof Reflect=="object"?Reflect:null,DIt=zU&&typeof zU.apply=="funct
`;super(r),this.name="AggregateError",this.errors=e}};XMe.exports={AggregateError:YMe,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 X$r},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:Q$r,deprecate(t,e){return t},addAbortListener:zW().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);WIt(e,"signal"),eBr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[G$r]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[J$r](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Z$r.any||function(e){if(e.length===1)return e[0];let r=new Y$r,n=()=>r.abort();return e.forEach(o=>{WIt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};XMe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var zp=x((e2o,JIt)=>{"use strict";var{format:tBr,inspect:hae,AggregateError:rBr}=Vf(),nBr=globalThis.AggregateError||rBr,oBr=Symbol("kIsNodeError"),iBr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],aBr=/^([A-Z][a-z0-9]*)+$/,sBr="__node_internal_",gae={};function BD(t,e){if(!t)throw new gae.ERR_INTERNAL_ASSERTION(e)}function KIt(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 uBr(t,e,r){if(typeof e=="function")return BD(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 BD(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:tBr(e,...r)}function jd(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(uBr(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[oBr]=!0,gae[t]=n}function GIt(t){let e=sBr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function lBr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new nBr([e,t],e.message);return r.code=e.code,r}return t||e}var QMe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new gae.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};jd("ERR_ASSERTION","%s",Error);jd("ERR_INVALID_ARG_TYPE",(t,e,r)=>{BD(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)BD(typeof u=="string","All expected entries have to be of type string"),iBr.includes(u)?o.push(u.toLowerCase()):aBr.test(u)?i.push(u):(BD(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0
`)>=0)return!1;return!0}function F4r(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Ow.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Ow.call(Array(e+1),r)}}function b1e(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+Ow.call(t,","+r)+`
`+e.prev}function Wae(t,e){var r=y1e(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=pP(t,o)?e(t[o],t):""}var i=typeof f1e=="function"?f1e(t):[],a;if(tq){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)pP(t,u)&&(r&&String(Number(u))===u&&u<t.length||tq&&a["$"+u]instanceof Symbol||(tNt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof f1e=="function")for(var l=0;l<i.length;l++)rNt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var cNt=x((A2o,lNt)=>{"use strict";var k4r=o9(),$4r=XD(),Jae=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},B4r=function(t,e){if(t){var r=Jae(t,e);return r&&r.value}},z4r=function(t,e,r){var n=Jae(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},U4r=function(t,e){return t?!!Jae(t,e):!1},q4r=function(t,e){if(t)return Jae(t,e,!0)};lNt.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new $4r("Side channel does not contain "+k4r(n))},delete:function(n){var o=e&&e.next,i=q4r(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return B4r(e,n)},has:function(n){return U4r(e,n)},set:function(n,o){e||(e={next:void 0}),z4r(e,n,o)}};return r}});var x1e=x((I2o,dNt)=>{"use strict";dNt.exports=Object});var pNt=x((M2o,fNt)=>{"use strict";fNt.exports=Error});var hNt=x((R2o,mNt)=>{"use strict";mNt.exports=EvalError});var yNt=x((N2o,gNt)=>{"use strict";gNt.exports=RangeError});var _Nt=x((j2o,bNt)=>{"use strict";bNt.exports=ReferenceError});var wNt=x((D2o,vNt)=>{"use strict";vNt.exports=SyntaxError});var SNt=x((L2o,xNt)=>{"use strict";xNt.exports=URIError});var ONt=x((F2o,CNt)=>{"use strict";CNt.exports=Math.abs});var PNt=x((k2o,ENt)=>{"use strict";ENt.exports=Math.floor});var ANt=x(($2o,TNt)=>{"use strict";TNt.exports=Math.max});var MNt=x((B2o,INt)=>{"use strict";INt.exports=Math.min});var NNt=x((z2o,RNt)=>{"use strict";RNt.exports=Math.pow});var DNt=x((U2o,jNt)=>{"use strict";jNt.exports=Math.round});var FNt=x((q2o,LNt)=>{"use strict";LNt.exports=Number.isNaN||function(e){return e!==e}});var $Nt=x((H2o,kNt)=>{"use strict";var H4r=FNt();kNt.exports=function(e){return H4r(e)||e===0?e:e<0?-1:1}});var zNt=x((V2o,BNt)=>{"use strict";BNt.exports=Object.getOwnPropertyDescriptor});var S1e=x((W2o,UNt)=>{"use strict";var Zae=zNt();if(Zae)try{Zae([],"length")}catch{Zae=null}UNt.exports=Zae});var HNt=x((K2o,qNt)=>{"use strict";var Yae=Object.defineProperty||!1;if(Yae)try{Yae({},"a",{value:1})}catch{Yae=!1}qNt.exports=Yae});var WNt=x((G2o,VNt)=>{"use strict";VNt.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 JNt=x((J2o,GNt)=>{"use strict";var KNt=typeof Symbol<"u"&&Symbol,V4r=WNt();GNt.exports=function(){return typeof KNt!="function"||typeof Symbol!="function"||typeof KNt("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:V4r()}});var C1e=x((Z2o,ZNt)=>{"use strict";ZNt.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var O1e=x((Y2o,YNt)=>{"use strict";var W4r=x1e();YNt.exports=W4r.getPrototypeOf||null});var ejt=x((X2o,QNt)=>{"use strict";var K4r="Function.prototype.bind called on incompatible ",G4r=Object.prototype.toString,J4r=Math.max,Z4r="[object Function]",XNt=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},Y4r=function(e,r){f
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return PDt(this,arguments,function*(){var r,n;this.controller.signal;let o=TDt(this.stream),i="",a=!1;try{for(var s=EDt(o),u;u=yield t_(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 t_(void 0);let f=yield t_(this.parse(JSON.parse(d)));yield yield t_(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield t_(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return PDt(this,arguments,function*(){var r,n;try{for(var o=EDt(this.iterMessages()),i;i=yield t_(o.next()),!i.done;){let a=i.value;yield yield t_(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield t_(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 RVr.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Bm.Stream=Z1e;function TDt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return ODt(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 ODt(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Bm.readableStreamAsyncIterable=TDt});var ADt=x(mse=>{"use strict";Object.defineProperty(mse,"__esModule",{value:!0});mse.Stream=void 0;var jVr=Y1e();Object.defineProperty(mse,"Stream",{enumerable:!0,get:function(){return jVr.Stream}})});var RDt=x((B4o,MDt)=>{"use strict";var X1e=Object.defineProperty,DVr=Object.getOwnPropertyDescriptor,LVr=Object.getOwnPropertyNames,FVr=Object.prototype.hasOwnProperty,kVr=(t,e)=>{for(var r in e)X1e(t,r,{get:e[r],enumerable:!0})},$Vr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of LVr(e))!FVr.call(t,o)&&o!==r&&X1e(t,o,{get:()=>e[o],enumerable:!(n=DVr(e,o))||n.enumerable});return t},BVr=t=>$Vr(X1e({},"__esModule",{value:!0}),t),IDt={};kVr(IDt,{Blob:()=>qVr,File:()=>HVr,FormData:()=>UVr});MDt.exports=BVr(IDt);var zVr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:UVr,Blob:qVr,File:HVr}=zVr});var VDt=x((z4o,HDt)=>{"use strict";var tNe=Object.defineProperty,VVr=Object.getOwnPropertyDescriptor,WVr=Object.getOwnPropertyNames,KVr=Object.prototype.hasOwnProperty,GVr=(t,e)=>{for(var r in e)tNe(t,r,{get:e[r],enumerable:!0})},JVr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of WVr(e))!KVr.call(t,o)&&o!==r&&tNe(t,o,{get:()=>e[o],enumerable:!(n=VVr(e,o))||n.enumerable});return t},ZVr=t=>JVr(tNe({},"__esModule",{value:!0}),t),rNe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Ds=(t,e,r)=>(rNe(t,e,"read from private field"),r?r.call(t):e.get(t)),Pw=(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)},f9=(t,e,r,n)=>(rNe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Q1e=(t,e,r)=>(rNe(t,e,"access private method"),r),$Dt={};GVr($Dt,{FormDataEncoder:()=>o6r,isFile:()=>nL,isFormData:()=>UDt});HDt.exports=ZVr($Dt);var hP=t=>typeof t=="function",YVr=t=>hP(t[Symbol.asyncIterator]),NDt=65536;function*BDt(t){if(t.byteLength<=NDt){yield t;return}let e=0;for(;e<t.byteLength;){let r=Math.min(t.byteLength-e,NDt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yield new Uint8Array(n)}}async function*XVr(t){let e=t.getReader();for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}async function*jDt(t){for await(let e of t)yield*BDt(e)}var QVr=t=>{if(YVr(t))return jDt(t);if(hP(t.getReader))return jDt(XVr(t));throw new TypeError("Unsup
2025-07-05 20:48:33 +08:00
`||e===`
`&&n[r-1]!=="\r"?`\r
2025-09-01 12:32:47 +08:00
`:e),t6r=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function LDt(t){if(t6r(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function FDt(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var r6r=t=>new Proxy(t,{get:(e,r)=>FDt(e,r),has:(e,r)=>FDt(e,r)!==void 0}),UDt=t=>!!(t&&hP(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&hP(t.append)&&hP(t.getAll)&&hP(t.entries)&&hP(t[Symbol.iterator])),kDt=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),nL=t=>!!(t&&typeof t=="object"&&hP(t.constructor)&&t[Symbol.toStringTag]==="File"&&hP(t.stream)&&t.name!=null),n6r={enableAdditionalHeaders:!1},hse={writable:!1,configurable:!1},SM,p9,gse,m9,rL,h9,g9,yse,bse,nNe,eNe,qDt,o6r=class{constructor(t,e,r){if(Pw(this,bse),Pw(this,eNe),Pw(this,SM,`\r
`),Pw(this,p9,void 0),Pw(this,gse,void 0),Pw(this,m9,"-".repeat(2)),Pw(this,rL,new TextEncoder),Pw(this,h9,void 0),Pw(this,g9,void 0),Pw(this,yse,void 0),!UDt(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(LDt(e)?r=e:n=e,n||(n=e6r()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!LDt(r))throw new TypeError("Expected options argument to be an object.");f9(this,g9,Array.from(t.entries())),f9(this,yse,{...n6r,...r}),f9(this,p9,Ds(this,rL).encode(Ds(this,SM))),f9(this,gse,Ds(this,p9).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,f9(this,h9,Ds(this,rL).encode(`${Ds(this,m9)}${this.boundary}${Ds(this,m9)}${Ds(this,SM).repeat(2)}`));let o={"Content-Type":this.contentType},i=Q1e(this,eNe,qDt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=r6r(Object.freeze(o)),Object.defineProperties(this,{boundary:hse,contentType:hse,contentLength:hse,headers:hse})}*values(){for(let[t,e]of Ds(this,g9)){let r=nL(e)?e:Ds(this,rL).encode(zDt(e));yield Q1e(this,bse,nNe).call(this,t,r),yield r,yield Ds(this,p9)}yield Ds(this,h9)}async*encode(){for(let t of this.values())nL(t)?yield*QVr(t.stream()):yield*BDt(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};SM=new WeakMap;p9=new WeakMap;gse=new WeakMap;m9=new WeakMap;rL=new WeakMap;h9=new WeakMap;g9=new WeakMap;yse=new WeakMap;bse=new WeakSet;nNe=function(t,e){let r="";if(r+=`${Ds(this,m9)}${this.boundary}${Ds(this,SM)}`,r+=`Content-Disposition: form-data; name="${kDt(t)}"`,nL(e)&&(r+=`; filename="${kDt(e.name)}"${Ds(this,SM)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Ds(this,yse).enableAdditionalHeaders===!0){let n=nL(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Ds(this,SM)}Content-Length: ${n}`)}return Ds(this,rL).encode(`${r}${Ds(this,SM).repeat(2)}`)};eNe=new WeakSet;qDt=function(){let t=0;for(let[e,r]of Ds(this,g9)){let n=nL(r)?r:Ds(this,rL).encode(zDt(r)),o=nL(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=Q1e(this,bse,nNe).call(this,e,n).byteLength,t+=o,t+=Ds(this,gse)}return String(t+Ds(this,h9).byteLength)}});var KDt=x((q4o,WDt)=>{"use strict";WDt.exports=typeof self=="object"?self.FormData:window.FormData});var GDt=x(Uc=>{"use strict";var i6r=Uc&&Uc.__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]}),a6r=Uc&&Uc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vq=Uc&&Uc.__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)&&i6r(e,t,r);return a6r(e,t),e},CM=Uc&&Uc.__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(Uc,"__esModule",{value:!0});Uc.WebFormData=Uc.Node16FormData=Uc.Node18FormData=Uc.newFormData=void 0;var _se=lq();function oNe(t){return typeof t=="object"&&t!=null&&"name"in t}function s6r(){return CM(this,void 0,void 0,function*(){let t;return _se.RUNTIME.type==="node"&&_se.RUNTIME.parsedVersion!=null&&_se.RUNTIME.parsedVersion>=18?t=new vse:_se.RUNTIME.type==="node"?t=new wse:t=new xse,yield t.setup(),t})}Uc.newFormData=s6r;var vse=class{setup(){return CM(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>vq(RDt()))).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 CM(this,void 0,void 0,function*(){n==null&&oNe(r)&&(n=r.name),r instanceof(yield Promise.r
`)),{ok:!0,value:e}):n}}});var iNe=x(Ese=>{"use strict";Object.defineProperty(Ese,"__esModule",{value:!0});Ese.stringifyValidationError=void 0;function p6r(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}Ese.stringifyValidationError=p6r});var sNe=x(Pse=>{"use strict";Object.defineProperty(Pse,"__esModule",{value:!0});Pse.JsonError=void 0;var m6r=iNe(),aNe=class t extends Error{constructor(e){super(e.map(m6r.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};Pse.JsonError=aNe});var lNe=x(Tse=>{"use strict";Object.defineProperty(Tse,"__esModule",{value:!0});Tse.ParseError=void 0;var h6r=iNe(),uNe=class t extends Error{constructor(e){super(e.map(h6r.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};Tse.ParseError=uNe});var QDt=x(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0});OM.transform=OM.optional=OM.getSchemaUtils=void 0;var g6r=Dd(),y6r=sNe(),b6r=lNe();function cNe(t){return{optional:()=>YDt(t),transform:e=>XDt(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new b6r.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new y6r.JsonError(n.errors)}}}OM.getSchemaUtils=cNe;function YDt(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:()=>g6r.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),cNe(e))}OM.optional=YDt;function XDt(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),cNe(r))}OM.transform=XDt});var Jh=x(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});Cy.ParseError=Cy.JsonError=Cy.transform=Cy.optional=Cy.getSchemaUtils=void 0;var dNe=QDt();Object.defineProperty(Cy,"getSchemaUtils",{enumerable:!0,get:function(){return dNe.getSchemaUtils}});Object.defineProperty(Cy,"optional",{enumerable:!0,get:function(){return dNe.optional}});Object.defineProperty(Cy,"transform",{enumerable:!0,get:function(){return dNe.transform}});var _6r=sNe();Object.defineProperty(Cy,"JsonError",{enumerable:!0,get:function(){return _6r.JsonError}});var v6r=lNe();Object.defineProperty(Cy,"ParseError",{enumerable:!0,get:function(){return v6r.ParseError}})});var eLt=x(Ase=>{"use strict";Object.defineProperty(Ase,"__esModule",{value:!0});Ase.date=void 0;var w6r=Dd(),fNe=zm(),x6r=gP(),S6r=Jh(),C6r=/^([+-]?\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 O6r(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="string"?{ok:!1,errors:[{path:r,message:(0,fNe.getErrorMessageForIncorrectType)(e,"string")}]}:C6r.test(e)?{ok:!0,value:new Date(e)}:{ok:!1,errors:[{path:r,message:(0,fNe.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,fNe.getErrorMessageForIncorrectType)(e,"Date object")}]},getType:()=>w6r.SchemaType.DATE};return Object.assign(Object.assign({},(0,x6r.maybeSkipValidation)(t)),(0,S6r.getSchemaUtils)(t))}Ase.date=O6r});var tLt=x(Ise=>{"use strict";Object.defineProperty(Ise,"__esModule",{value:!0});Ise.date=void 0;var E6r=eLt();Object.defineProperty(Ise,"date",{enumerable:!0,get:function(){return E6r.date}})});var yP=x(Mse=>{"use strict";Object.defineProperty(Mse,"__esModule",{value:!0});Mse.createIdentitySchemaCreator=void 0;var P6r=Jh(),T6r=gP();function A6r(t,e){return()=>{let r={parse:e,json:e,getType:()=>t};return Object.assign(Object.assign({},(0,T6r.maybeSkipValidation)(r)),(0,P6r.getSchemaUtils)(r))}}Mse.createIdentitySchemaCreator=A6r});var nLt=x(Rse=>{"use stri
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return x9(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};Cu.StreamUtils=ONe;function JLt(t,e){return C9(this,arguments,function*(){var n,o;if(!t.body)throw e?.abort(),new Aq.CohereError({message:"Attempted to iterate over a response with no body"});let i=new ENe,a=new PM,s=PNe(t.body);try{for(var u=S9(O5r(s)),l;l=yield Va(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield Va(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield Va(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield Va(d))}})}Cu._iterSSEMessages=JLt;function O5r(t){return C9(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=S9(t),a;a=yield Va(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=E5r(o))!==-1;)yield yield Va(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield Va(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield Va(o))})}function E5r(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 ENe=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]=T5r(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},PM=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 Aq.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 Aq.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new Aq.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}};Cu.LineDecoder=PM;PM.NEWLINE_CHARS=new Set([`
`,"\r"]);PM.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function P5r(t){let e=new PM,r=[];for(let n of t)r.push(...e.decode(n));return r}Cu._decodeChunks=P5r;function T5r(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function PNe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return x9(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 x9(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Cu.readableStreamAsyncIterable=PNe});var TNe=x(Tw=>{"use strict";var A5r=Tw&&Tw.__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]}),I5r=Tw&&Tw.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M5r=Tw&&Tw.__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)&&A5r(e,t,r);return I5r(e,t),e};Object.defineProperty(Tw,"__esModule",{value:!0});Tw.V2ChatStreamRequestCitationMode=void 0;var R5r=M5r(J());Tw.V2ChatStreamRequestCitationMode=R5r.serialization.enum_(["FAST","ACCURATE","OFF"])});var ANe=x(Aw=>{"use strict";var N5r=Aw&&Aw.__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]}),j5r=Aw&&Aw.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),D5r=Aw&&Aw.__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)&&N5r(e,t,r);return j5r(e,t),e};Object.defineProperty(Aw,"__esModule",{value:!0});Aw.V2ChatRequestCitationMode=void 0;var L5r=D5r(J());Aw.V2ChatRequestCitationMode=L5r.serialization.enum_(["FAST","ACCURATE","OFF"])});var Iq=x(Iw=>{"use strict";var F5r=Iw&&Iw.__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]}),k5r=Iw&&Iw.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$5r=Iw&&Iw.__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)&&F5r(e,t,r);return k5r(e,t),e};Object.defineProperty(Iw,"__esModule",{value:!0});Iw.TextContent=void 0;var YLt=$5r(J());Iw.TextContent=YLt.serialization.object({text:YLt.serialization.string()})});var INe=x(Mw=>{"use strict";var B5r=Mw&&Mw.__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]}),z5r=Mw&&Mw.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),U5r=Mw&&Mw.__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)&&B5r(e,t,r);return z5r(e,t),e};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.Content=void 0;var q5r=U5r(J()),H5r=Iq();Mw.Content=q5r.serialization.union("type",{text:H5r.TextContent}).transform({
`)}}}}catch(w){a={error:w}}finally{try{m&&!m.done&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}for(let w of y.flush()){let S=(0,xi.parseAWSEvent)(w);if(S){let C=yield(0,xi.mapResponseFromBedrock)(c,u,S);_.push(JSON.stringify(C)+`
`)}}return _.end(),{ok:!0,body:_}}else{let g=yield p.body;return{ok:!0,body:yield(0,xi.mapResponseFromBedrock)(c,u,g)}}}catch(g){throw g}});xi.fetchOverride=Hun});var SP=x(Uue=>{"use strict";Object.defineProperty(Uue,"__esModule",{value:!0});Uue.CohereEnvironment=void 0;Uue.CohereEnvironment={Production:"https://api.cohere.com"}});var kM=x((v$t,que)=>{(function(t,e,r){typeof que<"u"&&que.exports?que.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",v$t,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 kLe=x(Vm=>{"use strict";var Vun=Vm&&Vm.__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]}),Wun=Vm&&Vm.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),J9=Vm&&Vm.__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)&&Vun(e,t,r);return Wun(e,t),e},Hue=Vm&&Vm.__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())})},Kun=Vm&&Vm.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vm,"__esModule",{value:!0});Vm.V2=void 0;var w$t=J9(SP()),qm=J9(J()),Fs=J9(KE()),Hm=J9(xP()),x$t=Kun(kM()),CP=J9(ou()),FLe=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return Hue(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:qm.fetcher)({url:(0,x$t.default)((o=yield qm.Supplier.get(this._options.environment))!==null&&o!==void 0?o:w$t.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield qm.Supplier.get(this._options.clientName))!=null?yield qm.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":qm.RUNTIME.type,"X-Fern-Runtime-Version":qm.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Hm.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 qm.Stream({stream:i.body,parse:a=>Hue(this,void 0,void 0,function*(){return Hm.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 Fs.BadRequestError(i.error.body);case 401:th
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Pe.InternalServerError(i.error.body);case 501:throw new Pe.NotImplementedError(ct.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Pe.ServiceUnavailableError(i.error.body);case 504:throw new Pe.GatewayTimeoutError(ct.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Qr.CohereTimeoutError;case"unknown":throw new Qr.CohereError({message:i.error.errorMessage})}})}chat(e,r){var n,o;return Ym(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Et.fetcher)({url:(0,a_.default)((o=yield Et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:i_.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Et.Supplier.get(this._options.clientName))!=null?yield Et.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":Et.RUNTIME.type,"X-Fern-Runtime-Version":Et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ct.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 ct.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 Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Pe.InternalServerError(i.error.body);case 501:throw new Pe.NotImplementedError(ct.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Pe.ServiceUnavailableError(i.error.body);case 504:throw new Pe.GatewayTimeoutError(ct.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Qr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Qr.CohereTimeoutError;case"unknown":throw new Qr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Ym(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Et.fetcher)({url:(0,a_.default)((o=yield Et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:i_.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Et.Supplier.get(this._options.clientName))!=null?yield Et.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":Et.RUNTIME.type,"X-Fern-Runtime-Version":Et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ct.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 ct.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 Pe.BadRequestError(i.error.body);case 401:throw new Pe.UnauthorizedError(i.error.body);case 403:throw new Pe.ForbiddenError(i.error.body);case 404:throw new Pe.NotFoundError(i.error.body);case 422:throw new Pe.UnprocessableEntityError(ct.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Pe.TooManyRequestsError(ct.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Pe.ClientClosedRequestError(ct.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`)),D$t=!0),new u_(!0).update(t).hex())});function UC(t,e){e?(Vc[0]=Vc[16]=Vc[1]=Vc[2]=Vc[3]=Vc[4]=Vc[5]=Vc[6]=Vc[7]=Vc[8]=Vc[9]=Vc[10]=Vc[11]=Vc[12]=Vc[13]=Vc[14]=Vc[15]=0,this.blocks=Vc):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 kt,Lln,l_,Que,Vc,F$t=b(()=>{"use strict";kt="0123456789abcdef".split(""),Lln=[-2147483648,8388608,32768,128],l_=[24,16,8,0],Que=[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],Vc=[];UC.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]<<l_[i++&3];else for(i=this.start;o<a&&i<64;++o)n=t.charCodeAt(o),n<128?s[i>>>2]|=n<<l_[i++&3]:n<2048?(s[i>>>2]|=(192|n>>>6)<<l_[i++&3],s[i>>>2]|=(128|n&63)<<l_[i++&3]):n<55296||n>=57344?(s[i>>>2]|=(224|n>>>12)<<l_[i++&3],s[i>>>2]|=(128|n>>>6&63)<<l_[i++&3],s[i>>>2]|=(128|n&63)<<l_[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++o)&1023),s[i>>>2]|=(240|n>>>18)<<l_[i++&3],s[i>>>2]|=(128|n>>>12&63)<<l_[i++&3],s[i>>>2]|=(128|n>>>6&63)<<l_[i++&3],s[i>>>2]|=(128|n&63)<<l_[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}};UC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=Lln[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()}};UC.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,h,m,g,y,_,w;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(w=e&r,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=u[0]-1413257819,s=p-150054599<<0,n=p+24177077<<0):(g=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),g=t&e,f=g^t&r^w,m=o&i^~o&a,p=s+d+m+Que[l]+u[l],h=c+f,s=n+p<<0,n=p+h<<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),y=n&t,f=y^n&e^g,m=a&s^~a&o,p=i+d+m+Que[l+1]+u[l+1],h=c+f,a=r+p<<0,r=p+h<<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),_=r&n,f=_^r&t^y,m=i&a^~i&s,p=o+d+m+Que[l+2]+u[l+2],h=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=B$t.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=eFe.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=eFe.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 h=this.textEncoder.encode(p[0]),m=this.rankMap.get(h.join(","));if(m!=null){i.push(m);continue}i.push(...qln(h,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(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)}},tle=eFe;zln(tle,"specialTokenRegex",t=>new RegExp(t.map(e=>Hln(e)).join("|"),"g"))});var U$t=b(()=>{z$t()});async function q$t(t){return t in rle||(rle[t]=Vln.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new tle(e)).catch(e=>{throw delete rle[t],e})),await rle[t]}async function H$t(t){return q$t(tFe(t))}var rle,Vln,rFe=b(()=>{U$t();PB();rle={},Vln=new Ph({})});function $d(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 Wln,Kln,e2,t2,aK=b(()=>{$$t();H6();BA();PB();rFe();Tf();Wln=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;Kln=()=>!1,e2=class extends Un{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??Kln(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},t2=class extends e2{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=ele.global():this.cache=void 0,this.caller=new Ph(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 H$t("modelName"in this?Wln(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 kB(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 SBt(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 lle(t){return!!t.finishReason&&mcn.includes(t.finishReason)}function UM(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];lle(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function uK(t){return this instanceof uK?(this.v=t,this):new uK(t)}function hcn(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(h,m){i.push([f,p,h,m])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(h){d(i[0][3],h)}}function u(f){f.value instanceof uK?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 gcn(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=_cn(e),[n,o]=r.tee();return{stream:bcn(n),response:ycn(o)}}async function ycn(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return pFe(vcn(e));e.push(o)}}function bcn(t){return hcn(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield uK(r.read());if(o)break;yield yield uK(pFe(n))}})}function _cn(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 Yf("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(CBt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new Yf(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(CBt)}return i()})}}})}function vcn(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 TBt(t,e,r,n){let o=await cK(e,TL.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return gcn(o)}async function ABt(t,e,r,n){let i=await(await cK(e,TL.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:pFe(i)}}function IBt(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 lK(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 wcn(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 WC(t,e){if(!(this instanceof WC))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 hc(e.headers),this.url=e.url||"",this._initBody(t)}function WBt(t,e){return new Promise(function(r,n){var o=new RL(t,e);if(o.signal&&o.signal.aborted)return n(new ML("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:qcn(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 WC(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 ML("Aborted","AbortError"))},0)};function s(l){try{return l===""&&zd.location.href?zd.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&&(Vp.blob?i.responseType="blob":Vp.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof hc||zd.Headers&&e.headers instanceof zd.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(n2(l)),i.setRequestHeader(l,_Fe(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 zd,Vp,zBt,qBt,Bcn,Hcn,ML,KBt=b(()=>{zd=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Vp={searchParams:"URLSearchParams"in zd,iterable:"Symbol"in zd&&"iterator"in Symbol,blob:"FileReader"in zd&&"Blob"in zd&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in zd,arrayBuffer:"ArrayBuffer"in zd};Vp.arrayBuffer&&(zBt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],qBt=ArrayBuffer.isView||function(t){return t&&zBt.indexOf(Object.prototype.toString.call(t))>-1});hc.prototype.append=function(t,e){t=n2(t),e=_Fe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};hc.prototype.delete=function(t){delete this.map[n2(t)]};hc.prototype.get=function(t){return t=n2(t),this.has(t)?this.map[t]:null};hc.prototype.has=function(t){return this.map.hasOwnProperty(n2(t))};hc.prototype.set=function(t,e){this.map[n2(t)]=_Fe(e)};hc.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};hc.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),vFe(t)};hc.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),vFe(t)};hc.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),vFe(t)};Vp.iterable&&(hc.prototype[Symbol.iterator]=hc.prototype.entries);Bcn=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];RL.prototype.clone=function(){return new RL(this,{body:this._bodyInit})};VBt.call(RL.prototype);VBt.call(WC.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-09-01 12:32:47 +08:00
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},Xcn=t=>{if(!t)return ZBt;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=JBt);let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},Qcn=Object.defineProperty,edn=(t,e,r)=>e in t?Qcn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xFe=(t,e,r)=>(edn(t,typeof e!="symbol"?e+"":e,r),r),i2=class{constructor(e){xFe(this,"config"),xFe(this,"fetch"),xFe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Xcn(e?.host??ZBt)),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 o2(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Ycn(a.body),u=new CFe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await o2(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 Zcn(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await o2(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await GBt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await o2(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await o2(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await o2(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await GBt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},TKo=new i2});var YBt=b(()=>{xv()});function XBt(t,e=0){return(Ud[t[e+0]]+Ud[t[e+1]]+Ud[t[e+2]]+Ud[t[e+3]]+"-"+Ud[t[e+4]]+Ud[t[e+5]]+"-"+Ud[t[e+6]]+Ud[t[e+7]]+"-"+Ud[t[e+8]]+Ud[t[e+9]]+"-"+Ud[t[e+10]]+Ud[t[e+11]]+Ud[t[e+12]]+Ud[t[e+13]]+Ud[t[e+14]]+Ud[t[e+15]]).toLowerCase()}var Ud,yle,QBt=b(()=>{Ud=[];for(yle=0;yle<256;++yle)Ud.push((yle+256).toString(16).slice(1))});function PFe(){if(!ble&&(ble=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ble))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ble(tdn)}var ble,tdn,ezt=b(()=>{tdn=new Uint8Array(16)});var rdn,TFe,tzt=b(()=>{rdn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),TFe={randomUUID:rdn}});function ndn(t,e,r){if(TFe.randomUUID&&!e&&!t)return TFe.randomUUID();t=t||{};var n=t.random||(t.rng||PFe)();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 XBt(n)}var AFe,rzt=b(()=>{tzt();ezt();QBt();AFe=ndn});var nzt=b(
`):[]}};sg=new WeakMap,ug=new WeakMap;NL.NEWLINE_CHARS=new Set([`
`,"\r"]);NL.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function gK(){}function Tle(t,e,r){return!e||Ale[t]>Ale[r]?gK:e[t].bind(e)}function cu(t){let e=t.logger,r=t.logLevel??"off";if(!e)return _dn;let n=zzt.get(e);if(n&&n[0]===r)return n[1];let o={error:Tle("error",e,r),warn:Tle("warn",e,r),info:Tle("info",e,r),debug:Tle("debug",e,r)};return zzt.set(e,[r,o]),o}var Ale,WFe,_dn,zzt,AP,yK=b(()=>{TP();Ale={off:0,error:200,warn:300,info:400,debug:500},WFe=(t,e,r)=>{if(t){if(hzt(Ale,t))return t;cu(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ale))}`)}};_dn={error:gK,warn:gK,info:gK,debug:gK},zzt=new WeakMap;AP=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*vdn(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ht("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 ht("Attempted to iterate over a response with no body");let r=new KFe,n=new NL,o=kFe(t.body);for await(let i of wdn(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*wdn(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"?b2(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=$zt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function xdn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var bK,XC,KFe,GFe=b(()=>{Iy();JC();hK();Bzt();hK();wle();Ple();yK();JC();XC=class t{constructor(e,r,n){this.iterator=e,bK.set(this,void 0),this.controller=r,tr(this,bK,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?cu(n):console;async function*a(){if(o)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of vdn(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 gc(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 gc(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(pK(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 NL,u=kFe(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 ht("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(pK(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(bK=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,ce(this,bK,"f")),new t(()=>o(r),this.controller,ce(this,bK,"f"))]}toReadableStream(){let e=this,r;return FFe({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=b2(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};KFe=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]=xdn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function Ile(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return cu(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):XC.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 JFe(d,r)}return await r.text()})();return cu(t).debug(`[${n}] response parsed`,AP({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function JFe(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 ZFe=b(()=>{GFe();yK()});var _K,jL,Mle=b(()=>{Iy();ZFe();jL=class t extends Promise{constructor(e,r,n=Ile){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,_K.set(this,void 0),tr(this,_K,e,"f")}_thenUnwrap(e){return new t(ce(this,_K,"f"),this.responsePromise,async(r,n)=>JFe(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(ce(this,_K,"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)}};_K=new WeakMap});var Rle,Nle,vK,QC,Cn,Ga=b(()=>{Iy();JC();ZFe();Mle();TP();Nle=class{constructor(e,r,n,o){Rle.set(this,void 0),tr(this,Rle,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 ht("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ce(this,Rle,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Rle=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},vK=class extends jL{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await Ile(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},QC=class extends Nle{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}},Cn=class extends Nle{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:{...pzt(this.options.query),after:r}}:null}}});function _2(t,e,r){return XFe(),new File(t,e??"unknown_file",r)}function wK(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 Cdn(t){let e=typeof t=="function"?t:t.fetch,r=Uzt.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 Uzt.set(e,n),n}var XFe,QFe,lg,Uzt,Odn,Edn,YFe,IP=b(()=>{hK();XFe=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&pa
2025-08-12 16:40:13 +08:00
${i.map(f=>f.error).join(`
`)}
${a}
2025-09-01 12:32:47 +08:00
${d}`)}return a},Le=Mdn(Wzt)});var DL,jle=b(()=>{Dr();Ga();ia();DL=class extends qe{list(e,r={},n){return this._client.getAPIList(Le`/chat/completions/${e}/messages`,Cn,{query:r,...n})}}});var c_=b(()=>{JC()});function SK(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Kzt(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function CK(t){return t?.$brand==="auto-parseable-response-format"}function LL(t){return t?.$brand==="auto-parseable-tool"}function Gzt(t,e){return!e||!rke(e)?{...t,choices:t.choices.map(r=>(Zzt(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:OK(t,e)}function OK(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new m2;if(n.finish_reason==="content_filter")throw new h2;return Zzt(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Ddn(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?jdn(e,n.message.content):null}}});return{...t,choices:r}}function jdn(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 Ddn(t,e){let r=t.tools?.find(n=>SK(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:LL(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Jzt(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>SK(n)&&n.function?.name===e.function.name);return SK(r)&&(LL(r)||r?.function.strict||!1)}function rke(t){return CK(t.response_format)?!0:t.tools?.some(e=>LL(e)||e.type==="function"&&e.function.strict===!0)??!1}function Zzt(t){for(let e of t||[])if(e.type!=="function")throw new ht(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Yzt(t){for(let e of t??[]){if(e.type!=="function")throw new ht(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new ht(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var v2=b(()=>{c_()});var w2,nke,oke=b(()=>{w2=t=>t?.role==="assistant",nke=t=>t?.role==="tool"});var ike,Dle,Lle,EK,PK,Fle,TK,MP,AK,kle,$le,x2,Xzt,VM,Ble=b(()=>{Iy();c_();VM=class{constructor(){ike.add(this),this.controller=new AbortController,Dle.set(this,void 0),Lle.set(this,()=>{}),EK.set(this,()=>{}),PK.set(this,void 0),Fle.set(this,()=>{}),TK.set(this,()=>{}),MP.set(this,{}),AK.set(this,!1),kle.set(this,!1),$le.set(this,!1),x2.set(this,!1),tr(this,Dle,new Promise((e,r)=>{tr(this,Lle,e,"f"),tr(this,EK,r,"f")}),"f"),tr(this,PK,new Promise((e,r)=>{tr(this,Fle,e,"f"),tr(this,TK,r,"f")}),"f"),ce(this,Dle,"f").catch(()=>{}),ce(this,PK,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ce(this,ike,"m",Xzt).bind(this))},0)}_connected(){this.ended||(ce(this,Lle,"f").call(this),this._emit("connect"))}get ended(){return ce(this,AK,"f")}get errored(){return ce(this,kle,"f")}get aborted(){return ce(this,$le,"f")}abort(){this.controller.abort()}on(e,r){return(ce(this,MP,"f")[e]||(ce(this,MP,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=ce(this,MP,"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(ce(this,MP,"f")[e]||(ce(this,MP,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{tr(this,x2,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){tr(this,x2,!0,"f"),await ce(this,PK,"f")}_emit(e,...r){if(ce(this,AK,"f"))return;e==="end"&&(tr(this,AK,!0,"f"),ce(this,Fle,"f").call(this));let n=ce(this,MP,"f")[e];if(n&&(ce(this,MP,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!ce(this,x2,"f")&&!n?.length&&Promise.reject(o),ce(t
\r `.includes(t[n]);)n++};return a()},hke=t=>Fdn(t,Kc.ALL^Kc.NUM)});var gke=b(()=>{GFe()});function $dn(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 ht(`missing finish_reason for choice ${d}`);let{content:h=null,function_call:m,tool_calls:g,...y}=l,_=l.role;if(!_)throw new ht(`missing role for choice ${d}`);if(m){let{arguments:w,name:S}=m;if(w==null)throw new ht(`missing function_call.arguments for choice ${d}`);if(!S)throw new ht(`missing function_call.name for choice ${d}`);return{...p,message:{content:h,function_call:{arguments:w,name:S},role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:_,content:h,refusal:l.refusal??null,tool_calls:g.map((w,S)=>{let{function:C,type:E,id:P,...T}=w,{arguments:I,name:N,...M}=C||{};if(P==null)throw new ht(`missing choices[${d}].tool_calls[${S}].id
${Hle(t)}`);if(E==null)throw new ht(`missing choices[${d}].tool_calls[${S}].type
${Hle(t)}`);if(N==null)throw new ht(`missing choices[${d}].tool_calls[${S}].function.name
${Hle(t)}`);if(I==null)throw new ht(`missing choices[${d}].tool_calls[${S}].function.arguments
${Hle(t)}`);return{...T,id:P,type:E,function:{...M,name:N,arguments:I}}})}}:{...p,message:{...y,content:h,role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Gzt(u,e)}function Hle(t){return JSON.stringify(t)}var bc,RP,C2,WM,yke,Ule,bke,_ke,vke,qle,wke,nUt,FL,Vle=b(()=>{Iy();rUt();c_();v2();gke();dke();FL=class t extends S2{constructor(e){super(),bc.add(this),RP.set(this,void 0),C2.set(this,void 0),WM.set(this,void 0),tr(this,RP,e,"f"),tr(this,C2,[],"f")}get currentChatCompletionSnapshot(){return ce(this,WM,"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())),ce(this,bc,"m",yke).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)ce(this,bc,"m",bke).call(this,a);if(i.controller.signal?.aborted)throw new Bs;return this._addChatCompletion(ce(this,bc,"m",qle).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ce(this,bc,"m",yke).call(this),this._connected();let o=XC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(ce(this,bc,"m",qle).call(this)),ce(this,bc,"m",bke).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Bs;return this._addChatCompletion(ce(this,bc,"m",qle).call(this))}[(RP=new WeakMap,C2=new WeakMap,WM=new WeakMap,bc=new WeakSet,yke=function(){this.ended||tr(this,WM,void 0,"f")},Ule=function(r){let n=ce(this,C2,"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},ce(this,C2,"f")[r.index]=n,n)},bke=function(r){if(this.ended)return;let n=ce(this,bc,"m",nUt).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=ce(this,bc,"m",Ule).call(this,i);i.finish_reason&&(ce(this,bc,"m",vke).call(this,i),a.current_tool_call_index!=null&&ce(this,bc,"m",_ke).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(ce(this,bc,"m",vke).call(this,i),a.current_tool_call_index!=null&&ce(this,bc,"m",_ke).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))}}},_ke=function(r,n){if(ce(this,bc,"m",Ule).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=ce(this,RP,"f")?.tools?.find(s=>SK(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-09-01 12:32:47 +08:00
`);this.baseURL=s.baseURL,this.timeout=s.timeout??_$e.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=WFe(s.logLevel,"ClientOptions.logLevel",this)??WFe(d_("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Szt(),tr(this,rce,Ozt,"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 HFe(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${HM}`}defaultIdempotencyKey(){return`stainless-node-retry-${RFe()}`}makeStatusError(e,r,n,o){return gc.generate(e,r,n,o)}buildURL(e,r,n){let o=!ce(this,b$e,"m",PUt).call(this)&&n||this.baseURL,i=fzt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return mzt(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 jL(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(cu(this).debug(`[${l}] sending request`,AP({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Bs;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(mK),h=Date.now();if(p instanceof Error){let y=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Bs;let _=pK(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return cu(this).info(`[${l}] connection ${_?"timed out":"failed"} - ${y}`),cu(this).debug(`[${l}] connection ${_?"timed out":"failed"} (${y})`,AP({retryOfRequestLogID:n,url:s,durationMs:h-d,message:p.message})),this.retryRequest(o,r,n??l);throw cu(this).info(`[${l}] connection ${_?"timed out":"failed"} - error; no more retries left`),cu(this).debug(`[${l}] connection ${_?"timed out":"failed"} (error; no more retries left)`,AP({retryOfRequestLogID:n,url:s,durationMs:h-d,message:p.message})),_?new KC:new qM({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),g=`[${l}${c}${m}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let P=`retrying, ${r} attempts remaining`;return await Czt(p.body),cu(this).info(`${g} - ${P}`),cu(this).debug(`[${l}] response error (${P})`,AP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(o,r,n??l,p.headers)}let _=y?"error; no more retries left":"error; not retryable";cu(this).info(`${g} - ${_}`);let w=await p.text().catch(P=>mK(P).message),S=yzt(w),C=S?void 0:w;throw cu(this).debug(`[${l}] response error (${_})`,AP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:C,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 oO(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 eh(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var v$e,Hd,IUt=b(()=>{FB();dSe();GA();hj();bE();v$e=class extends Cj{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(Wi(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=>Qm(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}},Hd=class extends v$e{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 wQe(this.zodSchema,e);if(r.success)return r.data;throw new Mh(`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 MUt=b(()=>{IUt()});var K2=b(()=>{MUt()});var w$e=b(()=>{_j()});function LP(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 rR=b(()=>{});var NUt,RUt,jUt,oce=b(()=>{NUt=Symbol("Let zodToJsonSchema decide on which parser to use"),RUt={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-09-01 12:32:47 +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 sce(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]:Pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===re.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(ice(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 uce=b(()=>{xd();Au();ace()});function JUt(t,e){if(e.mapStrategy==="record")return sce(t,e);let r=Pr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var $$e=b(()=>{Au();uce()});function ZUt(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 B$e=b(()=>{});function YUt(){return{not:{}}}var z$e=b(()=>{});function XUt(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var U$e=b(()=>{});function eqt(t,e){if(e.target==="openApi3")return QUt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in kK&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=kK[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 QUt(t,e)}var kK,QUt,lce=b(()=>{Au();kK={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};QUt=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Pr(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function tqt(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:kK[t.innerType._def.typeName],nullable:!0}:{type:[kK[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Pr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var q$e=b(()=>{Au();lce()});function rqt(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",C$e(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?go(r,"
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-09-01 12:32:47 +08:00
`,t}var hqt=b(()=>{});function oR(t){let e;return t.constructor.name===KC.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Bs.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=$K(t,"INVALID_TOOL_RESULTS"):t.status===401?e=$K(t,"MODEL_AUTHENTICATION"):t.status===429?e=$K(t,"MODEL_RATE_LIMIT"):t.status===404?e=$K(t,"MODEL_NOT_FOUND"):e=t,e}function rBe(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 Rfn(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function gqt(t,e,r){if(Ah(t))return pqt(t,e,r);if(Sm(t))return Rfn({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:F6(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>UQ(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}var nF=b(()=>{nO();ag();IL();w$e();HQ();mqt();hqt()});function Nfn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function yqt(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(bqt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function bqt(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}: ${cce(o,e)},`):r.push(`${n}?: ${cce(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function cce(t,e){if(Nfn(t))return t.anyOf.map(r=>cce(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["{",bqt(t,e+2),"}"].join(`
`);case"array":return t.items?`${cce(t.items,e)}[]`:"any[]";default:return""}}var _qt=b(()=>{});function vqt(t,e){let r;return Wc(t)?r=qC(t):r=t,r.type==="function"&&e?.strict!==void 0&&(r.function.strict=e.strict),r}function dce(t){return"type"in t&&t.type!=="function"&&t.type!=="custom"}function wqt(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function xqt(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 nBe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Sqt(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 Cqt(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Oqt(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 Eqt(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 Pqt=b(()=>{ag();nF()});function mce(t){return t&&(/^o\d/.test(t)||t.startsWith("gpt-5"))}function jfn(t){return t!==void 0&&typeof t.schema=="object"}function Dfn(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 iBe(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(!Ys.isInstance(t))throw new Error("Invalid generic chat message");return Dfn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function oBe(t,e){return t.flatMap(r=>{let n=iBe(r);n==="system"&&mce(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.map(a=>Ib(a)?x6(a,Tqt):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=""),Wi(r)&&r.tool_calls?.length?(i.tool_calls=r.tool_calls.map(oO),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 G2,Tqt,BK,fce,pce,iO,hce=b(()=>{nO();$s();Zf();no();HC();ig();Pm();Db();K2();IL();w$e();rR();nF();_qt();Pqt();G2="__openai_function_call_ids__";Tqt={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=wB({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=G0e(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: ${h.message}`),new mj(m,JSON.stringify(e))}else{let h=va(o,this.schema);if(!h.valid){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
2025-08-30 08:29:39 +08:00
Details: ${h.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
2025-09-01 12:32:47 +08:00
`)}`),new mj(m,JSON.stringify(e))}i=o}let a=T6(r),u=await gu.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(h){throw await u?.handleToolError(h),h}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;$A(e)&&(f=e.id),!f&&kYe(a)&&(f=a.toolCall.id);let p=Ffn({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},iR=class extends uBe{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:dt.object({input:dt.string().optional()}).transform(r=>r.input)})}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}}});var zK=b(()=>{Lqt()});var lBe,Fqt=b(()=>{no();nO();zK();lBe=class extends iR{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??lt("OPENAI_API_KEY"),n=e?.organization??lt("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Er(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return this.dallEResponseFormat==="url"?e.flatMap(r=>r.data?.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="string"&&o.image_url!==void 0)??[]):e.flatMap(r=>r.data?.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="object"&&"url"in o.image_url&&typeof o.image_url.url=="string"&&o.image_url.url!==void 0)??[])}async _call(e){let r={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){let i=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(r)));return this.processMultipleGeneratedUrls(i)}let n=await this.client.images.generate(r),o="";return this.dallEResponseFormat==="url"?[o]=n.data?.map(i=>i.url).filter(i=>i!=="undefined")??[]:[o]=n.data?.map(i=>i.b64_json).filter(i=>i!=="undefined")??[],o}};Object.defineProperty(lBe,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})});var kqt=b(()=>{Fqt()});var $qt=b(()=>{hce()});var Bqt=b(()=>{yj()});var zqt=b(()=>{Pm();Bqt();zK()});var Uqt=b(()=>{nO();hce();Iqt();aBe();Nqt();jqt();sBe();Dqt();nF();rR();kqt();$qt();zqt()});var _ce=b(()=>{Uqt()});var vce,qqt=b(()=>{PP();Ay();no();vce=class extends qp{constructor(e){let r={maxConcurrency:2,...e};super(r),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"jina-clip-v2"}),Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:24}),Object.defineProperty(this,"baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:"https://api.jina.
without CORS Error: `+eo(n)+`
with CORS Error: `+eo(o);throw new Error(i)}}}}});function Jqt(t){return t!==void 0&&qK.includes(t)?Kqt[t]:void 0}var Kqt,Gqt,qK,Sce=b(()=>{Kqt={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"},Gqt={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},qK=Object.keys(Kqt)});function aa(t,e){if(e.length<cBe)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=cBe)Array.prototype.push.apply(t,e.slice(n,n+cBe))}}function e2t(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 Ufn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function qfn(){return typeof process<"u"&&process.release&&process.release.name==="node"}function Qqt(){return BigInt(Math.floor(performance.now()*1e6))}function iF(t){return typeof t=="number"&&(t=BigInt(t)),t<Zqt?`${t}ns`:t<Yqt?`${t/Zqt}\u03BCs`:t<Xqt?`${t/Yqt}ms`:`${t/Xqt}s`}function g_(){return Ufn()?Qqt():qfn()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?Qqt():BigInt(0)}function HK(){return`${Bfn}-${zfn++}`}function J2(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 t2t(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function Z2(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 Cce(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 Y2(t,e){return Cce(t,[e])[e]}functi
- `),Wfn={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-09-01 12:32:47 +08:00
- ${Vfn}`,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-09-01 12:32:47 +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 r2t(t){return{raw:Number(t),formatted:iF(t)}}function n2t(t){if(t.id){if(typeof t.id!="string")throw Xt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return HK()}function fBe(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(kP(n)){let i=mBe(n);if(!Array.isArray(o)||o.length!==i)throw Xt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(X2(n)){if(!Array.isArray(o))return r;let i=pBe(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=fBe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function o2t(t){return t==="geopoint"}function kP(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function X2(t){return typeof t=="string"&&Kfn[t]}function pBe(t){return Gfn[t]}function mBe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Xt("INVALID_VECTOR_VALUE",t);case e<=0:throw Xt("INVALID_VECTOR_SIZE",t);default:return e}}var Kfn,Gfn,VK=b(()=>{Gc();du();du();Kfn={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Gfn={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function i2t(){return{idToInternalId:new Map,internalIdToId:[],save:Jfn,load:Zfn}}function Jfn(t){return{internalIdToId:t.internalIdToId}}function Zfn(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 zi(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?zi(t,e.toString()):e}function Ry(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var Ny=b(()=>{});function Xfn(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Qfn(t,e){let r=zi(t.sharedInternalDocumentStore,e);return t.docs[r]}function epn(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=zi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function tpn(t){return t.docs}function rpn(t,e,r){let n=zi(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function npn(t,e){let r=zi(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function opn(t){return t.count}function ipn(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function apn(t){return{docs:t.docs,count:t.count}}function a2t(){return{create:Xfn,get:Qfn,getMultiple:epn,getAll:tpn,store:rpn,remove:npn,count:opn,load:ipn,save:apn}}var hBe=b(()=>{Ny()});function u2t(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),Xt("PLUGIN_CRASHED")}return r}var s2t,l2t=b(()=>{Gc();s2t=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function y_(t,e,r,n){if(t.some(Mu))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function aF(t,e,r){if(t.some(Mu))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}},d4=class t extends nze{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-09-01 12:32:47 +08:00
`," ",""];throw new Error(`Language ${e} is not supported.`)}}});var L3t=b(()=>{D3t()});var F3t=b(()=>{L3t()});var k3t=b(()=>{F3t()});var oze=b(()=>{k3t()});var $3t,uO,Ade,B3t=b(()=>{or();oF();Gt();I3t();bt();ir();$3t=j(a4());oze();uO=require("obsidian");rh();Ade=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=oe();this.rateLimiter=new eG(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,wa(async()=>{let i=oe();this.rateLimiter=new eG(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 uO.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 uO.Notice("No valid content to index."),0;for(let s=0;s<a.length&&!this.state.isIndexingCancelled;s+=this.embeddingBatchSize){await this.handlePause();let u=a.slice(s,s+this.embeddingBatchSize);try{await this.rateLimiter.wait();let l=await n.embedDocuments(u.map(f=>f.content));if(!l||l.length!==u.length)throw new Error(`Embedding model returned ${l?.length??0} embeddings for ${u.length} documents`);for(let f=0;f<u.length;f++){let p=u[f],h=l[f];if(!h||!Array.isArray(h)||h.length===0){ie(`Invalid embedding for document ${p.fileInfo.path}: ${h}`),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}try{await this.dbOps.upsert({...p.fileInfo,id:this.getDocHash(p.content),content:p.content,embedding:h,created_at:Date.now(),nchars:p.content.length}),this.state.processedFiles.add(p.fileInfo.path)}catch(m){this.handleError(m,{filePath:p.fileInfo.path,errors:r}),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}}this.state.indexedCount=this.state.processedFiles.size,this.updateIndexingNoticeMessage();let c=Math.floor((this.state.indexedCount-u.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>c&&(await this.dbOps.saveDB(),console.log("Copilot index checkpoint save completed."))}catch(l){if(this.handleError(l,{filePath:u?.[0]?.fileInfo?.path,errors:r,batch:u}),this.isRateLimitError(l))break}}return this.finalizeIndexing(r),setTimeout(()=>{this.dbOps.saveDB().then(()=>{B("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{ie("Background integrity check failed:",s)})}).catch(s=>{ie("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=Iu.getModelName(r),o=d4.fromLanguage("markdown",{chunkSize:Mj}),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:tu(new Date(a.stat.ctime)).display,modified:tu(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-09-01 12:32:47 +08:00
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,$3t.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=vc(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>_s(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(!_s(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 B([`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 uO.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 uO.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=oe(),o=th(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...XK(this.app),...th(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 uO.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 uO.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 uO.Notice("Indexing cancelled");return}e.length>0?new uO.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new uO.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(),oe().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 Qf={};os(Qf,{default:()=>zP});var rG,zP,Jc=b(()=>{xE();oF();bt();rG=require("obsidian");Ede();A3t();B3t();zP=class t{constructor(){this.embeddingsManager=Iu.getInstance(),this.dbOps=new BP(app),this.indexOps=new Ade(app,this.dbOps,this.embeddingsManager),this.eventHandler=new Pde(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={...oe()};let e=async()=>{let r=oe(),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())}};wa(()=>{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 rn&&r.message.includes("Vault adapter not available")&&(e--,e>0)){await new Promise(n=>setTimeout(n,100));continue}new rG.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(),rG.Platform.isMobile&&oe().disableIndexOnMobile?(new rG.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){await this.waitForInitialization(),aw
2025-07-05 20:48:33 +08:00
${e.join(`
2025-09-01 12:32:47 +08:00
`)}`)}}});var fR,Mde=b(()=>{mze();My();ir();Gt();fR=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Ji.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=>!jet(n))}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){let n=eo(r);return ie(`Error processing URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processUrls(e){let r=this.extractUrls(e),n="",o=[],i={};if(r.length===0)return{urlContext:n,imageUrls:o,processedErrorUrls:i};let a=r.map(async u=>{if(await cO.isImageUrl(u,app.vault))return o.push(u),null;if(!this.mentions.has(u)){let l=await this.processUrl(u);this.mentions.set(u,{type:"url",original:u,processed:l.response,error:l.error})}return this.mentions.get(u)});return(await Promise.all(a)).forEach(u=>{u?.processed&&(n+=`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
<url_content>
<url>${u.original}</url>
<content>
${u.processed}
</content>
2025-09-01 12:32:47 +08:00
</url_content>`),u?.error&&(i[u.original]=u.error)}),{urlContext:n,imageUrls:o,processedErrorUrls:i}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}}});var X3t,Rde,Q3t=b(()=>{Gt();X3t=j(a4()),Rde=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)||(B("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,X3t.MD5)(r).toString();return B("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)){B("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return B("Cache miss for PDF:",e.path),null}catch(r){return ie("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);B("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){ie("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);B("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ie("Error clearing PDF cache:",e)}}}});function UP(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 eHt(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var oG=b(()=>{});var tHt,jde,rHt,Nde,nHt=b(()=>{tHt=require("obsidian"),Nde=class{constructor(e){this.vault=e;bwe(this,jde)}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 tHt.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];SGe(this,jde,rHt).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-09-01 12:32:47 +08:00
`,o}};jde=new WeakSet,rHt=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 oHt,hze,Dde,gze,m4,iG,pR,Lde=b(()=>{Q3t();nG();Gt();oG();oHt=require("obsidian");nHt();hze=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},Dde=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=Rde.getInstance()}async parseFile(e,r){try{B("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return B("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);B("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 ie(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){B("Clearing PDF cache"),await this.pdfCache.clear()}},gze=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{B("Parsing Canvas file:",e.path);let n=new Nde(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return ie(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},m4=class m4{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=b_.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){m4.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(B(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw ie("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(n)return B(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;B(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);B(`[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-09-01 12:32:47 +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),B(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw ie(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),UP(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-m4.lastRateLimitNoticeTime<6e4)return;m4.lastRateLimitNoticeTime=r;let n=eHt(e);new oHt.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(){B("Cache clearing is now handled at the project level")}};m4.lastRateLimitNoticeTime=0;iG=m4,pR=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new hze),this.registerParser(new iG(e,o)),n||this.registerParser(new Dde(e)),this.registerParser(new gze)}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 Dde&&await e.clearCache()}}});var kde={};os(kde,{createToolCallMarker:()=>Fde,decodeResultFromMarker:()=>bze,decodeToolCallMarkerResults:()=>ehn,ensureEncodedToolCallMarkerResults:()=>thn,parseToolCallMarkers:()=>_ze,updateToolCallMarker:()=>vze});function yze(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function bze(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function ehn(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):(ENC:[\s\S]*?)-->/g,(e,r,n)=>{let o=bze(n)||n;return`<!--TOOL_CALL_END:${r}:${o}-->`})}function thn(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):([\s\S]*?)-->/g,(e,r,n)=>{if(n.startsWith("ENC:"))return e;let o=yze(n);return`<!--TOOL_CALL_END:${r}:${o}-->`})}function _ze(t){let e=[],r=/<!--TOOL_CALL_START:([^:]+):([^:]+):([^:]+):([^:]+):([^:]*):([^:]+)-->([\s\S]*?)<!--TOOL_CALL_END:\1:([\s\S]*?)-->/g,n=0,o;for(;(o=r.exec(t))!==null;){o.index>n&&e.push({type:"text",content:t.slice(n,o.index)});let[i,a,s,u,l,c,d,f,p]=o;e.push({type:"toolCall",content:f,toolCall:{id:a,toolName:s,displayName:u,emoji:l,confirmationMessage:c||void 0,isExecuting:d==="true",result:bze(p)||void 0,startIndex:o.index,endIndex:o.index+i.length}}),n=o.index+i.length}return n<t.length&&e.push({type:"text",content:t.slice(n)}),e.length===0&&e.push({type:"text",content:t}),{segments:e}}function Fde(t,e,r,n,o="",i=!0,a="",s=""){let u=s&&yze(s);return`<!--TOOL_CALL_START:${t}:${e}:${r}:${n}:${o}:${i}-->${a}<!--TOOL_CALL_END:${t}:${u}-->`}function vze(t,e,r){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(<!--TOOL_CALL_START:${n}:[^:]+:[^:]+:[^:]+:[^:]*:)true(-->[\\s\\S]*?<!--TOOL_CALL_END:${n}:)[\\s\\S]*?-->`,"g"),i=yze(r);return t.replace(o,`$1false$2${i}-->`)}var h4=b(()=>{});var iHt,qP,sG=b(()=>{or();Gt();ir();iHt=require("obsidian"),qP=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a,s){e&&!(n.signal.aborted&&n.signal.reason==="new-chat")?(await this.chainManager.memoryManager.getMemory().saveContext({input:r.message},{output:s||e}),o({message:e,sender:Zg,isVisible:!0,timestamp:tu(new Date),sources:a}),i("")):n.signal.reason==="new-chat"&&i(""),B(`==== Chat Memory ====
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(u=>u.content));try{let{decodeToolCallMarkerResults:u}=await Promise.resolve().then(()=>(h4(),kde)),l=u(e);B(`==== Final AI Response ====
2025-08-30 08:29:39 +08:00
`,l)}catch{B(`==== Final AI Response ====
2025-09-01 12:32:47 +08:00
`,e)}return e}async handleError(e,r,n){let o=eo(e);ie("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}`,ie(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-08-30 08:29:39 +08:00
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
2025-09-01 12:32:47 +08:00
Error Details: `+s),r({message:s,isErrorMessage:!0,sender:Zg,isVisible:!0,timestamp:tu(new Date)})}else new iHt.Notice(s),ie(i)}}});var __,g4=b(()=>{__=class{constructor(e,r){this.updateCurrentAiMessage=e;this.modelAdapter=r;this.hasOpenThinkBlock=!1;this.fullResponse="";this.shouldTruncate=!1}handleClaude37Chunk(e){let r="";for(let n of e)switch(n.type){case"text":r+=n.text;break;case"thinking":return this.hasOpenThinkBlock||(this.fullResponse+=`
2025-08-30 08:29:39 +08:00
<think>`,this.hasOpenThinkBlock=!0),n.thinking!==void 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-09-01 12:32:47 +08:00
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content),!0):!1}processChunk(e){if(this.shouldTruncate)return;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.modelAdapter?.shouldTruncateStreaming?.(this.fullResponse)&&(this.shouldTruncate=!0,this.fullResponse=this.truncateToLastCompleteToolCall(this.fullResponse)),this.updateCurrentAiMessage(this.fullResponse)}truncateToLastCompleteToolCall(e){let r=e.lastIndexOf("</use_tool>");if(r===-1)return e;let n=e.substring(0,r+11);return this.modelAdapter?.sanitizeResponse?this.modelAdapter.sanitizeResponse(n,1):n}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.updateCurrentAiMessage(this.fullResponse)),this.fullResponse}}});var uG,aHt=b(()=>{or();Gt();bt();ir();sG();g4();uG=class extends qP{async run(e,r,n,o,i){let a=new __(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=QB(l),d=[],f=Mf(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:eI(p),content:f});for(let m of c)d.push({role:m.role,content:m.content});if(e.content&&Array.isArray(e.content)){let m=e.content.map(g=>g.type==="text"?{...g,text:e.message}:g);d.push({role:"user",content:m})}else d.push({role:"user",content:e.message});B(`==== Final Request to AI ====
`,d);let h=await Od(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let m of h){if(r.signal.aborted){B("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(m)}}catch(u){u.name==="AbortError"||r.signal.aborted?B("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)}}});var y4,sHt=b(()=>{UA();Tf();vv();y4=class extends Un{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,In(r))}async getRelevantDocuments(e,r){let n=In(T6(r)),i=await(await gu.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}}}});var wze=b(()=>{sHt()});var $de={};os($de,{HybridRetriever:()=>lG});var lG,cG=b(()=>{My();oF();mR();Gt();Jc();or();bt();ir();tG();ZA();wze();Bce();Ede();lG=class extends y4{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=Em.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
2025-08-30 08:29:39 +08:00
Question: {question}
2025-09-01 12:32:47 +08:00
Passage:`)}async getRelevantDocuments(r,n){return Od(async()=>{let o=Jg(r,app.vault),i=o.map(m=>m.basename),a=[...new Set([...this.options.salientTerms,...i])],s=await this.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=await this.rewriteQuery(r));let l=await this.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)return oe().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((m,g)=>{let y=g.metadata.score;return typeof y=="number"&&!isNaN(y)?Math.max(m,y):m},0),p=c.every(m=>typeof m.metadata.score!="number"||isNaN(m.metadata.score)),h=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return h&&(d=(await Ji.getInstance().rerank(r,c.map(g=>g.pageContent.slice(0,3e3)))).response.data.map(g=>({...c[g.index],metadata:{...c[g.index].metadata,rerank_score:g.relevance_score}}))),oe().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
2025-08-30 08:29:39 +08:00
Original Query: `,r),console.log("Rewritten Query: ",u)),console.log(`
2025-09-01 12:32:47 +08:00
Explicit Chunks: `,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),h?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}async rewriteQuery(r){try{return await Cee(async()=>{let n=await this.queryRewritePrompt.format({question:r}),o=await Od(()=>Vd.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?Aj(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)},oz)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await zP.getInstance().getDb(),a=await BP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new nh({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 zP.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&&(oe().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);B("==== Daily note date range: ====",d[0],d[d.length-1]);let f=Jg(d.join(", "),app.vault),h=(await this.getExplicitChunks(f)).map(w=>({...w,metadata:{...w.metadata,includeInContext:!0}}));B("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let g=(await Kp(a,s)).hits.map(w=>new nh({pageContent:w.document.content,metadata:{...w.document.metadata,score:w.score,path:w.document.path,mtime:w.document.mtime,ctime:w.document.ctime,title:w.document.title,id:w.document.id,embeddingModel:w.document.embeddingModel,tags:w.document.tags,extension:w.document.extension,created_at:w.document.created_at,nchars:w.document.nchars}})),y=[...h,...g];return Array.from(new Set(y.map(w=>w.metadata.id))).map(w=>y.find(S=>S.metadata.id===w)).filter(w=>w!==void 0)}oe().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await Kp(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 nh({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 Iu.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}}))}}});var Sze,xze,hR,Bde=b(()=>{Gt();or();Sze=require("obsidian");oze();xze={maxChars:Mj,overlap:0,maxBytesTotal:10*1024*1024},hR=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0;this.splitter=d4.fromLanguage("markdown",{chunkSize:Mj,chunkOverlap:0,separators:[`
2025-08-30 08:29:39 +08:00
`,`
2025-09-01 12:32:47 +08:00
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return Bt("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(Bt("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let n=e.filter(a=>!(!a||typeof a!="string"||a.includes("..")||a.startsWith("/")));if(n.length===0)return Bt("ChunkManager: No valid note paths provided"),[];let o={...xze,...r},i=[];for(let a of n){let s=this.cache.get(a);if(!s&&(s=await this.generateChunksForNote(a,o),s.length>0)){let u=this.calculateChunkBytes(s);this.memoryUsage+u<=o.maxBytesTotal?(this.cache.set(a,s),this.memoryUsage+=u):Bt(`ChunkManager: Skipping cache for ${a}, would exceed memory budget`)}i.push(...s)}return B(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return Bt("ChunkManager: Failed to get chunks",n),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[r]=e.split("#"),o=(await this.getValidatedChunks(r)).find(i=>i.id===e);return o||Bt(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r=this.cache.get(e);if(!r&&(B(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return Bt(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof Sze.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(B(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.regenerateChunks(e),!r||r.length===0)?(Bt(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):r}getChunkTextSync(e){let[r]=e.split("#"),n=this.cache.get(r);return n?n.find(i=>i.id===e)?.content||"":(Bt(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),"")}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,xze);if(r.length>0){let n=this.calculateChunkBytes(r);if(this.memoryUsage+n<=xze.maxBytesTotal){let o=this.cache.get(e);o&&(this.memoryUsage-=this.calculateChunkBytes(o)),this.cache.set(e,r),this.memoryUsage+=n}else Bt(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return Bt(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,B("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof Sze.TFile))return[];let o=await this.safeReadFile(n);if(!o?.trim())return[];let a=(this.app.metadataCache.getFileCache(n)?.headings||[]).slice().sort((l,c)=>l.position.start.offset-c.position.start.offset),s=[],u=0;if(a.length===0){let l=await this.processContentSection(o,"",n,u,r);return s.push(...l),s}for(let l=0;l<a.length;l++){let c=a[l],d=a[l+1],f=c.position.start.offset,p=d?.position.start.offset||o.length,h=o.substring(f,p),m=await this.processContentSection(h,c.heading,n,u,r);s.push(...m),u+=m.length}return s}catch(n){return Bt(`ChunkManager: Failed to chunk note ${e}`,n),[]}}async processContentSection(e,r,n,o,i){let a=n.basename,s=[],u=`
2025-08-30 08:29:39 +08:00
NOTE TITLE: [[${a}]]
NOTE BLOCK CONTENT:
2025-09-01 12:32:47 +08:00
`,l=u+e;if(l.length<=i.maxChars){let c=this.generateChunkId(n.path,o),d=this.calculateContentHash(l);s.push({id:c,notePath:n.path,chunkIndex:o,content:l,contentHash:d,title:a,heading:r,mtime:n.stat.mtime})}else try{(await this.splitter.createDocuments([e],[],{chunkHeader:u,appendChunkOverlapHeader:i.overlap>0})).forEach((d,f)=>{let p=o+f,h=this.generateChunkId(n.path,p),m=this.calculateContentHash(d.pageContent);s.push({id:h,notePath:n.path,chunkIndex:p,content:d.pageContent,contentHash:m,title:a,heading:r,mtime:n.stat.mtime})})}catch(c){Bt(`ChunkManager: Failed to split section in ${n.path}`,c);let d=this.generateChunkId(n.path,o),f=this.calculateContentHash(l);s.push({id:d,notePath:n.path,chunkIndex:o,content:l,contentHash:f,title:a,heading:r,mtime:n.stat.mtime})}return s}calculateChunkBytes(e){return e.reduce((r,n)=>r+Buffer.byteLength(n.content,"utf8"),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(r){return Bt(`ChunkManager: Failed to read ${e.path}`,r),""}}generateChunkId(e,r){return`${e}#${r}`}calculateContentHash(e){let r=e.length.toString(16),n=e.slice(0,32).replace(/\s/g,"").substring(0,8);return r+n}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}}});var Cze=x(()=>{});function Wd(t,e,r){let n=typeof r,o=typeof t;if(n!=="undefined"){if(o!=="undefined"){if(r){if(o==="function"&&n===o)return function(s){return t(r(s))};if(e=t.constructor,e===r.constructor){if(e===Array)return r.concat(t);if(e===Map){var i=new Map(r);for(var a of t)i.set(a[0],a[1]);return i}if(e===Set){a=new Set(r);for(i of t.values())a.add(i);return a}}}return t}return r}return o==="undefined"?e:t}function b4(t,e){return typeof t>"u"?e:t}function zs(){return Object.create(null)}function v_(t){return typeof t=="string"}function fG(t){return typeof t=="object"}function pG(t,e){if(v_(e))t=t[e];else for(let r=0;t&&r<e.length;r++)t=t[e[r]];return t}function x4(t={}){if(!this||this.constructor!==x4)return new x4(...arguments);if(arguments.length)for(t=0;t<arguments.length;t++)this.assign(arguments[t]);else this.assign(t)}function hF(t){t.F=null,t.B.clear(),t.D.clear()}function Mze(t,e,r){r||(e||typeof t!="object"?typeof e=="object"&&(r=e,e=0):r=t),r&&(t=r.query||t,e=r.limit||e);let n=""+(e||0);r&&(n+=(r.offset||0)+!!r.context+!!r.suggest+(r.resolve!==!1)+(r.resolution||this.resolution)+(r.boost||0)),t=(""+t).toLowerCase(),this.cache||(this.cache=new bF);let o=this.cache.get(t+n);if(!o){let i=r&&r.cache;i&&(r.cache=!1),o=this.search(t,e,r),i&&(r.cache=i),this.cache.set(t+n,o)}return o}function bF(t){this.limit=t&&t!==!0?t:1e3,this.cache=new Map,this.h=""}function pHt(t,e,r,n){let o=[];for(let i=0,a;i<t.index.length;i++)if(a=t.index[i],e>=a.length)e-=a.length;else{e=a[n?"splice":"slice"](e,r);let s=e.length;if(s&&(o=o.length?o.concat(e):e,r-=s,n&&(t.length-=s),!r))break;e=0}return o}function S4(t){if(!this||this.constructor!==S4)return new S4(t);this.index=t?[t]:[],this.length=t?t.length:0;let e=this;return new Proxy([],{get(r,n){if(n==="length")return e.length;if(n==="push")return function(o){e.index[e.index.length-1].push(o),e.length++};if(n==="pop")return function(){if(e.length)return e.length--,e.index[e.index.length-1].pop()};if(n==="indexOf")return function(o){let i=0;for(let a=0,s,u;a<e.index.length;a++){if(s=e.index[a],u=s.indexOf(o),u>=0)return i+u;i+=s.length}return-1};if(n==="includes")return function(o){for(let i=0;i<e.index.length;i++)if(e.index[i].includes(o))return!0;return!1};if(n==="slice")return function(o,i){return pHt(e,o||0,i||e.length,!1)};if(n==="splice")return function(o,i){return pHt(e,o||0,i||e.length,!0)};if(n==="constructor")return Array;if(typeof n!="symbol")return(r=e.index[n/2**31|0])&&r[n]},set(r,n,o){return r=n/2**31|0,(e.index[r]||(e.index[r]=[]))[n]=o,e.length++,!0}})}function w_(t=8){if(!this||this.constructor!==w_)return new w_(t);this.index=zs(),this.h=[],this.size=0,t>32?(this.B=xHt,this.A=BigInt(t)):(this.B=wHt,this.A=t)}function x_(t=8){if(!this||this.constructor!==x_)return new x_(t);this.index=zs(),this.h=[],this.size=0,t>32?(this.B=xHt,this.A=
`).map(l=>l.trim()),o=[r],i=new Set,a=null;for(let l of n)if(!(!l||l==="")){if(l.toUpperCase().includes("QUERIES")){a="queries";continue}if(l.toUpperCase().includes("TERMS")||l.toUpperCase().includes("KEYWORDS")){a="terms";continue}if(a==="queries"&&o.length<=this.config.maxVariants){let c=l.replace(/^[-•*\d.)\s]+/,"").trim();c&&c!==r&&o.push(c)}else if(a==="terms"){let c=l.replace(/^[-•*\d.)\s]+/,"").trim().toLowerCase();c&&this.isValidTerm(c)&&i.add(c)}}if(o.length===1&&i.size===0)for(let l of n.slice(0,this.config.maxVariants))l&&!l.toUpperCase().includes("QUERY")&&o.push(l);let s=this.extractSalientTermsFromOriginal(r),u=o.slice(1);return{queries:o.slice(0,this.config.maxVariants+1),salientTerms:s,originalQuery:r,expandedQueries:u.slice(0,this.config.maxVariants),expandedTerms:Array.from(i)}}fallbackExpansion(e){let r=this.extractTermsFromQueries([e]),n=new Set([e]);for(let i of r)if(i.length>=3){let a=efe.generateVariants(i);for(let s of a.slice(0,3))if(s!==i){let u=e.toLowerCase().replace(new RegExp(`\\b${i}\\b`,"gi"),s);u!==e.toLowerCase()&&n.add(u)}}return{queries:[e],salientTerms:r,originalQuery:e,expandedQueries:[],expandedTerms:[]}}extractTermsFromQueries(e){let r=new Set;for(let n of e){let o=n.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/);for(let i of o)this.isValidTerm(i)&&(r.add(i),i.includes("-")&&i.split("-").forEach(a=>{this.isValidTerm(a)&&r.add(a)}))}return Array.from(r)}isValidTerm(e){return e.length>=this.config.minTermLength&&/^[\w-]+$/.test(e)}cacheResult(e,r){if(this.cache.size>=this.config.cacheSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,r)}clearCache(){this.cache.clear(),B("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}async expandQueries(e){return(await this.expand(e)).queries}};rfe.PROMPT_TEMPLATE=`Generate alternative search queries and semantically related terms for the following query:
2025-08-30 08:29:39 +08:00
"{query}"
Instructions:
1. Generate {count} alternative search queries that capture the same intent
2. Extract semantically related terms that someone might use when searching for this topic
3. Include:
- Keywords from the original query
- Synonyms and related concepts
- Domain-specific terminology
- Associated terms someone might use
4. Keep the SAME LANGUAGE as the original query
5. Focus on NOUNS and meaningful concepts
6. EXCLUDE common action verbs in ANY language (find, search, get, \u67E5\u627E, chercher, buscar, etc.)
Example: "find my piano notes"
- Queries: "piano lesson notes", "piano practice sheets"
- Terms: piano, notes, music, sheet, practice, lesson, piece, scales, exercises
Example: "typescript interfaces"
- Queries: "typescript type definitions", "typescript contracts"
- Terms: typescript, interfaces, types, definitions, contracts, typing, declarations
Example: "\u67E5\u627E\u6211\u7684\u7B14\u8BB0" (Chinese)
- Queries: "\u6211\u7684\u5B66\u4E60\u7B14\u8BB0", "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
- Terms: \u7B14\u8BB0, \u6587\u6863, \u8BB0\u5F55, \u8D44\u6599, \u5B66\u4E60, \u5907\u5FD8\u5F55 (keep in Chinese)
Example: "rechercher documents projet" (French)
- Queries: "documents de projet", "fichiers projet"
- Terms: documents, projet, fichiers, dossiers, archives (keep in French)
Format your response using XML tags:
<queries>
<query>alternative query 1</query>
<query>alternative query 2</query>
</queries>
<terms>
<term>keyword1</term>
<term>keyword2</term>
<term>keyword3</term>
<term>related_term1</term>
<term>related_term2</term>
2025-09-01 12:32:47 +08:00
</terms>`;tfe=rfe});var gG,nfe,LHt=b(()=>{Gt();rh();gG=class gG{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=vc(),a=this.app.vault.getMarkdownFiles().filter(d=>_s(d,n,o)),s=new Set,u=gG.CONFIG.BATCH_SIZE,l=e.map(d=>d.toLowerCase());for(let d=0;d<a.length&&s.size<r;d+=u){let f=a.slice(d,d+u);await Promise.all(f.map(async p=>{if(!(s.size>=r))try{let h=p.path.toLowerCase(),m=!1;for(let g of l)if(h.includes(g)){s.add(p.path),m=!0;break}if(!m){let y=(await this.app.vault.cachedRead(p)).toLowerCase();for(let _ of l)if(y.includes(_)){s.add(p.path);break}}}catch(h){B(`GrepScanner: Skipping file ${p.path}: ${h}`)}})),d%gG.CONFIG.YIELD_INTERVAL===0&&await new Promise(p=>setTimeout(p,0))}let c=Array.from(s).slice(0,r);return c.length>0&&B(` Grep: ${c.length} files match [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`),c}async grep(e,r=200){return this.batchCachedReadGrep([e],r)}async fileContainsAny(e,r){try{let n=e.path.toLowerCase(),o=0;for(let s of r)n.includes(s.toLowerCase())&&o++;if(o>0)return!0;let a=(await this.app.vault.cachedRead(e)).toLowerCase();return r.some(s=>a.includes(s.toLowerCase()))}catch{return!1}}};gG.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};nfe=gG});var _hn,ofe,FHt=b(()=>{Gt();_hn={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},ofe=class{constructor(e){this.config=_hn;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let r=this.calculateFolderStats(e);return this.logBoostedFolders(r),e.map(n=>{let o=this.extractFolder(n.id),i=r.get(o);if(i){let a=n.score*i.boostFactor;return{...n,score:a,explanation:n.explanation?{...n.explanation,folderBoost:{folder:i.folderPath,documentCount:i.documentCount,totalDocsInFolder:i.totalDocsInFolder,relevanceRatio:i.relevanceRatio,boostFactor:i.boostFactor},finalScore:a}:void 0}}return n})}calculateFolderStats(e){let r=new Map;for(let i of e){let a=this.extractFolder(i.id);r.set(a,(r.get(a)||0)+1)}let n=this.getTotalDocsPerFolder(),o=new Map;for(let[i,a]of r.entries()){let s=n.get(i)||a,u=a/s;if(a>=this.config.minDocsForBoost&&u>=this.config.minRelevanceRatio){let c=1+(1+Math.log2(a+1)-1)*Math.sqrt(u),d=Math.min(c,this.config.maxBoostFactor);o.set(i,{folderPath:i,documentCount:a,totalDocsInFolder:s,relevanceRatio:u,boostFactor:d})}}return o}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let r=this.app.vault.getMarkdownFiles();for(let n of r){let o=this.extractFolder(n.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let r=Array.from(e.values()).sort((n,o)=>o.relevanceRatio-n.relevanceRatio);r.length>0&&(B(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);B(` ${n.folderPath||"(root)"}: ${n.documentCount}/${n.totalDocsInFolder} docs (${o}% relevant, ${n.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var vhn,ife,kHt=b(()=>{Gt();vhn={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},ife=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...vhn,...r}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let r=this.filterCandidates(e);if(r.length<2)return e;let n=new Set(r.map(s=>s.id)),o=new Map;for(let s of r){let u=this.calculateConnections(s.id,n);o.set(s.id,u)}let i=e.map(s=>{let u=o.get(s.id);return!u||u.boostMultiplier===1?s:{...s,score:s.score*u.boostMultiplier,explanation:s.explanation?{...s.explanation,graphConnections:{backlinks:u.backlinks.length,coCitations:u.coCitations.length,sharedTags:u.sharedTags.length,score:u.connectionScore,boostMultiplier:u.boostMultiplier}}:void 0}}),a=i.filter(s=>{let u=o.get(s.id);return u&&u.boostMultiplier>1});return a.length>0&&B(`GraphBoostCalculator: Boosted ${a.length} notes based on connections`),i}calculateConnections(e,r){let n=this.fin
`):[]}};dg=new WeakMap;WP.NEWLINE_CHARS=new Set([`
`,"\r"]);WP.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function EG(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 qze=b(()=>{});async function*Ihn(t,e){if(!t.body)throw e.abort(),new Vr("Attempted to iterate over a response with no body");let r=new Hze,n=new WP,o=EG(t.body);for await(let i of Mhn(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*Mhn(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=YHt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Rhn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var dO,Hze,pfe=b(()=>{yG();C_();Uze();qze();VP();C_();dO=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 Ihn(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 Zc.generate(void 0,`SSE Error: ${a.data}`,a.data,Vze(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 WP,s=EG(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 $ze({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?.()}})}};Hze=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]=Rhn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function XHt(t,e,r){if(t=await t,jhn(t))return t;if(Nhn(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=PG(o)?[await o.arrayBuffer()]:[o];return new ufe(i,e,r)}let n=await Dhn(t);if(e||(e=Fhn(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ufe(n,e,r)}async function Dhn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(PG(t))e.push(await t.arrayBuffer());else if(khn(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Lhn(t)}`);return e}function Lhn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Fhn(t){return Wze(t.name)||Wze(t.filename)||Wze(t.path)?.split(/[\\/]/).pop()}var Nhn,jhn,PG,Wze,khn,Kze,Gze=b(()=>{yG();yG();Nhn=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",jhn=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&PG(t),PG=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";Wze=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},khn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Kze=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody"});async function nVt(t){let{response:e}=t;if(t.options.stream)return E4("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):dO.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 E4("response",e.status,e.url,e.headers,i),oVt(i,e)}let o=await e.text();return E4("response",e.status,e.url,e.headers,o),o}function oVt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}function Hhn(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function TG(t){if(!t)return!0;for(let e in t)return!1;return!0}function iVt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rVt(t,e){for(let r in e){if(!iVt(e,r))continue;let n=r.toLowerCase();if(!n)continue;let o=e[r];o===null?delete t[n]:o!==void 0&&(t[n]=o)}}function E4(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${t}`,...e)}var Bhn,zhn,mfe,gfe,yfe,bfe,Zze,Vze,Uhn,Dy,qhn,QHt,eVt,tVt,Vhn,Whn,Khn,Ghn,Jhn,Jze,dfe,_fe,Zhn,aVt,Yhn,hfe,VP=b(()=>{zHt();pfe();C_();yG();Gze();Bhn=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},zhn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private ac
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 Pfe.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}})}};wR.Batches=SF;wR.BetaMessageBatchesPage=A4});var pO,sUe=b(()=>{KP();Yze();Yze();aUe();aUe();pO=class extends Yc{constructor(){super(...arguments),this.models=new xF(this._client),this.messages=new wR(this._client)}};pO.Models=xF;pO.BetaModelInfosPage=P4;pO.Messages=wR});var CF,uUe=b(()=>{KP();CF=class extends Yc{create(e,r){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}}});var OF,R4,lUe=b(()=>{KP();VP();AG();Xze();C_();OF=class extends Yc{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 Dy(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",R4,{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 Vr(`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)=>T4.fromResponse(i.response,i.controller))}},R4=class extends fO{};OF.MessageBatchesPage=R4});var tp,Bn,Fy,xR,DG,Tfe,LG,FG,Afe,kG,JP,$G,Ife,Mfe,N4,Rfe,Nfe,cUe,pVt,dUe,fUe,pUe,mUe,mVt,hVt,jfe,gVt=b(()=>{C_();pfe();eUe();tp=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},Bn=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)},hVt="__json_buf",jfe=class t{constructor(){Fy.add(this),this.messages=[],this.receivedMessages=[],xR.set(this,void 0),this.controller=new AbortController,DG.set(this,void 0),Tfe.set(this,()=>{}),LG.set(this,()=>{}),FG.set(this,void 0),Afe.set(this,()=>{}),kG.set(this,()=>{}),JP.set(this,{}),$G.set(this,!1),Ife.set(this,!1),Mfe.set(this,!1),N4.set(this,!1),Rfe.set(this,void 0),Nfe.set(this,void 0),dUe.set(this,e=>{if(tp(this,Ife,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Kd),e instanceof Kd)return tp(this,Mfe,!0,"f"),this._emit("abort",e);if(e instanceof Vr)return this._emit("error",e);if(e instanceof Error){let r=new Vr(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Vr(String(e)))}),tp(this,DG,new Promise((e,r)=>{tp(this,Tfe,e,"f"),tp(this,LG,r,"f")}),"f"),tp(this,FG,new Promise((e,r)=>{tp(this,Afe,e,"f"),tp(this,kG,r,"f")}),"f"),Bn(this,DG,"f").catch(()=>{}),Bn(this,FG,"f").catch(()=>{})}get response(){return Bn(this,Rfe,"f")}get request_id(){return Bn(this,Nfe,"f")}async withResponse(){let e=await Bn(this,DG,"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;
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 jfe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},yVt={"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"};ZP.Batches=OF;ZP.MessageBatchesPage=R4});var SR,EF,gUe=b(()=>{KP();VP();AG();SR=class extends Yc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Dy(e)?this.list({},e):this._client.getAPIList("/v1/models",EF,{query:e,...r})}},EF=class extends fO{};SR.ModelInfosPage=EF});var bVt=b(()=>{sVt();sUe();uUe();hUe();gUe()});var _Vt,Ri,Qpi,emi,vVt=b(()=>{VP();C_();Gze();bVt();uUe();gUe();sUe();hUe();Ri=class extends yfe{constructor({baseURL:e=_fe("ANTHROPIC_BASE_URL"),apiKey:r=_fe("ANTHROPIC_API_KEY")??null,authToken:n=_fe("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&aVt())throw new Vr(`It looks like you're running in a browser-like environment.
2025-08-30 08:29:39 +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-09-01 12:32:47 +08:00
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new CF(this),this.messages=new ZP(this),this.models=new SR(this),this.beta=new pO(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&&!TG(r)?r:n!=null&&!TG(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};_Vt=Ri;Ri.Anthropic=_Vt;Ri.HUMAN_PROMPT=`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
Human:`;Ri.AI_PROMPT=`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
Assistant:`;Ri.DEFAULT_TIMEOUT=6e5;Ri.AnthropicError=Vr;Ri.APIError=Zc;Ri.APIConnectionError=_R;Ri.APIConnectionTimeoutError=O4;Ri.APIUserAbortError=Kd;Ri.NotFoundError=wG;Ri.ConflictError=xG;Ri.RateLimitError=CG;Ri.BadRequestError=bG;Ri.AuthenticationError=_G;Ri.InternalServerError=OG;Ri.PermissionDeniedError=vG;Ri.UnprocessableEntityError=SG;Ri.toFile=XHt;Ri.fileFromPath=lfe;Ri.Completions=CF;Ri.Messages=ZP;Ri.Models=SR;Ri.ModelInfosPage=EF;Ri.Beta=pO;({HUMAN_PROMPT:Qpi,AI_PROMPT:emi}=Ri)});function yUe(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}var BG,bUe=b(()=>{Db();BG=class extends wj{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 Mh(`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 Mh(`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)?yUe(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 wVt(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeof t=="string"?{type:"tool",name:t}:t}var xVt=b(()=>{});function SVt(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}var CVt=b(()=>{});function OVt(t){let e=wB({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-08-30 08:29:39 +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-09-01 12:32:47 +08:00
`))}function sgn(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 Xs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Xs({content:[{type:"tool_result",content:_Ue(r.content),tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function EVt(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}}function _Ue(t){let e=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof t=="string"?t:t.map(o=>{if(Ib(o))return x6(o,ugn);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=OVt(o.image_url):a=OVt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(SVt(o))return o;if(o.type==="document")return{...o,...i?{cache_control:i}:{}};if(o.type==="thinking")return{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};if(o.type==="redacted_thinking")return{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};if(r.find(a=>a===o.type)&&"text"in o)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(e.find(a=>a===o.type)){let a={...o};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}return{...a,...i?{cache_control:i}:{}}}else throw new Error("Unsupported message content format")}})}function Dfe(t){let e=sgn(t),r;e.length>0&&e[0]._getType()==="system"&&(r=t[0].content);let o=(r!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i._getType()}" is not supported.`);if(Wi(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(EVt)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(EVt)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:_Ue(i.content)}}}else return{role:a,content:_Ue(i.content)}});return{messages:lgn(o),system:r}}function lgn(t){if(!t||t.length<=1)return t;let e=[],r=t[0],n=i=>typeof i=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){let a=t[i];o(r)&&o(a)?r={...r,content:[...n(r.content),...n(a.content)]}:(e.push(r),r=a)}return e.push(r),e}var ugn,vUe=b(()=>{$s();CVt();ugn={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=wB({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.sourc
2025-08-30 08:29:39 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-09-01 12:32:47 +08:00
`,t}function wUe(t){let e;return t.status===400&&t.message.includes("tool")?e=Lfe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=Lfe(t,"MODEL_AUTHENTICATION"):t.status===404?e=Lfe(t,"MODEL_NOT_FOUND"):t.status===429?e=Lfe(t,"MODEL_RATE_LIMIT"):e=t,e}var IVt=b(()=>{});function cgn(t){return!!(t.tools&&t.tools.length>0)}function dgn(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 fgn(t){return!!(t.thinking&&t.thinking.type==="enabled")}function pgn(t){return"input_schema"in t}function mgn(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 xUe,Ffe,MVt=b(()=>{vVt();$s();Zf();no();HC();ig();Kg();Pm();IL();ag();bUe();xVt();vUe();AVt();IVt();xUe=class extends Pu{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??lt("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 Ri(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.t
`):[]}};pg=new WeakMap;IF.NEWLINE_CHARS=new Set([`
`,"\r"]);IF.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function LUe(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 QVt=b(()=>{});async function*Ign(t,e){if(!t.body)throw e.abort(),new Ht("Attempted to iterate over a response with no body");let r=new FUe,n=new IF,o=LUe(t.body);for await(let i of Mgn(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*Mgn(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=YVt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Rgn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var gO,FUe,Vfe=b(()=>{zG();oh();XVt();QVt();yo();oh();gO=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 Ign(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 Ru(void 0,s.error,void 0,kUe(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 Ru(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 IF,s=LUe(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 IUe({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?.()}})}};FUe=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]=Rgn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function zUe(t,e,r){if(t=await t,t6t(t))return t;if(e6t(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=UG(o)?[await o.arrayBuffer()]:[o];return new Bfe(i,e,r)}let n=await jgn(t);if(e||(e=Lgn(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Bfe(n,e,r)}async function jgn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(UG(t))e.push(await t.arrayBuffer());else if(Fgn(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Dgn(t)}`);return e}function Dgn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Lgn(t){return $Ue(t.name)||$Ue(t.filename)||$Ue(t.path)?.split(/[\\/]/).pop()}var e6t,t6t,UG,Ngn,$Ue,Fgn,UUe,ky,r6t,BUe,Wfe=b(()=>{zG();zG();e6t=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",t6t=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&UG(t),UG=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",Ngn=t=>t6t(t)||e6t(t)||NUe(t);$Ue=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Fgn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",UUe=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",ky=async t=>{let e=await r6t(t.body);return MUe(e,t)},r6t=async t=>{let e=new AUe;return await Promise.all(Object.entries(t||{}).map(([r,n])=>BUe(e,r,n))),e},BUe=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(Ngn(r)){let n=await zUe(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>BUe(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>BUe(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function u6t(t){let{response:e}=t;if(t.options.stream)return XP("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):gO.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 XP("response",e.status,e.url,e.headers,a),l6t(a,e)}let i=await e.text();return XP("response",e.status,e.url,e.headers,i),i}function l6t(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}function qgn(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function c6t(t){if(!t)return!0;for(let e in t)return!1;return!0}function d6t(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function a6t(t,e){for(let r
\r `.includes(t[n]);)n++};return a()},pqe=t=>oyn(t,Qc.ALL^Qc.NUM)});function ayn(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 Ht(`missing finish_reason for choice ${d}`);let{content:h=null,function_call:m,tool_calls:g,...y}=l,_=l.role;if(!_)throw new Ht(`missing role for choice ${d}`);if(m){let{arguments:w,name:S}=m;if(w==null)throw new Ht(`missing function_call.arguments for choice ${d}`);if(!S)throw new Ht(`missing function_call.name for choice ${d}`);return{...p,message:{content:h,function_call:{arguments:w,name:S},role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:_,content:h,refusal:l.refusal??null,tool_calls:g.map((w,S)=>{let{function:C,type:E,id:P,...T}=w,{arguments:I,name:N,...M}=C||{};if(P==null)throw new Ht(`missing choices[${d}].tool_calls[${S}].id
${spe(t)}`);if(E==null)throw new Ht(`missing choices[${d}].tool_calls[${S}].type
${spe(t)}`);if(N==null)throw new Ht(`missing choices[${d}].tool_calls[${S}].function.name
${spe(t)}`);if(I==null)throw new Ht(`missing choices[${d}].tool_calls[${S}].function.arguments
${spe(t)}`);return{...T,id:P,type:E,function:{...M,name:N,arguments:I}}})}}:{...p,message:{...y,content:h,role:_,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return v6t(u,e)}function spe(t){return JSON.stringify(t)}var X4,Zi,xc,rT,Q4,IR,mqe,ipe,hqe,gqe,yqe,ape,bqe,P6t,e3,_qe=b(()=>{oh();cqe();Vfe();Z4();E6t();X4=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},Zi=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)},e3=class t extends Y4{constructor(e){super(),xc.add(this),rT.set(this,void 0),Q4.set(this,void 0),IR.set(this,void 0),X4(this,rT,e,"f"),X4(this,Q4,[],"f")}get currentChatCompletionSnapshot(){return Zi(this,IR,"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())),Zi(this,xc,"m",mqe).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)Zi(this,xc,"m",hqe).call(this,a);if(i.controller.signal?.aborted)throw new Ma;return this._addChatCompletion(Zi(this,xc,"m",ape).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Zi(this,xc,"m",mqe).call(this),this._connected();let o=gO.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Zi(this,xc,"m",ape).call(this)),Zi(this,xc,"m",hqe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Ma;return this._addChatCompletion(Zi(this,xc,"m",ape).call(this))}[(rT=new WeakMap,Q4=new WeakMap,IR=new WeakMap,xc=new WeakSet,mqe=function(){this.ended||X4(this,IR,void 0,"f")},ipe=function(r){let n=Zi(this,Q4,"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},Zi(this,Q4,"f")[r.index]=n,n)},hqe=function(r){if(this.ended)return;let n=Zi(this,xc,"m",P6t).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=Zi(this,xc,"m",ipe).call(this,i);i.finish_reason&&(Zi(this,xc,"m",yqe).call(this,i),a.current_tool_call_index!=null&&Zi(this,xc,"m",gqe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Zi(this,xc,"m",yqe).call(this,i),a.current_tool_call_index!=null&&Zi(this,xc,"m",gqe).call(this,i,a.current_tool_call_index)),a.cur
2025-08-30 08:29:39 +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-09-01 12:32:47 +08:00
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new kF(this),this.chat=new eT(this),this.embeddings=new $F(this),this.files=new RR(this),this.images=new VF(this),this.audio=new bO(this),this.moderations=new KF(this),this.models=new jR(this),this.fineTuning=new T_(this),this.vectorStores=new gg(this),this.beta=new P_(this),this.batches=new PR(this),this.uploads=new kR(this),this.responses=new FR(this),this.evals=new xO(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 PUe(e,{arrayFormat:"brackets"})}};K6t=Tr;Tr.OpenAI=K6t;Tr.DEFAULT_TIMEOUT=6e5;Tr.OpenAIError=Ht;Tr.APIError=Ru;Tr.APIConnectionError=YP;Tr.APIConnectionTimeoutError=fg;Tr.APIUserAbortError=Ma;Tr.NotFoundError=F4;Tr.ConflictError=k4;Tr.RateLimitError=B4;Tr.BadRequestError=j4;Tr.AuthenticationError=D4;Tr.InternalServerError=z4;Tr.PermissionDeniedError=L4;Tr.UnprocessableEntityError=$4;Tr.toFile=zUe;Tr.fileFromPath=zfe;Tr.Completions=kF;Tr.Chat=eT;Tr.ChatCompletionsPage=ER;Tr.Embeddings=$F;Tr.Files=RR;Tr.FileObjectsPage=UF;Tr.Images=VF;Tr.Audio=bO;Tr.Moderations=KF;Tr.Models=jR;Tr.ModelsPage=WF;Tr.FineTuning=T_;Tr.VectorStores=gg;Tr.VectorStoresPage=GF;Tr.VectorStoreSearchResponsesPage=JF;Tr.Beta=P_;Tr.Batches=PR;Tr.BatchesPage=MF;Tr.Uploads=kR;Tr.Responses=FR;Tr.Evals=xO;Tr.EvalListResponsesPage=zF});var J6t,G6t,Z6t,bpe=b(()=>{J6t=Symbol("Let zodToJsonSchema decide on which parser to use"),G6t={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"},Z6t=t=>typeof t=="string"?{...G6t,basePath:["#"],definitions:{},name:t}:{...G6t,basePath:["#"],definitions:{},...t}});function Y6t(t){if(!t)return!0;for(let e in t)return!1;return!0}var iJ,Xqe=b(()=>{iJ=t=>"_def"in t?t._def:t});var X6t,Qqe=b(()=>{bpe();Xqe();X6t=t=>{let e=Z6t(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])=>[iJ(o),{def:iJ(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function e2e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function bo(t,e,r,n,o){t[e]=r,e2e(t,e,n,o)}var zR=b(()=>{});function Q6t(){return{}}var t2e=b(()=>{});function e8t(t,e){let r={type:"array"};return t.type?._def?.typeName!==re.ZodAny&&(r.items=Ar(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&bo(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&bo(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(bo(r,"minItems",t.exactLength.value,t.exactLength.message,e),bo(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var r2e=b(()=>{xd();zR();Nu()});function t8t(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?bo(r,"minimum",n.value,n.message,e):bo(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),bo(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?bo(r,"maximum",n.value,n.message,e):bo(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),bo(r,"maximum",n.value,n.message,e));break;case"multipleOf":bo(r,"multipleOf",n.value,n.message,e);break}return r}var n2e=b(()=>{zR()});function r8t(){return{type:"boolean"}}var o2e=b(()=>{}
2025-08-30 08:29:39 +08:00
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
2025-09-01 12:32:47 +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 wpe(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]:Ar(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Ar(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(_pe(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 xpe=b(()=>{xd();Nu();vpe()});function d8t(t,e){if(e.mapStrategy==="record")return wpe(t,e);let r=Ar(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Ar(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 h2e=b(()=>{Nu();xpe()});function f8t(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 g2e=b(()=>{});function p8t(){return{not:{}}}var y2e=b(()=>{});function m8t(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var b2e=b(()=>{});function g8t(t,e){if(e.target==="openApi3")return h8t(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in aJ&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=aJ[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 h8t(t,e)}var aJ,h8t,Spe=b(()=>{Nu();aJ={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};h8t=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Ar(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 y8t(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:aJ[t.innerType._def.typeName],nullable:!0}:{type:[aJ[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Ar(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Ar(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var _2e=b(()=>{Nu();Spe()});function b8t(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",e2e(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?bo(r,"
This will become an error in a future version of the SDK.`),{properties:{...n.properties,[o]:s},required:i.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]})},{properties:{},required:[]}),additionalProperties:Lyn(t,e)};return r.required.length||delete r.required,r}var w2e=b(()=>{Nu()});var v8t,x2e=b(()=>{Nu();v8t=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Ar(t.innerType._def,e);let r=Ar(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}}});var w8t,S2e=b(()=>{Nu();w8t=(t,e)=>{if(e.pipeStrategy==="input")return Ar(t.in._def,e);if(e.pipeStrategy==="output")return Ar(t.out._def,e);let r=Ar(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ar(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function x8t(t,e){return Ar(t.type._def,e)}var C2e=b(()=>{Nu()});function S8t(t,e){let n={type:"array",uniqueItems:!0,items:Ar(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&bo(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&bo(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var O2e=b(()=>{zR();Nu()});function C8t(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ar(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ar(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ar(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var E2e=b(()=>{Nu()});function O8t(){return{not:{}}}var P2e=b(()=>{});function E8t(){return{}}var T2e=b(()=>{});var P8t,A2e=b(()=>{Nu();P8t=(t,e)=>Ar(t.innerType._def,e)});function Ar(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==J6t)return a}if(n&&!r){let a=Fyn(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=$yn(t,t.typeName,e,r);return i&&Byn(t,e,i),o.jsonSchema=i,i}var Fyn,kyn,$yn,Byn,Nu=b(()=>{xd();t2e();r2e();n2e();o2e();i2e();a2e();u2e();l2e();c2e();d2e();f2e();p2e();h2e();g2e();y2e();b2e();_2e();v2e();w2e();x2e();S2e();C2e();xpe();O2e();vpe();E2e();P2e();Spe();T2e();A2e();bpe();Fyn=(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:kyn(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}},kyn=(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("/")},$yn=(t,e,r,n)=>{switch(e){case re.ZodString:return _pe(t,r);case re.ZodNumber:return b8t(t,r);case re.ZodObject:return _8t(t,r);case re.ZodBigInt:return t8t(t,r);case re.ZodBoolean:return r8t();case re.ZodDate:return s2e(t,r);case re.ZodUndefined:return O8t();case re.ZodNull:return m8t(r);case re.ZodArray:return e8t(t,r);case re.ZodUnion:case re.ZodDiscriminatedUnion:return g8t(t,r);case re.ZodIntersection:return u8t(t,r);case re.ZodTuple:return C8t(t,r);case re.ZodRecord:return wpe(t,r);case re.ZodLiteral:return l8t(t,r);case re.ZodEnum:return s8t(t);case re.ZodNativeEnum:return f8t(t);case re.ZodNullable:return y8t(t,r);case re.ZodOptional:return v8t(t,r);case re.ZodMap:return d8t(t,r);case re.ZodSet:return S8t(t,r);case re.ZodLazy:return Ar(t.getter()._def,r);case re.ZodPromise:return x8t(t,r);case re.ZodNaN:case re.ZodNever:return p8t();case re.ZodEffects:return a8t(t,r,n);case re.ZodAny:return Q6t();case re.ZodUnknown:return E8t();case re.ZodDefault:return i8t(t,
2025-08-30 08:29:39 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-09-01 12:32:47 +08:00
`,t}var R8t=b(()=>{});function QF(t){let e;return t.constructor.name===fg.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Ma.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=uJ(t,"INVALID_TOOL_RESULTS"):t.status===401?e=uJ(t,"MODEL_AUTHENTICATION"):t.status===429?e=uJ(t,"MODEL_RATE_LIMIT"):t.status===404?e=uJ(t,"MODEL_NOT_FOUND"):e=t,e}function I2e(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var v3=b(()=>{ZF();Kg();ag();R8t()});function zyn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function N8t(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(j8t(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function j8t(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}: ${Epe(o,e)},`):r.push(`${n}?: ${Epe(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Epe(t,e){if(zyn(t))return t.anyOf.map(r=>Epe(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["{",j8t(t,e+2),"}"].join(`
`);case"array":return t.items?`${Epe(t.items,e)}[]`:"any[]";default:return""}}var D8t=b(()=>{});function L8t(t,e){let r;if(Wc(t)){let n=Ope({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:BM(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}var F8t=b(()=>{ag();sJ()});function Uyn(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 N2e(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(!Ys.isInstance(t))throw new Error("Invalid generic chat message");return Uyn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function R2e(t,e){return t.flatMap(r=>{let n=N2e(r);n==="system"&&j2e(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=""),Wi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(oO),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function k8t(t,e){return t.flatMap(r=>{let n=N2e(r);if(n==="system"&&j2e(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[w3];if(Wi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type==="
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},W2e=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]=Xyn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},I3=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 ed(`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 ed(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new ed("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}};I3.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);I3.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function J2e(t,e,r){if(t=await t,r??(r=l5t(t)?{lastModified:t.lastModified,type:t.type}:{}),u5t(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Ipe([o],e,r)}let n=await ebn(t);if(e||(e=rbn(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Ipe(n,e,r)}async function ebn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Dpe(t))e.push(await t.arrayBuffer());else if(nbn(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${tbn(t)}`);return e}function tbn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function rbn(t){return K2e(t.name)||K2e(t.filename)||K2e(t.path)?.split(/[\\/]/).pop()}var u5t,l5t,Dpe,Qyn,K2e,nbn,Z2e,pJ,c5t,G2e,Lpe=b(()=>{cJ();cJ();u5t=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",l5t=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Dpe(t),Dpe=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",Qyn=t=>l5t(t)||u5t(t)||q2e(t);K2e=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},nbn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Z2e=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",pJ=async t=>{let e=await c5t(t.body);return z2e(e,t)},c5t=async t=>{let e=new $2e;return await Promise.all(Object.entries(t||{}).map(([r,n])=>G2e(e,r,n))),e},G2e=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(Qyn(r)){let n=await J2e(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>G2e(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>G2e(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function g5t(t){let{response:e}=t;if(t.options.stream)return M3("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):jpe.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 M3("response",e.status,e.url,e.headers,i),i}let o=await e.text();return M3("response",e.status,e.url,e.headers,o),o}function lbn(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function hbn(t){if(!t)return!0;for(let e in t)return!1;return!0}function gbn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function h5t(t,e){for(let r in e){if(!gbn(e,r))continue;let n=r.toLowerCase();if(!n)continue;let o=e[r];o===null?delete t[n]:o!==void 0&&(t[n]=o)}}function M3(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var ibn,abn,Fpe,kpe,$pe,d5t,X2e,sbn,ubn,f5t,p5t,m5t,cbn,dbn,fbn,pbn
2025-08-30 08:29:39 +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-09-01 12:32:47 +08:00
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new WR(this),this.chat=new VR(this),this.embeddings=new KR(this),this.audio=new HR(this),this.models=new GR(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}`}}};T5t=Us;Us.Groq=T5t;Us.GroqError=ed;Us.APIError=Sc;Us.APIConnectionError=iT;Us.APIConnectionTimeoutError=rk;Us.APIUserAbortError=qR;Us.NotFoundError=O3;Us.ConflictError=E3;Us.RateLimitError=T3;Us.BadRequestError=x3;Us.AuthenticationError=S3;Us.InternalServerError=A3;Us.PermissionDeniedError=C3;Us.UnprocessableEntityError=P3;Us.toFile=J2e;Us.fileFromPath=Mpe;({GroqError:mSi,APIError:hSi,APIConnectionError:gSi,APIConnectionTimeoutError:ySi,APIUserAbortError:bSi,NotFoundError:_Si,ConflictError:vSi,RateLimitError:wSi,BadRequestError:xSi,AuthenticationError:SSi,InternalServerError:CSi,PermissionDeniedError:OSi,UnprocessableEntityError:ESi}=V2e);(function(t){t.Completions=WR,t.Chat=VR,t.Embeddings=KR,t.Audio=HR,t.Models=GR})(Us||(Us={}));A5t=Us});function Sbn(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 M5t(t){return t.map(e=>{if(typeof e.content!="string")throw new Error("Non string message content not supported");let r={role:Sbn(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 Wi(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(oO):(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 Cbn(t,e){let r=t.tool_calls;switch(t.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(Qm(i,{returnId:!0}))}catch(a){o.push(eh(i,a.message))}return new kn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:e})}default:return new Ys(t.content||"",t.role??"unknown")}}function Obn(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 Ebn(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 Cp({content:o})};if(n==="assistant"){let u=Obn(t.tool_calls,e);return{message:new Sr({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 Ef({content:o})}:{message:new Sp({content:o,role:n})}}var Bpe,R5t=b(()=>{Kg();HC();$s();Zf();no();IL();I5t();Pm();Db();K2();ag();Bpe=class extends Pu{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}),Objec
${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"}};ame.SDKError=D4e});var TJ=x(PJ=>{"use strict";Object.defineProperty(PJ,"__esModule",{value:!0});PJ.EventStream=void 0;PJ.discardSentinel=Xvn;var OJ=10,EJ=13,MWt=new Set([OJ,EJ]),Zvn=[new Uint8Array([EJ,OJ,EJ,OJ]),new Uint8Array([EJ,EJ]),new Uint8Array([OJ,OJ])],F4e=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=RWt(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=k4e(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=k4e(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{e.releaseLock()}}};PJ.EventStream=F4e;function RWt(t,e){let r=t[e],n=t[e+1];if(r==null||n==null||!MWt.has(r)||!MWt.has(n))return null;for(let o of Zvn){let i=Yvn(e,t,o);if(i!=null)return i}return null}function Yvn(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 k4e(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 Xvn(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=RWt(n,d);if(f==null)continue;let p=o,h=n.slice(p,d);o=d+f.length,k4e(h,Qvn)?.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 Qvn(t){return t}});var z4e=x(N_=>{"use strict";var ewn=N_&&N_.__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]}),twn=N_&&N_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rwn=N_&&N_.__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)&&ewn(e,t,r);return twn(e,t),e};Object.defineProperty(N_,"__esModule",{value:!0});N_.SDKValidationError=void 0;N_.formatZodError=B4e;var nwn=rwn(Ie()),$4e=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 nwn.ZodError?`${this.rawMessage}
${B4e(this.cause)}`:this.toString()}};N_.SDKValidationError=$4e;function B4e(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(`${B4e(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var Ce=x(AJ=>{"use strict";Object.defineProperty(AJ,"__esModule",{value:!0});AJ.parse=iwn;AJ.safeParse=awn;AJ.collectExtraKeys=swn;var own=Ie(),jWt=z4e(),NWt=By();function iwn(t,e,r){try{return e(t)}catch(n){throw n instanceof own.ZodError?new jWt.SDKValidationError(r,n,t):n}}function awn(t,e,r){try{return(0,NWt.OK)(e(t))}catch(n){return(0,NWt.ERR)(new jWt.SDKValidationError(r,n,t))}}function swn(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 Ci=x(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.jsonErr=cwn;nd.json=dwn;nd.textErr=fwn;nd.text=pwn;nd.bytesErr=mwn;nd.bytes=hwn;nd.streamErr=gwn;nd.stream=ywn;nd.sseErr=bwn;nd.sse=_wn;nd.nilErr=vwn;nd.nil=wwn;nd.fail=xwn;nd.match=Swn;nd.unpackHeaders=sme;nd.discardResponseBody=$Wt;var DWt=L4e(),uwn=TJ(),LWt=xJ(),FWt=P4e(),kWt=Ce(),lwn={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function cwn(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function dwn(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function fwn(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function pwn(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function mwn(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function hwn(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function gwn(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function ywn(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function bwn(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function _wn(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function vwn(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function wwn(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function xwn(t){return{enc:"fail",codes:t}}function Swn(...t){return async function(r,n){let o,i;for(let l of t){let{codes:c}=l,d="ctype"in l?l.ctype:lwn[l.enc];if(d&&(0,LWt.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,LWt.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new DWt.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,uwn.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await $Wt(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 DWt.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:sme(r.headers)}:null,...(0,FWt.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:sme(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:sme(r.headers)}:null,...(0,FWt.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,kWt.safeParse)(u,c=>i.schema.parse(c),"Respon
2025-08-30 08:29:39 +08:00
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
2025-09-01 12:32:47 +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 tge=x(ege=>{"use strict";Object.defineProperty(ege,"__esModule",{value:!0});ege.parseRecordDef=void 0;var UJ=Ie(),_Xt=Wl(),KNn=Qhe(),GNn=Vhe();function JNn(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===UJ.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,_Xt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,_Xt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,KNn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===UJ.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===UJ.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,GNn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}ege.parseRecordDef=JNn});var V3e=x(rge=>{"use strict";Object.defineProperty(rge,"__esModule",{value:!0});rge.parseMapDef=void 0;var vXt=Wl(),ZNn=tge();function YNn(t,e){if(e.mapStrategy==="record")return(0,ZNn.parseRecordDef)(t,e);let r=(0,vXt.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,vXt.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}}}rge.parseMapDef=YNn});var W3e=x(nge=>{"use strict";Object.defineProperty(nge,"__esModule",{value:!0});nge.parseNativeEnumDef=void 0;function XNn(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}}nge.parseNativeEnumDef=XNn});var K3e=x(oge=>{"use strict";Object.defineProperty(oge,"__esModule",{value:!0});oge.parseNeverDef=void 0;function QNn(){return{not:{}}}oge.parseNeverDef=QNn});var G3e=x(ige=>{"use strict";Object.defineProperty(ige,"__esModule",{value:!0});ige.parseNullDef=void 0;function ejn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}ige.parseNullDef=ejn});var age=x(f1=>{"use strict";Object.defineProperty(f1,"__esModule",{value:!0});f1.parseUnionDef=f1.primitiveMappings=void 0;var tjn=Wl();f1.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rjn(t,e){if(e.target==="openApi3")return wXt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in f1.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=f1.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-08-30 08:29:39 +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-09-01 12:32:47 +08:00
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Wi(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:zHe(i.id??"")})).map(oO)};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:zHe(o.tool_call_id)}:Wi(o)?i===void 0?{role:e(o.getType()),content:a}:{role:e(o.getType()),toolCalls:i}:{role:e(o.getType()),content:a}})}function N$n(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=UHe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=Qm(s,{returnId:!0});i.push({...u,id:u.id??qpe().replace(/-/g,"")})}catch(u){a.push(eh(s,u.message))}return new kn({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 Xs({content:o})}}function j$n(t,e){if(!t.content&&!t.toolCalls)return e?new Sr({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??qpe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=UHe(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 Cp({content:o}):n==="assistant"?new Sr({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 Vg({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new Eh({content:o,additional_kwargs:i}):new Sp({content:o,role:n})}function GQt(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:is(e.schema)}}})}function JQt(t){return typeof t?.parse=="function"}var ZQt,YQt,Gge,XQt=b(()=>{B5t();ZQt=j(VQt(),1),YQt=j(xJ(),1);$s();HC();Zf();BHe();no();Db();K2();Pm();Kg();WQt();Gge=class extends Pu{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,
2025-08-30 08:29:39 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-09-01 12:32:47 +08:00
`,t}var ner=b(()=>{});function kk(t){let e;return t.constructor.name===fg.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Ma.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=QJ(t,"INVALID_TOOL_RESULTS"):t.status===401?e=QJ(t,"MODEL_AUTHENTICATION"):t.status===429?e=QJ(t,"MODEL_RATE_LIMIT"):t.status===404?e=QJ(t,"MODEL_NOT_FOUND"):e=t,e}function qHe(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var iH=b(()=>{ZF();Kg();ag();ner()});function D$n(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function oer(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(ier(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function ier(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}: ${Jge(o,e)},`):r.push(`${n}?: ${Jge(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Jge(t,e){if(D$n(t))return t.anyOf.map(r=>Jge(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["{",ier(t,e+2),"}"].join(`
`);case"array":return t.items?`${Jge(t.items,e)}[]`:"any[]";default:return""}}var aer=b(()=>{});function ser(t,e){let r;if(Wc(t)){let n=Ope({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:BM(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}var uer=b(()=>{ag();sJ()});function L$n(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 WHe(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(!Ys.isInstance(t))throw new Error("Invalid generic chat message");return L$n(t)}default:throw new Error(`Unknown message type: ${e}`)}}function VHe(t,e){return t.flatMap(r=>{let n=WHe(r);n==="system"&&KHe(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=""),Wi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(oO),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function ler(t,e){return t.flatMap(r=>{let n=WHe(r);if(n==="system"&&KHe(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[aH];if(Wi(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==="
without CORS Error: `+eo(n)+`
with CORS Error: `+eo(o);throw new Error(i)}}}findModelByName(e){return oe().activeModels.find(n=>n.name===e)}};sd.REASONING_MODEL_TEMPERATURE=1;h1=sd});var tye={};os(tye,{TieredLexicalRetriever:()=>t7});async function z$n(){try{if(!YHe){let e=await Promise.resolve().then(()=>(eye(),Cer));YHe=()=>e.default.getInstance()}return YHe().getChatModel()}catch{return null}}var XHe,YHe,t7,r7=b(()=>{Gt();bt();ir();tG();wze();XHe=require("obsidian");Bde();BHt();YHe=null;t7=class extends y4{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.searchCore=new sfe(r,z$n),typeof this.searchCore.getChunkManager=="function"?this.chunkManager=this.searchCore.getChunkManager():this.chunkManager=new hR(r)}async getRelevantDocuments(r,n){try{if(this.options.timeRange)return this.getTimeRangeDocuments(r);let o=Jg(r,this.app.vault),i=o.map(f=>f.basename),a=[...new Set([...this.options.salientTerms,...i])];oe().debug&&B("TieredLexicalRetriever: Starting search",{query:r,salientTerms:a,maxK:this.options.maxK});let s=oe(),u=await this.searchCore.retrieve(r,{maxResults:this.options.maxK,salientTerms:a,enableLexicalBoosts:s.enableLexicalBoosts}),l=await this.getTitleMatches(o),c=await this.convertToDocuments(u),d=this.combineResults(c,l);return oe().debug&&B("TieredLexicalRetriever: Search complete",{totalResults:d.length,titleMatches:l.length,searchResults:u.length}),d}catch(o){return Bt("TieredLexicalRetriever: Error during search",o),[]}}async getTimeRangeDocuments(r){if(!this.options.timeRange)return[];let{startTime:n,endTime:o}=this.options.timeRange,i=this.generateDailyNoteDateRange(n,o);oe().debug&&B("TieredLexicalRetriever: Generated daily note titles",{startTime:new Date(n).toISOString(),endTime:new Date(o).toISOString(),titlesCount:i.length,firstTitle:i[0],lastTitle:i[i.length-1]});let a=i.join(", "),s=Jg(a,this.app.vault),l=(await this.getTitleMatches(s)).map(m=>(m.metadata.includeInContext=!0,m)),c=this.app.vault.getMarkdownFiles(),d=[],f=Math.min(this.options.maxK,100);for(let m of c)if(m.stat.mtime>=n&&m.stat.mtime<=o){if(s.some(g=>g.path===m.path))continue;if(d.length>=f)break;try{let g=await this.app.vault.cachedRead(m),y=this.app.metadataCache.getFileCache(m),_=(Date.now()-m.stat.mtime)/(1e3*60*60*24),w=Math.max(.3,Math.min(1,1-_/30));d.push(new nh({pageContent:g,metadata:{path:m.path,title:m.basename,mtime:m.stat.mtime,ctime:m.stat.ctime,tags:y?.tags?.map(S=>S.tag)||[],includeInContext:!0,score:w,rerank_score:w,source:"time-filtered"}}))}catch(g){Bt(`TieredLexicalRetriever: Failed to read file ${m.path}`,g)}}let p=new Map;for(let m of l)p.set(m.metadata.path,m);for(let m of d)p.has(m.metadata.path)||p.set(m.metadata.path,{...m,metadata:{...m.metadata,includeInContext:!0}});let h=Array.from(p.values()).sort((m,g)=>{let y=m.metadata.score||0;return(g.metadata.score||0)-y});return oe().debug&&B("TieredLexicalRetriever: Time range search complete",{timeRange:this.options.timeRange,dailyNotesFound:s.length,timeFilteredDocs:d.length,totalResults:h.length}),h}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=365;Math.ceil((n-r)/(1e3*60*60*24))>s&&(Bt(`TieredLexicalRetriever: Date range exceeds ${s} days, limiting to recent ${s} days`),i.setTime(a.getTime()-s*24*60*60*1e3));let l=new Date(i);for(;l<=a;)o.push(`[[${l.toLocaleDateString("en-CA")}]]`),l.setDate(l.getDate()+1);return o}async getTitleMatches(r){let n=[];for(let o of r)try{let i=await this.app.vault.cachedRead(o),a=this.app.metadataCache.getFileCache(o);n.push(new nh({pageContent:i,metadata:{path:o.path,title:o.basename,mtime:o.stat.mtime,ctime:o.stat.ctime,tags:a?.tags?.map(s=>s.tag)||[],includeInContext:!0,score:1,rerank_score:1,source:"title-match"}}))}catch(i){Bt(`TieredLexicalRetriever: Failed to read title-matched file ${o.path}`,i)}return n}async convertToDocuments(r){let n=[];for(let o of r)try{if(o.id.includes("#")){let[a]=o.id.split("#"),s=this.app.vault.getAbstractFileByPath(a);if(!s||!(s instanceof XHe.TFile))continue;let u="",l=this.chunkManager;if(typeof l.getChunkText=="function"?u=await l.ge
2025-08-30 08:29:39 +08:00
${E.pageContent}
2025-09-01 12:32:47 +08:00
</${rCe}>`).join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`),g=[],y=Mf(),_=`
2025-08-30 08:29:39 +08:00
Answer the question with as detailed as possible based only on the following context:
2025-09-01 12:32:47 +08:00
`+m,w=y+_,S=this.chainManager.chatModelManager.getChatModel();w&&g.push({role:eI(S),content:w});for(let E of c)g.push({role:E.role,content:E.content});if(e.content&&Array.isArray(e.content)){let E=e.content.map(P=>P.type==="text"?{...P,text:e.message}:P);g.push({role:"user",content:E})}else g.push({role:"user",content:e.message});B(`==== Final Request to AI ====
`,g);let C=await Od(()=>this.chainManager.chatModelManager.getChatModel().stream(g,{signal:r.signal}));for await(let E of C){if(r.signal.aborted){B("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(E)}}catch(u){u.name==="AbortError"||r.signal.aborted?B("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=Net(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
2025-08-30 08:29:39 +08:00
`);e+=`
#### Sources:
2025-09-01 12:32:47 +08:00
`+n}return e}}});async function rye(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-09-01 12:32:47 +08:00
`);return await Od(async()=>{let i=await Vd.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);return Aj(i.content)})}var QHe=b(()=>{mR();ir()});function k_(){}function Eer(t,e,r,n,o){for(var i=[],a;e;)i.push(e),a=e.previousComponent,delete e.previousComponent,e=a;i.reverse();for(var s=0,u=i.length,l=0,c=0;s<u;s++){var d=i[s];if(d.removed)d.value=t.join(n.slice(c,c+d.count)),c+=d.count;else{if(!d.added&&o){var f=r.slice(l,l+d.count);f=f.map(function(p,h){var m=n[c+h];return m.length>p.length?m:p}),d.value=t.join(f)}else d.value=t.join(r.slice(l,l+d.count));l+=d.count,d.added||(c+=d.count)}}return i}function Per(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function Ter(t,e){var r;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])return t.slice(-r);return t.slice(-r)}function eVe(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function tVe(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function o7(t,e){return eVe(t,e,"")}function nye(t,e){return tVe(t,e,"")}function Aer(t,e){return e.slice(0,U$n(t,e))}function U$n(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var o=Array(n),i=0;o[0]=0;for(var a=1;a<n;a++){for(e[a]==e[i]?o[a]=o[i]:o[a]=i;i>0&&e[a]!=e[i];)i=o[i];e[a]==e[i]&&i++}i=0;for(var s=r;s<t.length;s++){for(;i>0&&t[s]!=e[i];)i=o[i];t[s]==e[i]&&i++}return i}function Mer(t,e,r){return r?.ignoreWhitespace!=null&&!r.ignoreWhitespace?H$n(t,e,r):a7.diff(t,e,r)}function Ier(t,e,r,n){if(e&&r){var o=e.value.match(/^\s*/)[0],i=e.value.match(/\s*$/)[0],a=r.value.match(/^\s*/)[0],s=r.value.match(/\s*$/)[0];if(t){var u=Per(o,a);t.value=tVe(t.value,a,u),e.value=o7(e.value,u),r.value=o7(r.value,u)}if(n){var l=Ter(i,s);n.value=eVe(n.value,s,l),e.value=nye(e.value,l),r.value=nye(r.value,l)}}else if(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(t&&n){var c=n.value.match(/^\s*/)[0],d=e.value.match(/^\s*/)[0],f=e.value.match(/\s*$/)[0],p=Per(c,d);e.value=o7(e.value,p);var h=Ter(o7(c,p),f);e.value=nye(e.value,h),n.value=eVe(n.value,c,h),t.value=tVe(t.value,c,c.slice(0,c.length-h.length))}else if(n){var m=n.value.match(/^\s*/)[0],g=e.value.match(/\s*$/)[0],y=Aer(g,m);e.value=nye(e.value,y)}else if(t){var _=t.value.match(/\s*$/)[0],w=e.value.match(/^\s*/)[0],S=Aer(_,w);e.value=o7(e.value,S)}}function H$n(t,e,r){return Rer.diff(t,e,r)}function V$n(t,e){if(typeof t=="function")e.callback=t;else if(t)for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function Ner(t,e,r){var n=V$n(r,{ignoreWhitespace:!0});return iye.diff(t,e,n)}function rVe(t){"@babel/helpers - typeof";return rVe=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},rVe(t)}function nVe(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]=nVe(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),rVe(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]=nVe(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var oMi,oye,q$n,a7,Rer,iye,W$n,K$n,i7,oVe,iVe=b(()=>{k_.prototype={diff:function(e,r){var n,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});v
`));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};iye.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
2025-08-30 08:29:39 +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-09-01 12:32:47 +08:00
`)&&(e=e.slice(0,-1))),k_.prototype.equals.call(this,t,e,r)};W$n=new k_;W$n.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};K$n=new k_;K$n.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};i7=new k_;i7.useLongestToken=!0;i7.tokenize=iye.tokenize;i7.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(nVe(t,null,null,o),o," ")};i7.equals=function(t,e,r){return k_.prototype.equals.call(i7,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};oVe=new k_;oVe.tokenize=function(t){return t.slice()};oVe.join=oVe.removeEmpty=function(t){return t}});function jer(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 Der=b(()=>{});var KT,Br,Ler,Fer,s7,aye,ker,G$n,aVe=b(()=>{xn();Gt();iVe();un();KT=require("obsidian"),Br=j(Y()),Ler=j($c());po();Fer=j(Y());Der();s7="obsidian-copilot-apply-view",aye=class extends KT.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return s7}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),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,Ler.createRoot)(n)),this.root.render(Br.default.createElement(G$n,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},ker=(0,Br.memo)(({oldLine:t,newLine:e})=>{let r=Mer(t,e);return Br.default.createElement(Br.default.Fragment,null,r.map((n,o)=>n.added?Br.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?Br.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):Br.default.createElement("span",{key:o},n.value)))});ker.displayName="WordDiff";G$n=({app:t,state:e,close:r})=>{let[n,o]=(0,Fer.useState)(()=>e.changes.map(h=>({...h,accepted:null}))),i=jer(n),a=(0,Br.useRef)([]);if(!e||!e.changes)return ie("Invalid state:",e),Br.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Br.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Br.default.createElement(he,{onClick:()=>r("failed"),className:"tw-mt-4"},"Close"));let s=async()=>{try{let h=n.map(g=>g.accepted===null?{...g,accepted:!0}:g),m=await c(h);r(m?"accepted":"failed")}catch(h){ie("Error applying changes:",h),new KT.Notice(`Error applying changes: ${h.message}`),r("failed")}},u=async()=>{try{let h=n.map(g=>g.accepted===null?{...g,accepted:!1}:g),m=await c(h);r(m?"rejected":"failed")}catch(h){ie("Error applying changes:",h),new KT.Notice(`Error applying changes: ${h.message}`),r("failed")}},l=async h=>{let m=t.vault.getAbstractFileByPath(h);if(m)return m;if(h.includes("/")){let g=h.split("/").slice(0,-1).join("/");t.vault.getAbstractFileByPath(g)||await t.vault.createFolder(g)}return await t.vault.create(h,"")},c=async h=>{let m=h.filter(y=>y.added?y.accepted===!0:y.removed?y.accepted===!1:!0).map(y=>y.value).join(""),g=await l(e.path);return!g||!(g instanceof KT.TFile)?(ie("Error in getting file",e.path),new KT.Notice("Failed to create file"),!1):(await t.vault.modify(g,m),new KT.Notice("Changes applied successfully"),!0)},d=h=>{if(!i)return;let m=-1;for(let g=h+1;g<i.length;g++){let y=i[g],_=y.some(S=>S.added||S.removed),w=y.some(S=>(S.added||S.removed)&&S.accepted===null);if(_&&w){m=g;break}}m!==-1&&a.current[m]&&a.current[m]?.scrollIntoView({behavior:"smooth",block:"center"})},f=h=>{o(m=>{let g=[...m],y=i?.[h];return y&&y.forEach(_=>{let w=g.findIndex(S=>S===_);w!==-1&&(g[w]={...g[w],accepted:!0})}),g}),setTimeout(()=>d(h),0)},p=h=>{o(m=>{let g=[...m],y=i?.[h];return y&&y.forEach(_=>{let w=g.findIndex(S=>S===_);w!==-1&&(g[w]={...g[w],accepted:!1})}),g}),setTimeout(()=>d(h),0)};return Br.defa
2025-08-30 08:29:39 +08:00
`).replace(/\r/g,`
2025-09-01 12:32:47 +08:00
`)}function Y$n(t,e,r){let n=(t.match(/\r\n/g)||[]).length,o=(t.match(/(?<!\r)\n/g)||[]).length,i=n>o,a=u7(t),s=u7(e),u=u7(r),l=a.replaceAll(s,u);return i?l.replace(/\n/g,`\r
`):l}function X$n(t){let e=[],r=/-{3,}\s*SEARCH\s*(?:\r?\n)?/,n=/(?:\r?\n)?={3,}\s*(?:\r?\n)?/,o=/(?:\r?\n)?\+{3,}\s*REPLACE/,i=new RegExp(r.source+"([\\s\\S]*?)"+n.source+"([\\s\\S]*?)"+o.source,"g"),a;for(;(a=i.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();e.push({searchText:s,replaceText:u})}return e}var Bk,J$n,sye,Z$n,Uer,sVe=b(()=>{Bk=require("obsidian");aVe();iVe();xd();$k();J$n=dt.object({path:dt.string().describe(`(Required) The path to the file to write to.
2025-08-30 08:29:39 +08:00
The path must end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
2025-09-01 12:32:47 +08:00
The path must be relative to the root of the vault.`),content:dt.union([dt.string(),dt.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
2025-08-30 08:29:39 +08:00
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
2025-09-01 12:32:47 +08:00
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
2025-08-30 08:29:39 +08:00
# Rules for Obsidian Canvas content
* For canvas files, both 'nodes' and 'edges' arrays must be properly closed with ]
* Every node must have: id, type, x, y, width, height
* Every edge must have: id, fromNode, toNode
* All IDs must be unique
* Edge fromNode and toNode must reference existing node IDs
2025-09-01 12:32:47 +08:00
# Example content of a canvas file (as object)
2025-08-30 08:29:39 +08:00
{
"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"
}
]
2025-09-01 12:32:47 +08:00
}`)}),sye=Kl({name:"writeToFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
2025-08-30 08:29:39 +08:00
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
2025-09-01 12:32:47 +08:00
`,schema:J$n,handler:async({path:t,content:e})=>{let r=typeof e=="string"?e:JSON.stringify(e,null,2),n=await zer(t,r);return JSON.stringify({result:n,message:`File change result: ${n}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`})},timeoutMs:0}),Z$n=dt.object({path:dt.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),diff:dt.string().describe(`(Required) One or more SEARCH/REPLACE blocks. Each block MUST follow this exact format with these exact markers:
2025-08-30 08:29:39 +08:00
------- SEARCH
[exact content to find, including all whitespace and indentation]
=======
[new content to replace with]
+++++++ REPLACE
WHEN TO USE THIS TOOL vs writeToFile:
- Use replaceInFile for: small edits, fixing typos, updating specific sections, targeted changes
- Use writeToFile for: creating new files, major rewrites, when you can't identify specific text to replace
CRITICAL RULES:
1. SEARCH content must match EXACTLY - every character, space, and line break
2. Use the exact markers: "------- SEARCH", "=======", "+++++++ REPLACE"
3. For multiple changes, include multiple SEARCH/REPLACE blocks in order
4. Keep blocks concise - include only the lines being changed plus minimal context
COMMON MISTAKES TO AVOID:
- Wrong: Using different markers like "---- SEARCH" or "SEARCH -------"
- Wrong: Including too many unchanged lines
2025-09-01 12:32:47 +08:00
- Wrong: Not matching whitespace/indentation exactly`)});Uer=Kl({name:"replaceInFile",description:"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a LARGE file.",schema:Z$n,handler:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof Bk.TFile))return`File not found at path: ${t}. Please check the file path and try again.`;try{let n=await app.vault.read(r),o=n;if(n.length<3e3)return"File is too small to use this tool. Please use writeToFile instead.";let a=X$n(e);if(a.length===0)return`No valid SEARCH/REPLACE blocks found in diff. Please use the correct format with ------- SEARCH, =======, and +++++++ REPLACE markers.
diff: ${e}`;let s=0;for(let l of a){let{searchText:c,replaceText:d}=l,f=u7(o),p=u7(c);if(!f.includes(p))if(f.includes(p.trimEnd()))c=c.trimEnd(),d=d.trimEnd();else return`Search text not found in file ${t} : "${c}".`;let h=o;o=Y$n(o,c,d),o!==h&&s++}if(n===o)return`No changes made to ${t}. The search text was not found or replacement resulted in identical content. Call writeToFile instead`;let u=await zer(t,o);return JSON.stringify({result:u,blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) (replacing all occurrences). Result: ${u}. Do not call this tool again to modify this file in response to the current user request.`})}catch(n){return`Error performing SEARCH/REPLACE on ${t}: ${n}. Please check the file path and diff format and try again.`}},timeoutMs:0})});var uVe,qer,DO,l7=b(()=>{uVe=require("obsidian"),qer=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""}},DO=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 uVe.Notice(n.message):new uVe.Notice("An error occurred while executing the tool. Check console for details."),null}}}});function Q$n(t){return"children"in t&&"path"in t}function eBn(t){return"path"in t&&!("children"in t)}function tBn(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function lVe(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=vc();for(let u of t.children)if(eBn(u)){if(_s(u,i,a)){e&&r.push(u.name);let l=tBn(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(Q$n(u)){let l=lVe(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 uye,cVe=b(()=>{rh();xd();$k();uye=t=>Kl({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:dt.void(),handler:async()=>{let e=lVe(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-09-01 12:32:47 +08:00
`,n=JSON.stringify(e);if(n.length>5e5){let o=lVe(t,!1);return r+JSON.stringify(o)}return r+n},isBackground:!0})});var dVe,rBn,nBn,c7,Her,oBn,d7,fVe=b(()=>{QHe();or();My();Gt();bt();xd();$k();dVe=dt.object({query:dt.string().min(1).describe("The search query"),salientTerms:dt.array(dt.string()).describe("List of salient terms extracted from the query"),timeRange:dt.object({startTime:dt.any(),endTime:dt.any()}).optional().describe("Time range for search")}),rBn=Kl({name:"lexicalSearch",description:"Search for notes using lexical/keyword-based search",schema:dVe,handler:async({timeRange:t,query:e,salientTerms:r})=>{let n=oe(),o=t!==void 0,i=o?Math.max(n.maxSourceChunks,200):n.maxSourceChunks;B(`lexicalSearch returnAll: ${o}`);let s=await new(await Promise.resolve().then(()=>(r7(),tye))).TieredLexicalRetriever(app,{minSimilarityScore:o?0:.1,maxK:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:nCe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e);B(`lexicalSearch found ${s.length} documents for query: "${e}"`),t&&B(`Time range search from ${new Date(t.startTime.epoch).toISOString()} to ${new Date(t.endTime.epoch).toISOString()}`);let u=s.map(l=>{let c=l.metadata.rerank_score??l.metadata.score??0;return{title:l.metadata.title||"Untitled",content:l.pageContent,path:l.metadata.path||"",score:c,rerank_score:c,includeInContext:l.metadata.includeInContext??!0,source:l.metadata.source,mtime:l.metadata.mtime??null,explanation:l.metadata.explanation??null}});return JSON.stringify(u)}}),nBn=Kl({name:"semanticSearch",description:"Search for notes using semantic/meaning-based search with embeddings",schema:dVe,handler:async({timeRange:t,query:e,salientTerms:r})=>{let n=oe(),o=t!==void 0,i=o?Math.max(n.maxSourceChunks,200):n.maxSourceChunks;B(`semanticSearch returnAll: ${o}`);let s=await new(await Promise.resolve().then(()=>(cG(),$de))).HybridRetriever({minSimilarityScore:o?0:.1,maxK:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:nCe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e);B(`semanticSearch found ${s.length} documents for query: "${e}"`),t&&B(`Time range search from ${new Date(t.startTime.epoch).toISOString()} to ${new Date(t.endTime.epoch).toISOString()}`);let u=s.map(l=>{let c=l.metadata.rerank_score??l.metadata.score??0;return{title:l.metadata.title||"Untitled",content:l.pageContent,path:l.metadata.path||"",score:c,rerank_score:c,includeInContext:l.metadata.includeInContext??!0,source:l.metadata.source,mtime:l.metadata.mtime??null,explanation:l.metadata.explanation??null}});return JSON.stringify(u)}}),c7=Kl({name:"localSearch",description:"Search for notes based on the time range and query",schema:dVe,handler:async({timeRange:t,query:e,salientTerms:r})=>{let n=oe();return B(`localSearch delegating to ${n.enableSemanticSearchV3?"semantic":"lexical"} search`),n.enableSemanticSearchV3?await nBn.call({timeRange:t,query:e,salientTerms:r}):await rBn.call({timeRange:t,query:e,salientTerms:r})}}),Her=Kl({name:"indexVault",description:"Index the vault to the Copilot index",schema:dt.void(),handler:async()=>{if(oe().enableSemanticSearchV3)try{let r=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore();return`Semantic search index refreshed with ${r} documents.
2025-08-30 08:29:39 +08:00
`+JSON.stringify({success:!0,message:`Semantic search index has been refreshed with ${r} documents.`,documentCount:r})}catch(e){return JSON.stringify({success:!1,message:`Failed to index with semantic search: ${e.message}`})}else return`The tiered lexical retriever builds indexes on demand and doesn't require manual indexing.
2025-09-01 12:32:47 +08:00
`+JSON.stringify({success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."})},isBackground:!0}),oBn=dt.object({query:dt.string().min(1).describe("The search query"),chatHistory:dt.array(dt.object({role:dt.enum(["user","assistant"]),content:dt.string()})).describe("Previous conversation turns")}),d7=Kl({name:"webSearch",description:"Search the web for information",schema:oBn,isPlusOnly:!0,handler:async({query:t,chatHistory:e})=>{try{let r=await rye(t,e),n=await Ji.getInstance().webSearch(r),o=n.response.citations||[],a=[{type:"web_search",content:n.response.choices[0].message.content,citations:o,instruction:"Provide a response based on this information. Include source citations at the end under '#### Sources' as markdown links."}];return JSON.stringify(a)}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}}})});var Ver=x((pVe,mVe)=>{(function(t,e){typeof pVe=="object"&&typeof mVe<"u"?mVe.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(pVe,function(){"use strict";var t="month",e="quarter";return function(r,n){var o=n.prototype;o.quarter=function(s){return this.$utils().u(s)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(s-1))};var i=o.add;o.add=function(s,u){return s=Number(s),this.$utils().p(u)===e?this.add(3*s,t):i.bind(this)(s,u)};var a=o.startOf;o.startOf=function(s,u){var l=this.$utils(),c=!!l.u(u)||u;if(l.p(s)===e){var d=this.quarter()-1;return c?this.month(3*d).startOf(t).startOf("day"):this.month(3*d+2).endOf(t).endOf("day")}return a.bind(this)(s,u)}}})});var g1=x((hVe,gVe)=>{(function(t,e){typeof hVe=="object"&&typeof gVe<"u"?gVe.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(hVe,function(){"use strict";var t=1e3,e=6e4,r=36e5,n="millisecond",o="second",i="minute",a="hour",s="day",u="week",l="month",c="quarter",d="year",f="date",p="Invalid Date",h=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,m=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(D){var k=["th","st","nd","rd"],F=D%100;return"["+D+(k[(F-20)%10]||k[F]||k[0])+"]"}},y=function(D,k,F){var K=String(D);return!K||K.length>=k?D:""+Array(k+1-K.length).join(F)+D},_={s:y,z:function(D){var k=-D.utcOffset(),F=Math.abs(k),K=Math.floor(F/60),U=F%60;return(k<=0?"+":"-")+y(K,2,"0")+":"+y(U,2,"0")},m:function D(k,F){if(k.date()<F.date())return-D(F,k);var K=12*(F.year()-k.year())+(F.month()-k.month()),U=k.clone().add(K,l),X=F-U<0,ee=k.clone().add(K+(X?-1:1),l);return+(-(K+(F-U)/(X?U-ee:ee-U))||0)},a:function(D){return D<0?Math.ceil(D)||0:Math.floor(D)},p:function(D){return{M:l,y:d,w:u,d:s,D:f,h:a,m:i,s:o,ms:n,Q:c}[D]||String(D||"").toLowerCase().replace(/s$/,"")},u:function(D){return D===void 0}},w="en",S={};S[w]=g;var C="$isDayjsObject",E=function(D){return D instanceof N||!(!D||!D[C])},P=function D(k,F,K){var U;if(!k)return w;if(typeof k=="string"){var X=k.toLowerCase();S[X]&&(U=X),F&&(S[X]=F,U=X);var ee=k.split("-");if(!U&&ee.length>1)return D(ee[0])}else{var L=k.name;S[L]=k,U=L}return!K&&U&&(w=U),U||!K&&w},T=function(D,k){if(E(D))return D.clone();var F=typeof k=="object"?k:{};return F.date=D,F.args=arguments,new N(F)},I=_;I.l=P,I.i=E,I.w=function(D,k){return T(D,{locale:k.$L,utc:k.$u,x:k.$x,$offset:k.$offset})};var N=function(){function D(F){this.$L=P(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[C]=!0}var k=D.prototype;return k.parse=function(F){this.$d=function(K){var U=K.date,X=K.utc;if(U===null)return new Date(NaN);if(I.u(U))return new Date;if(U instanceof Date)return new Date(U);if(typeof U=="string"&&!/Z$/i.test(U)){var ee=U.match(h);if(ee){var L=ee[2]-1||0,Q=(ee[7]||"0").substring(0,3);return X?new Date(Date.UTC(e
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-09-01 12:32:47 +08:00
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,f7.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,f7.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?(lye(o,n),$_(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(sH(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}},GT=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 Do(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 _Ve(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function aBn(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function tf(t){return`(?:${aBn(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var v1=b(()=>{});function dye(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function w1(t,e,r){let n=(0,Jer.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 Jer,lH=b(()=>{Jer=j(g1(),1)});function sBn(t){let e=t.toLowerCase();return vVe[e]!==void 0?vVe[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}function dH(t){let e=t.toLowerCase();return wVe[e]!==void 0?wVe[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function S1(t){if(/BE/i.test(t))return t=t.replace(/BE/i,""),parseInt(t)-543;if(/BCE?/i.test(t))return t=t.replace(/BCE?/i,""),-parseInt(t);if(/(AD|CE)/i.test(t))return t=t.replace(/(AD|CE)/i,""),parseInt(t);let e=parseInt(t);return dye(e)}function rb(t){let e={},r=t,n=Zer.exec(r);for(;n;)lBn(e,n),r=r.substring(n[0].length).trim(),n=Zer.exec(r);return Object.keys(e).length==0?null:e}function lBn(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let r=sBn(e[1]),n=p7[e[2].toLowerCase()];t[n]=r}var xVe,SVe,tb,vVe,wVe,Yer,p7,Xer,cH,x1,Qer,Zer,uBn,etr,JT,C1,Oc=b(()=>{v1();lH();xVe={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},SVe={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},tb={...SVe,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},vVe={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
2025-09-01 12:32:47 +08:00
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),handler:async({timezoneOffset:t})=>BUn(t),isBackground:!0}),Dnr={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};Bye=Kl({name:"getTimeRangeMs",description:"Convert natural language time expressions to date ranges for use with localSearch",schema:dt.object({timeExpression:dt.string().describe(`Natural language time expression to convert to a date range.
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
2025-09-01 12:32:47 +08:00
3. Then use the returned time range with localSearch`)}),handler:async({timeExpression:t})=>GUn(t),isBackground:!0});zye=Kl({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:dt.object({epoch:dt.number().describe("Unix timestamp in seconds or milliseconds")}),handler:async({epoch:t})=>JUn(t),isBackground:!0});CZ=Kl({name:"startPomodoro",description:"Start a Pomodoro timer with a customizable interval",schema:dt.object({interval:dt.string().default("25min").describe("Time interval (e.g., '25min', '5s', '1h'). Default is 25min.")}),handler:async({interval:t})=>(YUn(t),`Pomodoro timer started. It will end in ${t}.`)});Uye=Kl({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:dt.object({time:dt.string().describe(`Time to convert. Supports various formats:
2025-08-30 08:29:39 +08:00
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
2025-09-01 12:32:47 +08:00
- Relative: "noon", "midnight"`),fromOffset:dt.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:dt.string().describe(`Target UTC offset. Must be numeric, not timezone name.
2025-08-30 08:29:39 +08:00
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
2025-09-01 12:32:47 +08:00
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),handler:async({time:t,fromOffset:e,toOffset:r})=>XUn(t,e,r),isBackground:!0})});var Lnr,Fnr,qye,E6e=b(()=>{My();ir();xd();$k();Lnr=5e4,Fnr=Kl({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:dt.object({}),isPlusOnly:!0,requiresUserMessageContent:!0,handler:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return JSON.stringify({success:!1,message:"Invalid input: User message must be a string"});if(e.length>Lnr)return JSON.stringify({success:!1,message:`Input too long: Maximum allowed length is ${Lnr} characters`});let r=_ee(e);if(r.length===0)return JSON.stringify({success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."});let n=await Promise.all(r.map(async i=>{try{let a=await Ji.getInstance().youtube4llm(i);return a.response.transcript?{url:i,success:!0,transcript:a.response.transcript,elapsed_time_ms:a.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(a){return console.error(`Error transcribing YouTube video ${i}:`,a),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}})),o=n.some(i=>i.success);return JSON.stringify({success:o,results:n,total_urls:r.length})}}),qye=Kl({name:"simpleYoutubeTranscription",description:"Get the transcript of a YouTube video",schema:dt.object({url:dt.string().url().describe("The YouTube video URL")}),isPlusOnly:!0,handler:async({url:t})=>{try{let e=await Ji.getInstance().youtube4llm(t);return e.response.transcript?JSON.stringify({success:!0,transcript:e.response.transcript,elapsed_time_ms:e.elapsed_time_ms}):JSON.stringify({success:!1,message:"Transcript not available. Only English videos with the auto transcript option turned on are supported at the moment"})}catch(e){return console.error(`Error transcribing YouTube video ${t}:`,e),JSON.stringify({success:!1,message:"An error occurred while transcribing the YouTube video."})}}})});var OZ,Zk,Hye=b(()=>{mR();ua();cVe();fVe();O6e();E6e();l7();ir();My();OZ=["@vault","@composer","@websearch","@youtube","@pomodoro"],Zk=class{static initTools(e){this.tools.length===0&&(this.tools=[$ye,Uye,zye,Bye,c7,Her,CZ,d7,qye,uye(e.getRoot())])}static async analyzeIntent(e){try{let r=await Ji.getInstance().broca(e,Fj());if(!r?.response)throw new Error(r?.detail||"Broca API call failed");let n=r.response.tool_calls,o=r.response.salience_terms,i=[],a;for(let s of n){let u=this.tools.find(l=>l.name===s.tool);if(u){let l=s.args||{};if(u.name==="getTimeRangeMs"&&(a=await DO.callTool(u,l)),u.name=="getFileTree"&&Fj())continue;i.push({tool:u,args:l})}}return await this.processAtCommands(e,i,{timeRange:a,salientTerms:o}),i}catch(r){throw console.error("Error in intent analysis:",r),r}}static async processAtCommands(e,r,n){let o=e.toLowerCase(),{timeRange:i,salientTerms:a}=n;if(o.includes("@vault")){let u=this.removeAtCommands(e);r.push({tool:c7,args:{timeRange:i||void 0,query:u,salientTerms:a}})}if(o.includes("@websearch")||o.includes("@web")){let u=this.removeAtCommands(e),c=await Vd.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=QB(c);r.push({tool:d7,args:{query:u,chatHistory:d}})}if(o.includes("@pomodoro")){let u=e.match(/@pomodoro\s+(\S+)/i),l=u?u[1]:"25min";r.push({tool:CZ,args:{interval:l}})}let s=_ee(e);for(let u of s)r.some(c=>c.tool.name===qye.name&&c.args.url===u)||r.push({tool:qye,args:{url:u}})}static removeAtCommands(e){return e.split(" ").filter(r=>!OZ.includes(r.toLowerCase())).join(" ").trim()}};Zk.tools=[]});var jH,P6e=b(()=>{jH=class{static tryParseJson(e){try{let r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch{return[]}}static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}let o;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":return this.formatLocalSearch(o);case"web
2025-08-30 08:29:39 +08:00
No matching notes found.`;let d=[],f=/<document>\s*<title>([^<]*)<\/title>(?:\s*<path>([^<]*)<\/path>)?(?:\s*<modified>([^<]*)<\/modified>)?[\s\S]*?<\/document>/g,p;for(;(p=f.exec(u))!==null;)d.push({title:p[1]||"Untitled",path:p[2]||"",mtime:p[3]||null});let m=d.slice(0,10).map((y,_)=>{let w=[`${_+1}. ${y.title}`];return y.mtime&&w.push(` \u{1F552} Modified: ${y.mtime}`),y.path&&y.path!==y.title&&w.push(` \u{1F4C1} ${y.path}`),w.join(`
`)}).join(`
`),g=c>10?`
... and ${c-10} more results`:"";return`\u{1F4DA} Found ${c} relevant notes
Top results:
${m}${g}`}}let r=this.parseSearchResults(e);if(!Array.isArray(r))return typeof e=="string"?e:JSON.stringify(e,null,2);let n=r.length;if(n===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let i=r.slice(0,10).map((s,u)=>this.formatSearchItem(s,u)).join(`
`),a=n>10?`
... and ${n-10} more results`:"";return`\u{1F4DA} Found ${n} relevant notes
Top results:
${i}${a}`}static parseSearchResults(e){if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null)return[e];if(typeof e=="string"){let r=e.trim();return!r.startsWith("[")&&!r.startsWith("{")?[]:this.tryParseJson(e)}return[]}static formatSearchItem(e,r){let n=e.path?.split("/").pop()?.replace(/\.md$/,"")||e.title||"Untitled",o=e.rerank_score||e.score||0,i=typeof o=="number"?o.toFixed(4):o,a=e.source==="time-filtered"?"Recency":"Relevance",s=[`${r+1}. ${n}`];if(e.source==="time-filtered"){if(e.mtime)try{let l=new Date(e.mtime),c=isNaN(l.getTime())?String(e.mtime):l.toISOString();s.push(` \u{1F552} Modified: ${c}${e.includeInContext?" \u2713":""}`)}catch{s.push(` \u{1F552} Modified: ${String(e.mtime)}${e.includeInContext?" \u2713":""}`)}}else e.source==="title-match"?s.push(` \u{1F516} Title match${e.includeInContext?" \u2713":""}`):s.push(` \u{1F4CA} ${a}: ${i}${e.includeInContext?" \u2713":""}`);let u=this.extractContentSnippet(e.content);return u&&s.push(` \u{1F4AC} "${u}${e.content?.length>150?"...":""}"`),e.path&&!e.path.endsWith(`/${n}.md`)&&s.push(` \u{1F4C1} ${e.path}`),s.join(`
`)}static extractContentSnippet(e,r=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,r).replace(/\s+/g," ").trim():""}static formatWebSearch(e){if(Array.isArray(e)&&e.length>0&&e[0].type==="web_search"){let r=["\u{1F310} Web Search Results"],n=e[0];return n.content&&(r.push(""),r.push(n.content)),n.citations&&n.citations.length>0&&(r.push(""),r.push("Sources:"),n.citations.forEach((o,i)=>{r.push(`[${i+1}] ${o}`)})),n.instruction&&(r.push(""),r.push(`Note: ${n.instruction}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),n=["\u{1F310} Web Search Results"],o=!1,i=[],a=[];for(let s of r){if(s.includes("Sources:")){o=!0;continue}o?a.push(s):s.includes("Here are the web search results")||i.push(s)}return i.length>0&&(n.push(""),n.push(...i.filter(s=>s.trim()))),a.length>0&&(n.push(""),n.push("Sources:"),a.forEach(s=>{s.trim()&&n.push(s)})),n.join(`
`)}return e}static formatYoutubeTranscription(e){let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{return e}else if(typeof e=="object")r=e;else return String(e);if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed
${r.message}`;if(r.results&&Array.isArray(r.results)){let n=[`\u{1F4FA} YouTube Transcripts (${r.total_urls} video${r.total_urls>1?"s":""})`];n.push("");for(let o of r.results){if(o.success){n.push(`\u{1F4F9} Video: ${o.url}`),n.push("");let i=o.transcript.split(`
`),a=0;for(let s of i)if(s.trim()&&(s.match(/^\[(\d+:\d+)\]/)?(a>0&&n.push(""),n.push(`\u23F0 ${s}`)):n.push(` ${s.trim()}`),a++,a>30)){n.push(""),n.push("... (transcript truncated for display)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274C Failed to transcribe: ${o.url}`),n.push(` ${o.message}`);n.push(""),n.push("---"),n.push("")}return n.join(`
`).trimEnd()}if(r.transcript){let n=["\u{1F4FA} YouTube Transcript"];n.push("");let o=r.transcript.split(`
`),i=0;for(let a of o)if(a.trim()&&(a.match(/^\[(\d+:\d+)\]/)?(i>0&&n.push(""),n.push(`\u23F0 ${a}`)):n.push(` ${a.trim()}`),i++,i>50)){n.push(""),n.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
2025-09-01 12:32:47 +08:00
`)}return typeof e=="object"?JSON.stringify(e,null,2):String(e)}static formatWriteToFile(e){let r=typeof e=="object"?e.result:e,n=String(r).toLowerCase();return n.includes("accepted")?"\u2705 File change: accepted":n.includes("rejected")?"\u274C File change: rejected":typeof e=="object"&&e.message?e.message:String(r)}static formatReplaceInFile(e){let r=0,n="";if(typeof e=="object")r=e.blocksApplied||0,n=e.result||"";else if(typeof e=="string"){let i=e.match(/Applied (\d+) SEARCH\/REPLACE block/);i&&(r=parseInt(i[1])),n=e}let o=String(n).toLowerCase();if(o.includes("accepted")){let i=r===1?"replacement":"replacements";return r>0?`\u2705 ${r} ${i} accepted`:"\u2705 File replacements: accepted"}else if(o.includes("rejected"))return r===0?"\u274C No replacements made":"\u274C File replacements: rejected";return typeof e=="object"&&e.message?e.message:String(n)}}});var Vye,knr=b(()=>{P6e();Vye=class{constructor(e,r){this.toolManager=e;this.writeToFileTool=r;this.buffer=""}findCompleteBlock(e){let r=/<writeToFile>[\s\S]*?<\/writeToFile>/,n=e.match(r);return!n||n.index===void 0?null:{block:n[0],endIdx:n.index+n[0].length}}async*processChunk(e){let r="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(r+=o.text);else e.content!=null&&(r=e.content);r&&(this.buffer+=r),yield e;let n=this.findCompleteBlock(this.buffer);for(;n;){let{block:o,endIdx:i}=n,a=o.match(/<path>([\s\S]*?)<\/path>/),s=o.match(/<content>([\s\S]*?)<\/content>/),u=a?a[1].trim():void 0,l=s?s[1].trim():void 0;try{let c=await this.toolManager.callTool(this.writeToFileTool,{path:u,content:l}),d=jH.format("writeToFile",c);yield{...e,content:`
2025-08-30 08:29:39 +08:00
${d}
`}}catch(c){yield{...e,content:`
Error: ${c?.message||c}
2025-09-01 12:32:47 +08:00
`}}this.buffer=this.buffer.substring(i),n=this.findCompleteBlock(this.buffer)}}}});function T6e(t){let e=[];for(let r of t)if(r){if(typeof r._getType=="function"){let n=r._getType();n==="human"?e.push({role:"user",content:r.content}):n==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let n=QUn(r);n&&e.push({role:n,content:r.content})}}return e}function QUn(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function Wye(t,e){let r=T6e(t);for(let n of r)e.push({role:n.role,content:n.content})}function $nr(t){return t.map(e=>{let r;return typeof e.content=="string"?r=e.content:Array.isArray(e.content)?r=e.content.filter(o=>o.type==="text").map(o=>o.text||"").join(" ")||"[Image content]":r=String(e.content||""),{role:e.role,content:r}})}var A6e=b(()=>{});function I6e(t){if(!Array.isArray(t))return"";let e=t.filter(n=>n.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map(n=>{let o=n.title||"Untitled",i=n.path||"",a=null;if(n.mtime){let s=new Date(n.mtime);isNaN(s.getTime())||(a=s.toISOString())}return`<document>
2025-08-30 08:29:39 +08:00
<title>${o}</title>${i&&i!==o?`
<path>${i}</path>`:""}${a?`
<modified>${a}</modified>`:""}
<content>
${n.content||""}
</content>
</document>`}).filter(n=>n.length>0).join(`
2025-09-01 12:32:47 +08:00
`)}function Bnr(t){try{let e=JSON.parse(t);return Array.isArray(e)?I6e(e):"Invalid search results format."}catch(e){return Bt("Failed to format localSearch result string:",e),"Error processing search results."}}function znr(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}var Unr=b(()=>{Gt()});async function M6e(t,e,r){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};let o=e.find(u=>u.name===t.name);if(!o){let u=e.map(l=>l.name).join(", ");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${u}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}if(o.isPlusOnly&&!await lO())return{toolName:t.name,result:`Error: ${Yk(t.name)} requires a Copilot Plus subscription`,success:!1};let i={...t.args};o.requiresUserMessageContent&&r&&(i._userMessageContent=r);let a=6e4;typeof o.timeoutMs=="number"&&(a=o.timeoutMs);let s;return!a||a===1/0?s=await DO.callTool(o,i):s=await Promise.race([DO.callTool(o,i),new Promise((u,l)=>setTimeout(()=>l(new Error(`Tool execution timed out after ${a}ms`)),a))]),s==null?(Bt(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Tool executed but returned no result",status:"empty"}),success:!0}):{toolName:t.name,result:typeof s=="string"?s:JSON.stringify(s),success:!0}}catch(o){return ie(`Error executing tool ${t.name}:`,o),{toolName:t.name,result:`Error: ${eo(o)}`,success:!1}}}function Yk(t){return t==="localSearch"?oe().enableSemanticSearchV3?"vault search (semantic)":"vault search (index-free)":{webSearch:"web search",getFileTree:"file tree",getCurrentTime:"current time",getTimeRangeMs:"time range",getTimeInfoByEpoch:"time info",convertTimeBetweenTimezones:"timezone converter",startPomodoro:"pomodoro timer",pomodoroTool:"pomodoro timer",simpleYoutubeTranscriptionTool:"YouTube transcription",youtubeTranscription:"YouTube transcription",indexVault:"vault indexing",indexTool:"index",writeToFile:"file editor",replaceInFile:"file editor"}[t]||t}function DH(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetweenTimezones:"\u{1F30D}",startPomodoro:"\u23F1\uFE0F",pomodoroTool:"\u23F1\uFE0F",simpleYoutubeTranscriptionTool:"\u{1F4FA}",youtubeTranscription:"\u{1F4FA}",indexVault:"\u{1F4DA}",indexTool:"\u{1F4DA}",writeToFile:"\u270F\uFE0F",replaceInFile:"\u{1F504}"}[t]||"\u{1F527}"}function qnr(t,e){if(t=="writeToFile"||t=="replaceInFile")return"Accept / reject in the Preview";if(t==="localSearch"&&e?.salientTerms&&!oe().enableSemanticSearchV3){let n=Array.isArray(e.salientTerms)?e.salientTerms:[];if(n.length>0)return`Terms: ${n.slice(0,3).join(", ")}${n.length>3?"...":""}`}return null}function R6e(t,e){let r=Yk(t.name),n=DH(t.name),o=Object.keys(t.args).length>0?JSON.stringify(t.args,null,2):"(no parameters)";B(`${n} [Iteration ${e}] ${r.toUpperCase()}`),B("Parameters:",o),B("---")}function N6e(t,e){let r=Yk(t),n=DH(t),o=e.success?"\u2705 SUCCESS":"\u274C FAILED";B(`${n} ${r.toUpperCase()} RESULT: ${o}`);let i=300;e.result.length>i?B(`Result: ${e.result.substring(0,i)}... (truncated, ${e.result.length} chars total)`):B("Result:",e.result),B("---")}function EZ(t){let e=new Map;for(let r of t){let n=r.path||r.title,o=e.get(n);(!o||r.score>o.score)&&e.set(n,r)}return Array.from(e.values()).sort((r,n)=>n.score-r.score)}var Kye=b(()=>{Gt();ly();bt();l7();ir()});var LO,Gye=b(()=>{QHe();or();mze();My();Gt();ly();bt();sVe();l7();ir();Hye();sG();knr();A6e();Unr();g4();Kye();LO=class extends qP{isYoutubeOnlyMessage(e){let r=e.trim(),n=r.includes("@youtube"),o=XSe(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 pF.processUrlBatch(e,r,this.chainManager.app.vault);return pF.showFailedImagesNotice(r),n}async processChatInputI
`}for(;(a=n.exec(e))!==null;){let s=a[1],u;for(;(u=o.exec(s))!==null;)i+=u[1]+`
`}return i.trim()}async extractEmbeddedImages(e,r){let n=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,o=/!\[.*?\]\(([^)]+)\)/g,i=[],a=[...e.matchAll(n)];for(let u of a){let l=u[1];if(r){let c=app.metadataCache.getFirstLinkpathDest(l,r);c?i.push(c.path):(Bt(`Could not resolve embedded image: ${l} from source: ${r}`),i.push(l))}else i.push(l)}let s=[...e.matchAll(o)];for(let u of s){let l=u[1].trim();if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}let c=l.replace(/^\.\//,"").replace(/^\//,"");if(r){let d=app.metadataCache.getFirstLinkpathDest(c,r);d?i.push(d.path):i.push(c)}else i.push(c)}return i}async buildMessageContent(e,r){let n=[],o=[],i=oe(),a=[];if(i.passMarkdownImages){let c;if(r.context?.notes&&r.context.notes.length>0)c=r.context.notes[0].path;else{let f=this.chainManager.app?.workspace.getActiveFile();f&&(c=f.path)}let d=this.extractNoteContent(e);if(d){let f=await this.extractEmbeddedImages(d,c);f.length>0&&a.push({urls:f,type:"embedded"})}}for(let c of a){let d=await this.processImageUrls(c.urls);o.push(...d.successfulImages),n.push(...d.failureDescriptions)}let s=r.content;if(s&&s.length>0){let c=await this.processChatInputImages(s);o.push(...c.successfulImages),n.push(...c.failureDescriptions)}let u=e;n.length>0&&(u=`${e}
2025-07-05 20:48:33 +08:00
Note:
${n.join(`
`)}
2025-09-01 12:32:47 +08:00
`);let l=[{type:"text",text:u}];return o.length>0&&l.push(...o),l}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")}appendComposerInstructionsIfNeeded(e,r){if(!r.message||!r.message.includes("@composer"))return e;let n=`<OUTPUT_FORMAT>
${Bet}
2025-08-30 08:29:39 +08:00
</OUTPUT_FORMAT>`;return`${e}
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${n}`}async streamMultimodalResponse(e,r,n,o){let s=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],u=[],l=await this.getSystemPrompt();s.length>0&&(l+=`
2025-09-01 12:32:47 +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:eI(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.`}),Wye(s,u);let d=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?await this.buildMessageContent(e,r):e;u.push({role:"user",content:p});let h=p instanceof Array?p[0].text:p;B("Enhanced user message: ",h),B(`==== Final Request to AI ====
`,u);let m=new Vye(DO,sye),g=new __(o),y=await Od(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));for await(let _ of y){if(n.signal.aborted){B("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}for await(let w of m.processChunk(_))g.processChunk(w)}return g.close()}async run(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="";if(!await lO({isCopilotPlus:!0}))return await this.handleError(new Error("Invalid license key"),o,n),"";let d=f=>{l=f,n(f)};try{if(this.isYoutubeOnlyMessage(e.message)){let M=XSe(e.message),D="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(M)try{let k=await Ji.getInstance().youtube4llm(M);return k.response.transcript?this.handleResponse(k.response.transcript,e,r,o,n):this.handleResponse(D,e,r,o,n)}catch(k){return ie("Error processing YouTube video:",k),this.handleResponse(D,e,r,o,n)}}B("==== Step 1: Analyzing intent ====");let f,p=e.originalMessage||e.message;try{f=await Zk.analyzeIntent(p)}catch(M){return this.handleResponse(Tet(M),e,r,o,n)}let h=e.message.split(" ").filter(M=>!OZ.includes(M.toLowerCase())).join(" ").trim(),{toolOutputs:m,sources:g}=await this.executeToolCalls(f,a);u=g;let _=m.find(M=>M.tool==="localSearch"&&M.output!=null)&&u.length>0,C=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],E=T6e(C),P=$nr(E),T=h;P.length>0&&(B("==== Condensing Question ===="),T=await rye(h,P),B("Condensed standalone question: ",T));let I=this.prepareEnhancedUserMessage(T,m,f),N=m.some(M=>M.tool!=="localSearch"&&M.output!=null);_&&!N&&(I=`Answer the question with as detailed as possible based only on the following context:
${I}`),I=this.appendComposerInstructionsIfNeeded(I,e),B("==== Invoking LLM with all tool results ===="),s=await this.streamMultimodalResponse(I,e,r,d)}catch(f){a?.(Iv.DEFAULT),f.name==="AbortError"||r.signal.aborted?B("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(f,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)?(Bt("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){Bt("Invalid document structure:",n);continue}let o=n.path||n.title,i=r.get(o),a=n&&"rerank_score"in n,s=a?n.rerank_score:n.score;(!i||s>(i.score??0))&&r.set(o,{title:n.title,path:n.path||n.title,score:s,isReranked:a,explanation:n.explanation||null})}return Array.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}async executeToolCalls(e,r){let n=[],o=[];for(let i of e){B(`==== Step 2: Calling tool: ${i.tool.name} ====`),i.tool.name==="localSearch"?r?.(Iv.READING_FILES):i.tool.name==="webSearch"?r?.(Iv.SEARCHING_WEB):i.tool.name==="getFileTree"&&r?.(Iv.READING_FILE_TREE);let a=await DO.callTool(i.tool,i.args);if(i.tool.name==="localSearch"){let u={result:typeof a=="string"?a:JSON.stringify(a),success:a!=null},l=this.getTimeExpression(e),c=this.processLocalSearchResult(u,l);o.push(...c.sources),n.push({tool:i.tool.name,output:c.formattedForLLM})}else n.push({tool:i.tool.name,output:a})}return{toolOutputs:n,sources:EZ(o)}}prepareEnhancedUserMessage(e,r,n){let o="",i=!1,a=r.find(s=>s.tool==="localSearch"&&s.output!=null);if(a&&typeof a.output=="string")try{let s=JSON.parse(a.output);Array.isArray(s)&&s.length>0&&(i=!0)}catch{}if(r.length>0){let s=r.filter(u=>u.output!=null);s.length>0&&(o=(i&&s.length===1?"":`
2025-07-05 20:48:33 +08:00
# Additional context:
2025-08-30 08:29:39 +08:00
`)+s.map(l=>{let c=l.output;return typeof c!="string"&&(c=JSON.stringify(c)),l.tool==="localSearch"?c:`<${l.tool}>
${c}
</${l.tool}>`}).join(`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
`))}return i&&r.filter(s=>s.output!=null).length===1?`${o}
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
Question: ${e}`:`${e}${o}`}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),0),i=n;if(o>oCe){let s=oCe/o;B("Truncating document contents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content?.slice(0,Math.floor((u.content?.length||0)*s))||""}))}let a=I6e(i);return r?`<localSearch timeRange="${r}">
2025-08-30 08:29:39 +08:00
${a}
</localSearch>`:`<localSearch>
${a}
</localSearch>`}processLocalSearchResult(e,r){let n=[],o;if(!e.success)return o=`<localSearch>
Search failed.
</localSearch>`,{formattedForLLM:o,sources:n};try{let i=JSON.parse(e.result);if(!Array.isArray(i))return o=`<localSearch>
Invalid search results format.
2025-09-01 12:32:47 +08:00
</localSearch>`,{formattedForLLM:o,sources:n};n=znr(i),o=this.prepareLocalSearchResult(i,r||"")}catch(i){Bt("Failed to parse localSearch results:",i);let a=Bnr(e.result);o=r?`<localSearch timeRange="${r}">
2025-08-30 08:29:39 +08:00
${a}
</localSearch>`:`<localSearch>
${a}
2025-09-01 12:32:47 +08:00
</localSearch>`}return{formattedForLLM:o,sources:n}}async getSystemPrompt(){return Mf()}}});var PZ,Vnr=b(()=>{ua();bt();mR();Gye();PZ=class extends LO{async getSystemPrompt(){let e=Mf(),r=wu();if(!r)return e;let n=await Vd.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-09-01 12:32:47 +08:00
</project_context>`),e}}});var FO,Jye=b(()=>{FO=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(r=>this.register(r))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,r){let n=[];for(let[o,i]of this.tools){let{metadata:a,tool:s}=i;if(a.isAlwaysEnabled){(!a.requiresVault||r)&&n.push(s);continue}e.has(o)&&(!a.requiresVault||r)&&n.push(s)}return n}getToolsByCategory(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.category;e.has(n)||e.set(n,[]),e.get(n).push(r)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getToolMetadata(e){return this.tools.get(e)?.metadata}clear(){this.tools.clear()}}});function tqn(t){FO.getInstance().register({tool:uye(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,customPromptInstructions:`For getFileTree:
2025-08-30 08:29:39 +08:00
- Use to browse the vault's file structure
- No parameters needed
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>getFileTree</name>
2025-09-01 12:32:47 +08:00
</use_tool>`}})}function Zye(t){let e=FO.getInstance(),r=e.getToolMetadata("getFileTree")!==void 0,n=t!==void 0;(e.getAllTools().length===0||r!==n)&&(e.clear(),e.registerAll(eqn),t&&tqn(t))}var eqn,j6e=b(()=>{Jye();fVe();O6e();E6e();sVe();cVe();eqn=[{tool:c7,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",customPromptInstructions:`For localSearch (searching notes in the vault):
2025-08-30 08:29:39 +08:00
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>localSearch</name>
<query>piano learning practice</query>
<salientTerms>["piano", "learning", "practice"]</salientTerms>
</use_tool>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
For localSearch with time range (e.g., "what did I do last week"):
Step 1 - Get time range:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Step 2 - Search with time range (after receiving time range result):
<use_tool>
<name>localSearch</name>
<query>what did I do</query>
<salientTerms>[]</salientTerms>
<timeRange>{"startTime": {...}, "endTime": {...}}</timeRange>
</use_tool>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
For localSearch with meaningful terms (e.g., "python debugging notes from yesterday"):
Step 1 - Get time range:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>yesterday</timeExpression>
</use_tool>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Step 2 - Search with time range:
<use_tool>
<name>localSearch</name>
<query>python debugging notes</query>
<salientTerms>["python", "debugging", "notes"]</salientTerms>
<timeRange>{"startTime": {...}, "endTime": {...}}</timeRange>
</use_tool>
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
For localSearch with non-English query (PRESERVE ORIGINAL LANGUAGE):
<use_tool>
<name>localSearch</name>
<query>\u94A2\u7434\u5B66\u4E60</query>
<salientTerms>["\u94A2\u7434", "\u5B66\u4E60"]</salientTerms>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:d7,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the internet for information",category:"search",customPromptInstructions:`For webSearch:
2025-08-30 08:29:39 +08:00
- Only use when the user explicitly requests web/internet search
- Always provide an empty chatHistory array
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>webSearch</name>
<query>piano learning techniques</query>
<chatHistory>[]</chatHistory>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:$ye,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example 1 - "what time is it" (local time):
<use_tool>
<name>getCurrentTime</name>
</use_tool>
2025-08-12 16:40:13 +08:00
2025-08-30 08:29:39 +08:00
Example 2 - "what time is it in Tokyo" (UTC+9):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>+9</timezoneOffset>
</use_tool>
2025-08-12 16:40:13 +08:00
2025-08-30 08:29:39 +08:00
Example 3 - "what time is it in New York" (UTC-5 or UTC-4 depending on DST):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>-5</timezoneOffset>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:zye,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:Bye,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
2025-08-30 08:29:39 +08:00
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
2025-08-12 16:40:13 +08:00
2025-08-30 08:29:39 +08:00
Example:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:Uye,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
2025-08-12 16:40:13 +08:00
2025-08-30 08:29:39 +08:00
Example - "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9):
<use_tool>
<name>convertTimeBetweenTimezones</name>
<time>6pm</time>
<fromOffset>-8</fromOffset>
<toOffset>+9</toOffset>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:CZ,metadata:{id:"pomodoro",displayName:"Pomodoro Timer",description:"Manage time with Pomodoro technique",category:"time"}},{tool:sye,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,customPromptInstructions:`For writeToFile:
2025-08-30 08:29:39 +08:00
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeToFile for any intent of updating or creating files
- Do not call writeToFile tool again if the result is not accepted
- Do not call writeToFile tool if no change needs to be made
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
</use_tool>`}},{tool:Uer,metadata:{id:"replaceInFile",displayName:"Replace in File",description:"Make targeted changes to existing files using SEARCH/REPLACE blocks",category:"file",requiresVault:!0,customPromptInstructions:`For replaceInFile:
- Remember: Small edits \u2192 replaceInFile, Major rewrites \u2192 writeToFile
- SEARCH text must match EXACTLY including all whitespace
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>replaceInFile</name>
<path>notes/meeting.md</path>
<diff>
------- SEARCH
## Attendees
- John Smith
- Jane Doe
=======
## Attendees
- John Smith
- Jane Doe
- Bob Johnson
+++++++ REPLACE
</diff>
2025-09-01 12:32:47 +08:00
</use_tool>`}},{tool:Fnr,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",customPromptInstructions:`For youtubeTranscription:
2025-08-30 08:29:39 +08:00
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
Example usage:
<use_tool>
<name>youtubeTranscription</name>
2025-09-01 12:32:47 +08:00
</use_tool>`}}]});function rqn(){return 1e4}function nqn(t,e){let r=e??rqn();if(!t||t.length<=r)return t;let n=t.substring(0,r),o=t.length-r;return`${n}
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
... (truncated ${o.toLocaleString()} characters)`}function oqn(t,e,r){let n=nqn(e,r);return`Tool '${t}' result: ${n}`}function D6e(t,e=!1){return t.map(r=>e?oqn(r.toolName,r.result):`Tool '${r.toolName}' result: ${r.result}`).join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`)}var Wnr=b(()=>{});function Knr(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],r=t.toLowerCase();return e.some(n=>r.includes(n))}var $6e,Xk,L6e,F6e,k6e,TZ,Gnr=b(()=>{Gt();$6e=50,Xk=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let r=[];for(let n of e)n.customPromptInstructions&&r.push(n.customPromptInstructions);return r.length>0?r.join(`
2025-08-30 08:29:39 +08:00
`):""}enhanceSystemPrompt(e,r,n,o){let i=o||[],a=this.buildToolSpecificInstructions(i);return`${e}
# Autonomous Agent Mode
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
When you need to use a tool, format it EXACTLY like this:
<use_tool>
<name>tool_name_here</name>
<parameter_name>value</parameter_name>
<another_parameter>["array", "values"]</another_parameter>
</use_tool>
IMPORTANT: Use the EXACT parameter names as shown in the tool descriptions below. Do NOT use generic names like "param1" or "param".
Available tools:
${r}
# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
${a?a+`
`:""}## General Guidelines
- Think hard about whether a query could potentially be answered from personal knowledge or notes, if yes, call a vault search (localSearch) first
- Only use web search if: the query explicitly asks for web search, OR the query explicitly requires current/web information
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
IMPORTANT: Do not include any code blocks (\`\`\`) or tool_code blocks in your responses. Only use the <use_tool> format for tool calls.
2025-09-01 12:32:47 +08:00
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},L6e=class extends Xk{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}enhanceSystemPrompt(e,r,n,o){let i=super.enhanceSystemPrompt(e,r,n,o),a=n||[],s=a.includes("writeToFile")||a.includes("replaceInFile"),u="";return this.isGPT5Model()?u=`
2025-08-30 08:29:39 +08:00
GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search
Example localSearch without time:
<use_tool>
<name>localSearch</name>
<query>piano notes</query>
<salientTerms>["piano", "notes"]</salientTerms>
</use_tool>`:u=`
CRITICAL FOR GPT MODELS: You MUST ALWAYS include XML tool calls in your response. Do not just describe what you plan to do - you MUST include the actual XML tool call blocks.`,s&&(u+=`
\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS - GPT SPECIFIC EXAMPLES \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use replaceInFile) or major rewrite (use writeToFile)
2. Include the tool call immediately in your response
EXAMPLE 1 - User says "fix the typo 'teh' to 'the' in my note":
\u2705 CORRECT RESPONSE:
"I'll fix the typo in your note.
<use_tool>
<name>replaceInFile</name>
<path>path/to/note.md</path>
<diff>
------- SEARCH
teh
=======
the
+++++++ REPLACE
</diff>
</use_tool>"
EXAMPLE 2 - User says "add item 4 to the list":
\u2705 CORRECT RESPONSE:
"I'll add item 4 to your list.
<use_tool>
<name>replaceInFile</name>
<path>path/to/file.md</path>
<diff>
------- SEARCH
- Item 1
- Item 2
- Item 3
=======
- Item 1
- Item 2
- Item 3
- Item 4
+++++++ REPLACE
</diff>
</use_tool>"
\u274C WRONG (DO NOT DO THIS):
"I'll help you add item 4 to the list. Let me update that for you."
[No tool call = FAILURE]
CRITICAL: The diff parameter MUST contain the SEARCH/REPLACE blocks wrapped in triple backticks EXACTLY as shown above.`),u+=`
FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST include the appropriate <use_tool> XML block in your very next response. Do not wait for another turn.`,i+u}enhanceUserMessage(e,r){return r?this.getBaseEnhancement(e,r):e}getBaseEnhancement(e,r){if(!r)return e;let n=e.toLowerCase(),o=n.includes("find")||n.includes("search")||n.includes("my notes"),i=n.includes("edit")||n.includes("modify")||n.includes("update")||n.includes("change")||n.includes("fix")||n.includes("add")||n.includes("typo");return o?`${e}
REMINDER: Use the <use_tool> XML format to call the localSearch tool.`:i?`${e}
2025-09-01 12:32:47 +08:00
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter). The diff parameter MUST contain triple backticks around the SEARCH/REPLACE blocks. Check the examples in your system prompt.`:e}needsSpecialHandling(){return!0}},F6e=class extends Xk{isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}enhanceSystemPrompt(e,r,n,o){let i=super.enhanceSystemPrompt(e,r,n,o);if(this.isThinkingModel()){let a=`
2025-08-30 08:29:39 +08:00
IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Place ALL tool calls AFTER your thinking is complete, in the main response body
- Tool calls must be in the main response body, NOT inside thinking sections
- Format tool calls exactly as shown in the examples above
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
- If you need to use tools, include them immediately after your thinking, before any final response
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information (place tool calls in main response)
3. Wait for tool results
4. Provide final response based on gathered information
INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`;return this.isClaudeSonnet4()&&(a+=`
\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
\u{1F504} CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information: <use_tool>...</use_tool>
4. \u270B STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer
\u2705 IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer
\u{1F3AF} CORRECT FIRST RESPONSE PATTERN (when tools needed):
I'll search your vault for piano practice information.
<use_tool>
<name>localSearch</name>
<query>piano practice</query>
<salientTerms>["piano", "practice"]</salientTerms>
</use_tool>
\u{1F310} MULTILINGUAL EXAMPLE (PRESERVE ORIGINAL LANGUAGE):
<use_tool>
<name>localSearch</name>
<query>\u30D4\u30A2\u30CE\u306E\u7DF4\u7FD2\u65B9\u6CD5</query>
<salientTerms>["\u30D4\u30A2\u30CE", "\u7DF4\u7FD2", "\u65B9\u6CD5"]</salientTerms>
</use_tool>
<use_tool>
<name>webSearch</name>
<query>piano techniques</query>
<chatHistory>[]</chatHistory>
</use_tool>
[RESPONSE ENDS HERE - NO MORE TEXT]
\u{1F3AF} CORRECT FOLLOW-UP RESPONSE PATTERN:
Let me gather more specific information about practice schedules.
<use_tool>
<name>localSearch</name>
<query>practice schedule</query>
<salientTerms>["practice", "schedule"]</salientTerms>
</use_tool>
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C WRONG PATTERN (DO NOT DO THIS):
<use_tool>...</use_tool>
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i+a}return i}needsSpecialHandling(){return this.isThinkingModel()}detectPrematureResponse(e){let r=e.indexOf("<use_tool>");if(r===-1)return{hasPremature:!1,type:null};let o=e.substring(0,r).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim();if(o.split(/[.!?]+/).filter(u=>u.trim().length>0).length>2||o.length>200)return{hasPremature:!0,type:"before"};let s=e.lastIndexOf("</use_tool>");return s!==-1&&e.substring(s+11).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim().length>100?{hasPremature:!0,type:"after"}:{hasPremature:!1,type:null}}sanitizeResponse(e,r){if(!this.isClaudeSonnet4()||r!==1)return e;let n=this.detectPrematureResponse(e);if(!n.hasPremature)return e;if(n.type==="after"){let o=e.lastIndexOf("</use_tool>");if(o!==-1){let i=e.substring(0,o+11),a=e.substring(o+11),s=/<think>[\s\S]*?<\/think>/g,u=a.match(s)||[];return i+(u.length>0?`
`+u.join(`
2025-09-01 12:32:47 +08:00
`):"")}}return e}shouldTruncateStreaming(e){if(!this.isClaudeSonnet4())return!1;let r=e.lastIndexOf("</use_tool>");return r===-1?!1:e.substring(r+11).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim().length>$6e}},k6e=class extends Xk{enhanceSystemPrompt(e,r,n,o){let i=super.enhanceSystemPrompt(e,r,n,o),u=`
2025-08-30 08:29:39 +08:00
\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(n||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT:
<use_tool>
<name>localSearch</name>
<query>piano</query>
<salientTerms>["piano"]</salientTerms>
</use_tool>
`:""}
GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
PATTERN FOR MULTI-STEP REQUESTS:
User: "based on my project roadmap notes and create summary"
Your response:
<use_tool>
<name>localSearch</name>
<query>project roadmap</query>
<salientTerms>["project", "roadmap"]</salientTerms>
</use_tool>
Remember: The user has already told you what to do. Execute it NOW with the available tools.`;return i+u}enhanceUserMessage(e,r){return r?`${e}
2025-09-01 12:32:47 +08:00
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},TZ=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(B(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new L6e(r);return n.isGPT5Model()?B("Using GPTModelAdapter with GPT-5 specific enhancements"):B("Using GPTModelAdapter"),n}return r.includes("claude")?(B("Using ClaudeModelAdapter"),new F6e(r)):r.includes("gemini")||r.includes("google/gemini")?(B("Using GeminiModelAdapter"),new k6e(r)):r.includes("copilot-plus")?(B("Using BaseModelAdapter for Copilot Plus"),new Xk(r)):(B("Using BaseModelAdapter (default)"),new Xk(r))}}});function Yye(t){let e=[];try{let r=/<use_tool>([\s\S]*?)<\/use_tool>/g,n;for(;(n=r.exec(t))!==null;){let o=n[1],i=o.match(/<name>([\s\S]*?)<\/name>/);if(i){let a=i[1].trim();if(!a||a.length===0){Bt("Skipping tool call with empty name");continue}let s={},u=o.replace(/<name>[\s\S]*?<\/name>/,""),l=/<([^>]+)>([\s\S]*?)<\/\1>/g,c;for(;(c=l.exec(u))!==null;){let d=c[1].trim(),f=c[2].trim();d&&(s[d]=B6e(f,d))}e.push({name:a,args:s})}}}catch(r){return ie("Error parsing XML tool calls:",r),[]}return e}function B6e(t,e){if(!t)return e==="chatHistory"||e==="salientTerms"?[]:"";if(!/<[^>]+>/.test(t)){if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{return JSON.parse(t)}catch{return t}return t}let n=t.match(/<item>([\s\S]*?)<\/item>/g);if(n)return n.map(s=>{let u=s.replace(/<\/?item>/g,"").trim();return B6e(u)});let o=/<([^>]+)>([\s\S]*?)<\/\1>/g,i=[],a;for(;(a=o.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();i.push([s,B6e(u)])}return i.length>0?Object.fromEntries(i):t}function Jnr(t){t=t.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,"");let e=t.match(/<use_tool>([\s\S]*)/),n=(e?e[1]:t).match(/<name>([\s\S]*?)<\/name>/);return n&&n[1].trim()||null}function AZ(t){let e=t;return e=e.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,""),e=e.replace(/<use_tool>([\s\S]*)$/g,""),e=e.replace(/```\w*\s*```/g,""),e=e.replace(/```tool_code[\s\S]*?```/g,""),e=e.replace(/```[\w]*[\s\n]*```/g,""),e=e.replace(/\n\s*\n\s*\n/g,`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`).trim(),e}var z6e=b(()=>{Gt()});var IZ,Znr=b(()=>{Gt();ly();bt();j6e();$k();Jye();ir();Wnr();Gye();A6e();Gnr();g4();h4();Kye();z6e();IZ=class t extends LO{constructor(){super(...arguments);this.llmFormattedMessages=[]}getAvailableTools(){let r=oe(),n=FO.getInstance();n.getAllTools().length===0&&Zye(this.chainManager.app?.vault);let o=new Set(r.autonomousAgentEnabledToolIds||[]);return n.getEnabledTools(o,!!this.chainManager.app?.vault)}static generateToolDescriptions(r){return r.map(o=>{let i="",a=$er(o.schema);return Object.keys(a).length>0&&(i=Object.entries(a).map(([s,u])=>`<${s}>${u}</${s}>`).join(`
2025-08-30 08:29:39 +08:00
`)),`<${o.name}>
<description>${o.description}</description>
<parameters>
${i}
</parameters>
</${o.name}>`}).join(`
2025-09-01 12:32:47 +08:00
`)}static generateSystemPrompt(r,n){let o=Mf(),i=t.generateToolDescriptions(r),a=r.map(l=>l.name),s=FO.getInstance(),u=r.map(l=>s.getToolMetadata(l.name)).filter(l=>l!==void 0);return n.enhanceSystemPrompt(o,i,a,u)}generateSystemPrompt(){let r=this.getAvailableTools(),n=this.chainManager.chatModelManager.getChatModel(),o=TZ.createAdapter(n);return t.generateSystemPrompt(r,o)}getTemporaryToolCallId(r,n){return`temporary-tool-call-id-${r}-${n}`}async run(r,n,o,i,a){let s="",u=[],l=[],c=[];if(this.llmFormattedMessages=[],!await lO({isAutonomousAgent:!0}))return await this.handleError(new Error("Invalid license key"),i,o),"";try{let g=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],y=this.generateSystemPrompt(),_=this.chainManager.chatModelManager.getChatModel(),w=TZ.createAdapter(_);y&&u.push({role:eI(_),content:y}),Wye(g,u);let S=this.isMultimodalModel(_),C=Knr(r.message),E=w.enhanceUserMessage(r.message,C),P=S?await this.buildMessageContent(E,r):E;u.push({role:"user",content:P});let T=r.originalMessage||r.message,I=oe().autonomousAgentMaxIterations,N=0;for(;N<I&&!n.signal.aborted;){N++,B(`=== Autonomous Agent Iteration ${N} ===`);let M=[],D=await this.streamResponse(u,n,V=>{let q=AZ(V),H=[];H.push(...l),q.trim()&&H.push(q);let G=Yye(V),Z=[];G.length>0&&(Z=G.map(Ae=>Ae.name));let de=this.getAvailableTools(),pe=new Set(de.filter(Ae=>Ae.isBackground).map(Ae=>Ae.name)),ae=Jnr(V);if(ae){let Ae=V.lastIndexOf(ae);V.length-Ae>$6e&&Z.push(ae)}Z=Z.filter(Ae=>!pe.has(Ae));for(let Ae=0;Ae<Z.length;Ae++){let ke=Z[Ae],Ot=this.getTemporaryToolCallId(ke,Ae);if(M.findIndex(Vn=>Vn.includes(Ot))!==-1)continue;let Mr=Fde(Ot,ke,Yk(ke),DH(ke),"",!0,"","");M.push(Mr)}M.length>0&&H.push(M.join(`
2025-08-30 08:29:39 +08:00
`));let Te=H.join(`
2025-09-01 12:32:47 +08:00
`);o(Te)},w);if(!D)break;let k=Yye(D),F=w.detectPrematureResponse?.(D);if(F?.hasPremature&&N===1&&(F.type==="before"?(Bt("\u26A0\uFE0F Model provided premature response BEFORE tool calls!"),Bt("Sanitizing response to keep only tool calls for first iteration")):F.type==="after"&&(Bt("\u26A0\uFE0F Model provided hallucinated response AFTER tool calls!"),Bt("Truncating response at last tool call for first iteration"))),k.length===0){let V=AZ(D),q=[...l];V.trim()&&q.push(V),s=q.join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`),this.llmFormattedMessages.push(D);break}let K=D;w.sanitizeResponse&&F?.hasPremature&&(K=w.sanitizeResponse(D,N));let U=AZ(K);U.trim()&&l.push(U);let X=[],ee=new Map;M.splice(k.length);for(let V=0;V<k.length;V++){let q=k[V];if(n.signal.aborted)break;R6e(q,N);let H=this.getAvailableTools(),Z=H.find(ae=>ae.name===q.name)?.isBackground||!1,de;if(!Z){let ae=DH(q.name),Te=Yk(q.name),Ae=qnr(q.name);de=`${q.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ee.set(V,de);let ke=Fde(de,q.name,Te,ae,Ae||"",!0,"",""),Ot=M.findIndex(Mr=>Mr.includes(this.getTemporaryToolCallId(q.name,V)));Ot!==-1?M[Ot]=ke:(M.push(ke),Bt("Created tool call marker for tool call that was not created during streaming",q.name));let jr=[...l,...M].join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`);o(jr)}let pe=await M6e(q,H,T);if(q.name==="localSearch"){let ae=this.processLocalSearchResult(pe);c.push(...ae.sources),pe.result=ae.formattedForLLM}if(X.push(pe),de&&!Z){let ae=M.findIndex(Ae=>Ae.includes(de));ae!==-1&&(M[ae]=vze(M[ae],de,pe.result));let Te=[...l,...M].join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`);o(Te)}N6e(q.name,pe)}if(M.length>0){let V=M.join(`
`);l.push(V)}if(this.llmFormattedMessages.push(D),X.length>0){let V=D6e(X,!0);V&&this.llmFormattedMessages.push(V)}let{ensureEncodedToolCallMarkerResults:L}=await Promise.resolve().then(()=>(h4(),kde)),Q=L(D);u.push({role:"assistant",content:Q});let z=D6e(X,!1);u.push({role:"user",content:z});let W=z.length>500?z.substring(0,500)+"... (truncated)":z;B("Tool results added to conversation:",W)}if(N>=I&&!s){Bt(`Autonomous agent reached maximum iterations (${I}) without completing the task`);let M=`
2025-08-30 08:29:39 +08:00
I've reached the maximum number of iterations (${I}) for this task. I attempted to gather information using various tools but couldn't complete the analysis within the iteration limit. You may want to try a more specific question or break down your request into smaller parts.`;s=l.join(`
2025-09-01 12:32:47 +08:00
`)+M}}catch(h){if(h.name==="AbortError"||n.signal.aborted)B("Autonomous agent stream aborted by user",{reason:n.signal.reason});else{ie("Autonomous agent failed, falling back to regular Plus mode:",h);try{return await new LO(this.chainManager).run(r,n,o,i,a)}catch(m){return ie("Fallback to regular Plus mode also failed:",m),await this.handleError(m,i,o),""}}}let f=EZ(c),p=this.llmFormattedMessages.join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`);return!s&&l.length>0&&(Bt("fullAIResponse was empty, using iteration history"),s=l.join(`
2025-08-30 08:29:39 +08:00
2025-09-01 12:32:47 +08:00
`)),await Promise.resolve().then(()=>(h4(),kde)),this.handleResponse(s,r,n,i,o,f.length>0?f:void 0,p)}async streamResponse(r,n,o,i){let a=new __(o,i),s=2,u=0;for(;u<=s;)try{let l=await Od(()=>this.chainManager.chatModelManager.getChatModel().stream(r,{signal:n.signal}));for await(let c of l){if(n.signal.aborted)break;a.processChunk(c)}return a.close()}catch(l){if(l.name==="AbortError"||n.signal.aborted)return a.close();if((l?.message?.includes("overloaded")||l?.message?.includes("Overloaded")||l?.error?.type==="overloaded_error")&&u<s){u++,B(`Retrying autonomous agent request (attempt ${u}/${s+1}) due to overloaded error`),await new Promise(d=>setTimeout(d,1e3*u));continue}throw l}return a.close()}}});var Ynr=b(()=>{sG();aHt();Oer();Gye();Vnr();Znr();g4();z6e();Kye()});var LH,Xnr,Xye,U6e,Qnr=b(()=>{LH=class{},Xnr=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},Xye=(t,e)=>{let r=Xnr(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},U6e=(t,e)=>{let r=Xnr(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}});var MZ=b(()=>{Qnr()});var q6e,FH,eor=b(()=>{cj();vj();q6e=class extends ym{addUserMessage(e){return this.addMessage(new Xs(e))}addAIChatMessage(e){return this.addMessage(new kn(e))}addAIMessage(e){return this.addMessage(new kn(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},FH=class extends q6e{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 tor=b(()=>{eor()});var H6e=b(()=>{tor()});var K_,k1=b(()=>{MZ();H6e();K_=class extends LH{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 FH,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(Xye(e,this.inputKey)),await this.chatHistory.addAIChatMessage(U6e(r,this.outputKey))}async clear(){await this.chatHistory.clear()}}});var RZ,ror=b(()=>{$s();k1();RZ=class extends K_{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]:Op(r,this.humanPrefix,this.aiPrefix)}}}});var nor=b(()=>{MZ();$s()});var oor=b(()=>{UA()});var ior=b(()=>{Zf();oor();Pm();ig()});var aor=b(()=>{Db()});var V6e=b(()=>{ig();ZA();Pm();ior();aor()});var Qye=b(()=>{ZA()});var W6e=b(()=>{$s();V6e();Qye();k1()});var NZ,sor=b(()=>{$s();k1();NZ=class extends K_{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.c
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-09-01 12:32:47 +08:00
`;this.qaPrompt=Em.fromMessages([JA.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 ebe,LZ,vor=b(()=>{ua();vu();or();Ynr();Gt();bt();ir();ZA();ebe=require("obsidian");eye();bor();_or();LZ=class{constructor(e){this.retrievedDocuments=[];this.app=e,this.memoryManager=jZ.getInstance(),this.chatModelManager=h1.getInstance(),this.promptManager=DZ.getInstance(),this.initialize(),wa(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 ebe.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!Iet(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",ey()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=ey(),o=wu();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:Dee();if(!i)throw new ebe.Notice("No model key found"),new Error("No model key found");try{if(r){let a=vee(i,oe().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Av[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=oe().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new ebe.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),B(`Setting model to ${i}`)}catch(a){ie(`createChainWithNewModel failed: ${a}`),B(`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=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=oe(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(cG(),$de))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(r7(),tye))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=c8.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:Mf()},this.storeRetrieverDocuments.bind(this),oe().debug),Dj("vault_qa"),oe().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=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=c8.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Dj("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=ey(),r=oe();switch(e){case"llm_chain":return new uG(this);case"vault_qa":return new n7(this);case"copilot_plus":return r.enableAutonomousAgent?new IZ(this):new LO(this);case"project"
`,e),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(s||l8(u)){let c=Em.fromMessages([new Pv("history"),Tv.fromTemplate("{input}")]);l8(u)&&(c=Em.fromMessages([[Fo,Mf()||""],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===Fo&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}}});var tbe,wor=b(()=>{ua();Gt();bt();ir();oG();tbe=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){wtt({success:[],failed:[],processingFiles:[],total:[]})}async executeWithProcessTracking(e,r,n){this.setFileOrUrlStartProcess(e);try{let o=await n();return this.setFileOrUrlProcessSuccessful(e),o}catch(o){let i=UP(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":eo(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){Ki.set(y8,r=>{let n={...r};return n.failed.find(o=>o.path===e)&&(n.failed=n.failed.filter(o=>o.path!==e)),n.success.includes(e)&&(n.success=n.success.filter(o=>o!==e)),n.processingFiles.includes(e)||(n.processingFiles=[...n.processingFiles,e]),n.total.includes(e)||(n.total=[...n.total,e]),n})}setFileOrUrlProcessSuccessful(e){Nv("processingFiles",r=>r.filter(n=>n!==e)),Nv("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){Nv("processingFiles",o=>o.filter(i=>i!==e)),Nv("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}preComputeAllItems(e,r){B(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);let n=[];n.push(...r.map(a=>a.path));let o=e.contextSource?.webUrls?.trim()||"";if(o){let a=o.split(`
2025-08-30 08:29:39 +08:00
`).filter(s=>s.trim());n.push(...a)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
2025-09-01 12:32:47 +08:00
`).filter(s=>s.trim());n.push(...a)}if(n.length>0){let a=[...new Set([...n])];Nv("total",s=>a),B(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){B(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
2025-08-30 08:29:39 +08:00
`).filter(u=>u.trim()).filter(u=>r.webContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
2025-09-01 12:32:47 +08:00
`).filter(u=>u.trim()).filter(u=>r.youtubeContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached YouTube URLs as successful`)}if(r.fileContexts){let a=new Set(n.filter(u=>u.extension==="md").map(u=>u.path)),s=Object.keys(r.fileContexts).filter(u=>a.has(u));s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){Nv("total",r=>r.includes(e)?r:[...r,e]),Nv("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){Nv("total",o=>o.includes(e)?o:[...o,e]),Nv("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}}});var Qk,Vd,mR=b(()=>{ua();nG();vu();or();Gt();Mde();rh();bt();Lde();ir();oG();Qk=require("obsidian");My();vor();wor();Vd=class t{constructor(e,r){this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new LZ(e),this.projectContextCache=b_.getInstance(),this.fileParserManager=new pR(Ji.getInstance(),this.app.vault,!0,null),this.loadTracker=tbe.getInstance(this.app),htt(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),gtt(async()=>{if(Fj())return;let n=oe(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(ey()==="vault_qa"||ey()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),cz(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){wa(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){return t.instance||(t.instance=new t(e,r)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}async switchProject(e){try{if(this.loadTracker.clearAllLoadStates(),TE(!0),B("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 pR(Ji.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),B(`Switched to project: ${e.name}`)}catch(r){throw ie(`Failed to switch project: ${r}`),r}finally{TE(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e){this.loadTracker.clearAllLoadStates(),TE(!0);try{if(!e.contextSource)return Bt(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;B(`[loadProjectContext] Starting for project: ${e.name}`),B(`[loadProjectContext] Project ${e.name}: Cleared all project context load states`);let r=await this.projectContextCache.getOrInitializeCache(e),n=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,n),this.loadTracker.markAllCachedItemsAsSuccess(e,r,n);let[o]=await Promise.all([this.processMarkdownFiles(e,r,n),this.processWebUrls(e,r),this.processYoutubeUrls(e,r)]);return o.timestamp=Date.now(),await this.projectContextCache.setCacheSafely(e,o),await this.processNonMarkdownFiles(e,n),B(`[loadProjectContext] Completed for project: ${e.name}.`),o}catch(r){throw ie(`[loadProjectContext] Failed for project ${e.name}:`,r),r}}async compareAndUpdateCache(e,r){try{if(!await this.projectContextCache.get(e))return!0;let o=e.contextSource?.inclusions||"",i=r.contextSource?.inclusions||"",a=e.contextSource?.exclus
2025-08-30 08:29:39 +08:00
`).filter(h=>h.trim()),p=l.split(`
`).filter(h=>h.trim());await this.projectContextCache.removeWebUrls(r,f.filter(h=>!p.includes(h)))}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(h=>h.trim()),p=d.split(`
2025-09-01 12:32:47 +08:00
`).filter(h=>h.trim());await this.projectContextCache.removeYoutubeUrls(r,f.filter(h=>!p.includes(h)))}}catch(n){ie(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Ns)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=oe().projectList.find(o=>o.id===e);if(!r)return Bt(`[getProjectContext] Project not found for ID: ${e}`),null;B(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?B(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):B(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r);if(!o)return ie(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else B(`[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(`
2025-08-30 08:29:39 +08:00
`)}`),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.getOrReuseFileContext(r,s)||"[Content not available]";return`[[${c}]]
2025-07-05 20:48:33 +08:00
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-30 08:29:39 +08:00
`}async processMarkdownFiles(e,r,n){if(B(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){B(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let o=await this.processMarkdownFileContext(n);this.projectContextCache.updateProjectMarkdownFilesFromPatterns(e,r,n),r.markdownContext=o,r.markdownNeedsReload=!1,B(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else B(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return B(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(r.fileContexts||{}).length}`),r}async processMarkdownFileContext(e){let r=e.filter(o=>o.extension==="md");B(`Found ${r.length} markdown files to process for project context`);let n=await Promise.all(r.map(async o=>{let i="",a="";try{let[s,u]=await this.loadTracker.executeWithProcessTracking(o.path,"md",async()=>Promise.all([this.app.vault.adapter.stat(o.path),this.app.vault.read(o)]));a=`[[${o.basename}]]
path: ${o.path}
type: ${o.extension}
created: ${s?new Date(s.ctime).toISOString():"unknown"}
2025-09-01 12:32:47 +08:00
modified: ${s?new Date(s.mtime).toISOString():"unknown"}`,i=u,B(`Completed processing markdown file: ${o.path}`)}catch(s){ie(`Error processing file ${o.path}: ${s}`),i=`[Error: ${eo(s)}]`}return`${a}
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${i}`}));return B("All markdown files processed for project context"),n.join(`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
`)}async processWebUrls(e,r){B(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(B(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
2025-09-01 12:32:47 +08:00
`).filter(c=>c.trim());B(`[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&&B(`[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){B(`[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.processWebUrlContext(c);return d&&B(`[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&&Bt(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),B(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){B(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(B(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());B(`[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&&B(`[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){B(`[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.processYoutubeUrlContext(c);return d&&B(`[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&&Bt(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),B(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlContext(e){if(!e?.trim())return"";try{let r=fR.getInstance(),{urlContext:n}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await r.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return n||""}catch(r){return ie(`Failed to process web URL: ${r}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let r=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>Ji.getInstance().youtube4llm(e));return r.response.transcript?`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
YouTube transcript from ${e}:
2025-09-01 12:32:47 +08:00
${r.response.transcript}`:""}catch(r){return ie(`Failed to process YouTube URL ${e}: ${r}`),new Qk.Notice(`Failed to process YouTube URL ${e}: ${eo(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(B(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new pR(Ji.getInstance(),this.app.vault,!0,e);let o=0;for(let i of n){let a=i.path;if(this.fileParserManager.supportsExtension(i.extension))try{await this.loadTracker.executeWithProcessTracking(a,"nonMd",async()=>{await this.projectContextCache.getOrReuseFileContext(e,a)||(B(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${a}`),await this.fileParserManager.parseFile(i,this.app.vault)),o++})}catch(s){if(ie(`[loadProjectContext] Project ${e.name}: Error parsing file ${a}:`,s),UP(s))throw s}}o>0&&B(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){Bt("[retryFailedItem] No current project, aborting retry");return}let r=oe().projectList.find(n=>n.id===this.currentProjectId);if(!r){ie(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(B(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":await this.retryWebUrl(r,e.path);break;case"youtube":await this.retryYoutubeUrl(r,e.path);break;case"md":await this.retryMarkdownFile(r,e.path);break;case"nonMd":await this.retryNonMarkdownFile(r,e.path);break;default:Bt(`[retryFailedItem] Unknown item type: ${e.type}`);return}B(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new Qk.Notice(`Retry successful: ${e.path}`)}catch(r){ie(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new Qk.Notice(`Retry failed: ${eo(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){Bt(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}B(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateWebUrl(e,r,n)}async retryYoutubeUrl(e,r){let n=await this.processYoutubeUrlContext(r);if(!n){Bt(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}B(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateYoutubeUrl(e,r,n)}async retryMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof Qk.TFile)||n.extension!=="md")throw new Error(`File not found or not a markdown file: ${r}`);try{await this.loadTracker.executeWithProcessTracking(n.path,"md",async()=>{}),B(`[retryMarkdownFile] Successfully reprocessed markdown file: ${r}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw ie(`[retryMarkdownFile] Error processing file ${r}: ${o}`),o}}async retryNonMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof Qk.TFile)||n.extension==="md")throw new Error(`File not found or is a markdown file: ${r}`);if(!this.fileParserManager.supportsExtension(n.extension))throw new Error(`Unsupported file extension: ${n.extension}`);try{await this.loadTracker.executeWithProcessTracking(r,"nonMd",async()=>this.fileParserManager.parseFile(n,this.app.vault)),B(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${r}`)}catch(o){throw ie(`[retryNonMarkdownFile] Error processing file ${r}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:r,exclusions:n}=vc({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>_s(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}}});var xor={};os(xor,{AutocompleteCache:()=>FZ});var FZ,G6e=b(()=>{Gt();FZ=class t{constructor(){this.cache=new Map,this.maxSize=200,this.ttlMs=10*60*1e3}static getInstance(){return t.instance||(t.instance=new t),t.instance}get(e){let r=this.cache.get(e)
2025-07-05 20:48:33 +08:00
`)&&a.startsWith(`
2025-09-01 12:32:47 +08:00
`)&&(a=a.substring(1)),a}},r8e=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}},obe=class{constructor(){this.processors=[];this.processors.push(new r8e),this.processors.push(new e8e),this.processors.push(new t8e)}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}};d8();var Eor=require("obsidian");function Por(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 Tor(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 Eor.TFile&&(r.push(i),r.length>=e))break}return r}Ede();bt();var n8e=require("obsidian"),pqn=.4,mqn=20,Aor=.7,ibe=.3;async function hqn(t,e){let r=oe().debug,n=await BP.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 gqn(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);for(let n of t)for(let o=0;o<e;o++)r[o]+=n[o];for(let n=0;n<e;n++)r[n]/=t.length;return r}function yqn(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 bqn({db:t,filePath:e}){let r=oe().debug,n=await hqn(e,t),o=gqn(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await BP.getDocsByEmbedding(t,o,{limit:mqn,similarity:pqn});return yqn(i,e)}function _qn(t){let e=new Map,n=Por(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=Tor(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 vqn(t,e){let r=new Map,n=Aor+ibe;for(let[o,i]of t)r.set(o,i*Aor/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=ibe:(i.links||i.backlinks)&&(a=ibe*.8),r.set(o,(r.get(o)??0)+a)}return r}async function sbe({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof n8e.TFile))return[];let n=await bqn({db:t,filePath:e}),o=_qn(r),i=vqn(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=abe(n.get(l)??0),f=abe(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 n8e.TFile)||l.extension!=="md"?null:{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}}}).filter(s=>s!==null)}function abe(t){return t>.7?3:t>.55?2:1}var Ior=require("obsidian"),wqn={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 xqn(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function Mor(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(wqn).some(n=>xqn(r,n)))return!0;return!1}function Ror(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-09-01 12:32:47 +08:00
`;return{prefix:r,noteContext:n}}var $1=class $1{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return $1.instance||($1.instance=new $1),$1.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=[];try{let a=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().getDb();a&&(r=await sbe({db:a,filePath:e.path}))}catch(i){console.warn("Failed to fetch relevant notes for autocomplete:",i)}let n=r.slice(0,$1.MAX_RELEVANT_NOTES);this.cachedNoteTitles=n.map(i=>i.document.title);let o=await Promise.all(n.map(async i=>{let a=app.vault.getAbstractFileByPath(i.document.path);if(!(a instanceof Ior.TFile))return"";let s=await app.vault.cachedRead(a);if(!s)return"";let u=s.length>3e3?s.slice(0,3e3)+"...":s;return`[[${i.document.title}]]:
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${u}`}));return this.currentNotePath=e.path,this.cachedNotes=o.join(`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};$1.MAX_RELEVANT_NOTES=3;var ube=$1;var e$=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 kZ=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-09-01 12:32:47 +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 Mor(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(o8e.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=Ror(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=oe();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(g=>g.word===c),h=f.some(g=>g.word.length-c.length>=2);if(p&&!h)return;let m=p?f.filter(g=>g.word!==c):f;if(m.length===0)return;try{let g=m.map(P=>P.word),y=o.slice(-1e3),_=a.slice(0,500),w,S,C;if(this.cacheEnabled&&(S=this.cache.generateWordKey(y,_,g),C=this.cache.get(S)),C)w=C;else{let P=this.client.wordcomplete(y,_,g);this.activeRequests.set(d,P),this.lastRequestTime=s,w=await P,this.cacheEnabled&&S&&this.cache.set(S,w),this.activeRequests.delete(d)}let E=w.response.selected_word;if(E&&E!==c){let P=this.generateCaseMatchedCompletion(E,c);P&&(yield{display_suggestion:P,complete_suggestion:P})}}catch(g){this.activeRequests.delete(d),ie("[Copilot Autocomplete] Error with LLM word selection, falling back to trie:",g);let y=m[0],_=this.generateCaseMatchedCompletion(y.word,c);_&&(yield{display_suggestion:_,complete_suggestion:_})}}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 ube.getInstance().getRelevantNotes(e.file));let h=e.file?.basename||"",m=h?`[[${h}]]:
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${c}`:c,g,y,_;if(this.cacheEnabled&&(y=this.cache.generateSentenceKey(m,i,p),_=this.cache.get(y)),_)g=_;else{let C=this.client.autocomplete(m,i,p);this.activeRequests.set(d,C),this.lastRequestTime=s,g=await C,this.cacheEnabled&&y&&this.cache.set(y,g),this.activeRequests.delete(d)}let w=g.response.completion,S=this.detectContext(o);w=this.postProcessor.process(c,a,w,S),yield{display_suggestion:w,complete_suggestion:w}}catch(f){this.activeRequests.delete(d),ie("[Copilot Autocomplete] Error fetching autocomplete suggestions:",f)}}}shouldUseWordCompletion(e,r){if(!r.enableWordCompletion||e.endsWith("[[")||/\[\[[^\]]*$/.test(e))return!1;let o=e.trim(),i=o[o.length-1];if(i&&/[a-zA-Z']/.test(i)){let a=this.getCurrentWordFromPrefix(e);if(a&&a.length>=2){let s=this.wordCompletionManager.getSuggestions(a);if(s.length===0)return!1;let u=s.some(c=>c.word===a),l=s.some(c=>c.word.length-a.length>=2);return!(u&&!l)}}return!1}getCurrentWordFromPrefix(e){let r=e.length;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!/[a-zA-Z']/.test(i)){r=o+1;break}o===0&&(r=0)}let n=e.substring(r);return n.length>=2?n:null}generateCaseMatchedCompletion(e,r){if(e.length<=r.length)return"";let n=e.substring(r.length),o=r===r.toUpperCase(),i=r===r.toLowerCase(),a=r.length>0&&r[0]===r[0].toUpperCase()&&r.slice(1)===r.slice(1).toLowerCase();return o?n.toUpperCase():i||a?n.toLowerCase():n}detectContext(e){let r=e.split(`
2025-09-01 12:32:47 +08:00
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var cbe=class t{constructor(e){this.plugin=e;let r=oe();this.cmIntegration=lbe.getInstance({delay:Yg.DELAY_MS,minTriggerLength:Yg.MIN_TRIGGER_LENGTH,maxContextLength:Yg.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=wa((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){ie("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};or();ir();zN();function jor(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:dm(),sender:n===Fo?Fo:Zg,message:o.trim(),isVisible:!0,timestamp:i?GSe(i):null}),n=a.startsWith("**user**:")?Fo:Zg,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:dm(),sender:n===Fo?Fo:Zg,message:o.trim(),isVisible:!0,timestamp:i?GSe(i):null}),r}async function Dor(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Fo){let o=t[r+1];o?.sender===Zg&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}ua();cze();nG();vu();Gt();var fir=require("obsidian");po();var dbe=j(Y());xn();var gi=dbe.forwardRef(({className:t,type:e,...r},n)=>dbe.createElement("input",{type:e,className:me("!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}));gi.displayName="Input";var fbe=j(Y());var zor=j(Y(),1);var For=j(Y(),1),kor=j(za(),1);var rf=j(Y(),1);var Lor=j(Y(),1);function Cqn(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function r$(...t){return e=>t.forEach(r=>Cqn(r,e))}function Vs(...t){return Lor.useCallback(r$(...t),t)}var $H=j(st(),1),a8e=rf.forwardRef((t,e)=>{let{children:r,...n}=t,o=rf.Children.toArray(r),i=o.find(Eqn);if(i){let a=i.props.children,s=o.map(u=>u===i?rf.Children.count(a)>1?rf.Children.only(null):rf.isValidElement(a)?a.props.children:null:u);return(0,$H.jsx)(i8e,{...n,ref:e,children:rf.isValidElement(a)?rf.cloneElement(a,void 0,s):null})}return(0,$H.jsx)(i8e,{...n,ref:e,children:r})});a8e.displayName="Slot";var i8e=rf.forwardRef((t,e)=>{let{children:r,...n}=t;if(rf.isValidElement(r)){let o=Tqn(r);return rf.cloneElement(r,{...Pqn(n,r.props),ref:e?r$(e,o):o})}return rf.Children.count(r)>1?rf.Children.only(null):null});i8e.displayName="SlotClone";var Oqn=({children:t})=>(0,$H.jsx)($H.Fragment,{children:t});function Eqn(t){return rf.isValidElement(t)&&t.type===Oqn}function Pqn(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 Tqn(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 $or=j(st(),1),Aqn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],qi=Aqn.reduce((t,e)=>{let r=For.forwardRef((n,o)=>{let{asChild:i,...a}=n,s=i?a8e:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,$or.jsx)(s,{...a,ref:o})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function Bor(t,e){t&&kor.flushSync(()=>t.dispatchEvent(e))}var Uor=j(st(),1),Iqn="Label",qor=zor.forwardRef((t,e)=>(0,Uor.jsx)(qi.label,{...t,ref:e,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(t.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));qor.displayName=Iqn;var s8e=qor;ire();xn();var Rqn=zz("tw-text-sm tw-font-medium tw-leading-none peer-disabled:tw-cursor-not-allowed peer-disabled:tw-opacity-70"),em=fbe.forwardRef(({className:t,...e},r)=>fbe.createElement(s8e,{ref:r,className:me(Rqn(),t),...e}));em.displayName=s8e.displayName;var UH=j(Y());var Og=j(Y(),1);var Vor=j(Y(),1);function Hor(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function u8e(...t){return e=>{let r=!1,n=t.map(o=>{let i=Hor(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():Hor(t[o],null)}}}}function Wor(...t){return Vor.useCallback(u8e(...t),t)}var ub=j(Y(),1),l8e=j(st(),1);function Kor(t,e){let r=ub.createContext(e),n=i=>{let{children:a,...s}=i,u=ub.useMemo(()=>s,Object.values(s));return(0,l8e.jsx)(r.Provider,{value:u,children:a})};n.displayName=t+"Provider";function o(i){let a=ub.useContext(r);if(a)return a
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-09-01 12:32:47 +08:00
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];var VH=require("obsidian");bt();o8();o8();var n$=WB(),o$=Rh([]),_8e=new Set;function i$(t){_8e.add(t)}function a$(t){_8e.delete(t)}function BZ(t){return _8e.has(t)}function zZ(t){let e=n$.get(o$);n$.set(o$,e.filter(r=>r.title!==t))}function s$(t,e){let r=n$.get(o$),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],n$.set(o$,n)}function ybe(t){n$.set(o$,t)}function lir(){return n8(o$,{store:n$})}function up(){return n$.get(o$)}d8();ir();or();function bbe(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 WH(t){return encodeURIComponent(t.toLowerCase())}function H1(){return(0,VH.normalizePath)(oe().customPromptsFolder)}function KH(t){return`${H1()}/${t}.md`}function GH(t){if(!(t instanceof VH.TFile)||t.extension!=="md")return!1;let e=H1();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function Zqn(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}function cir(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[zO]!=null}async function UZ(t){let e=await app.vault.read(t),r=Zqn(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[tA]??BO.showInContextMenu,i=n?.frontmatter?.[rA]??BO.showInSlashMenu,a=n?.frontmatter?.[oA]??BO.lastUsedMs,s=n?.frontmatter?.[zO]??BO.order,u=n?.frontmatter?.[nA]??BO.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function _be(){let t=app.vault.getFiles().filter(r=>GH(r)),e=await Promise.all(t.map(UZ));return ybe(e),e}function qZ(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function Yqn(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function Xqn(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function vbe(t){switch(oe().promptSortStrategy){case"timestamp":return Yqn(t);case"alphabetical":return Xqn(t);case"manual":return qZ(t);default:return t}}async function v8e(t,e,r=!1){let o=(await w8e(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${Tm}}`)||r)return o;let i=o.indexOf(b8e);return i===-1&&e.trim()?o+`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
<`+Tm+">"+e+"</"+Tm+">":o.slice(0,i)+e+o.slice(i+b8e.length)}var Qqn=/\{(?!copilot-selection\})([^}]+)\}/g;async function e2n(t,e,r){let n=new Map,o=new Set,i;for(;(i=Qqn.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await YB(r,e);u&&(s.content=`<${Ij}>
## ${bee(r)}
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${u}
2025-09-01 12:32:47 +08:00
</${Ij}>`,s.files.push(r))}else new VH.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await Aet(e,u),c=[];for(let d of l){let f=await YB(d,e);f&&(c.push(`<${Ij}>
## ${bee(d)}
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${f}
2025-09-01 12:32:47 +08:00
</${Ij}>`),s.files.push(d))}s.content=c.join(`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
`)}else{let u=Ret(a),l=await KSe(e,u),c=[];for(let d of l){let f=await YB(d,e);f&&(c.push(`<${Ij}>
## ${bee(d)}
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
${f}
2025-09-01 12:32:47 +08:00
</${Ij}>`),s.files.push(d))}s.content=c.join(`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +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 w8e(t,e,r,n){let o=oe(),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-09-01 12:32:47 +08:00
`,includedFiles:Array.from(i)};let{variablesMap:a,includedFiles:s}=await e2n(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,`{${Tm}}`),e?l+=`<${Tm}>
2025-08-30 08:29:39 +08:00
${e}
2025-09-01 12:32:47 +08:00
</${Tm}>`:n?(c=await YB(n,r),l+=`<${Tm} type="active_note">
2025-08-30 08:29:39 +08:00
${c||""}
2025-09-01 12:32:47 +08:00
</${Tm}>`,i.add(n)):l+=`<${Tm}>
2025-08-30 08:29:39 +08:00
(No selected text or active note available)
2025-09-01 12:32:47 +08:00
</${Tm}>`);for(let[f,p]of a.entries())f.toLowerCase()==="activenote"&&c!==null||(l?l+=`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
<${p8} name="${f}">
2025-07-05 20:48:33 +08:00
${p}
2025-09-01 12:32:47 +08:00
</${p8}>`:l+=`<${p8} name="${f}">
2025-08-30 08:29:39 +08:00
${p}
2025-09-01 12:32:47 +08:00
</${p8}>`);let d=Jg(u,r);for(let f of d)if(!i.has(f)){let p=await YB(f,r);if(p){let h=await r.adapter.stat(f.path),m=h?new Date(h.ctime).toISOString():"Unknown",g=h?new Date(h.mtime).toISOString():"Unknown",y=`<${f8}>
2025-08-30 08:29:39 +08:00
<title>${f.basename}</title>
<path>${f.path}</path>
<ctime>${m}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
2025-09-01 12:32:47 +08:00
</${f8}>`;l&&(l+=`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
`),l+=`${y}`,i.add(f)}}return{processedPrompt:l?`${u}
2025-07-05 20:48:33 +08:00
${l}`:`${u}
2025-09-01 12:32:47 +08:00
`,includedFiles:Array.from(i)}}function dir(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 wbe(){let e=up().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function x8e(t,e){try{i$(t.path),await app.fileManager.processFrontMatter(t,r=>{r[tA]==null&&(r[tA]=e.showInContextMenu),r[rA]==null&&(r[rA]=e.showInSlashMenu),r[zO]==null&&(r[zO]=e.order),r[nA]==null&&(r[nA]=e.modelKey),r[oA]==null&&(r[oA]=e.lastUsedMs)})}finally{a$(t.path)}}function xbe(t){let e=t.getCursor("from"),r=t.getCursor("to"),o=t.getValue().split(`
`),i=!1,a=[],s=0,u=0,l=0;for(;l<o.length;)if(o[l].trim()===`\`\`\`${HH}`){i=!0;let c=l;for(l++;l<o.length&&o[l].trim()!=="```";)l++;l++;let d=l-c;c<=e.line&&(s+=d),c<=r.line&&(u+=d)}else a.push(o[l]),l++;if(i){t.setValue(a.join(`
`));let c=Math.max(0,e.line-s),d=Math.max(0,r.line-u);t.setSelection({line:c,ch:e.ch},{line:d,ch:r.ch})}return i}function t2n({commands:t,command:e,onConfirm:r,onCancel:n}){let i=vn().activeModels.filter(f=>f.enabled).map(f=>({label:gbe(f),value:tn(f)})),[a,s]=(0,yi.useState)(e),[u,l]=(0,yi.useState)({}),c=(f,p)=>{s(h=>({...h,[f]:p})),l(h=>({...h,[f]:void 0}))},d=()=>{let f={},p=bbe(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 yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement(em,{htmlFor:"title"},"Name"),yi.default.createElement(gi,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&yi.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement(em,{htmlFor:"content"},"Prompt"),yi.default.createElement(sir,null),yi.default.createElement(J_,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&yi.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement(em,{htmlFor:"modelKey"},"Model (Optional)"),yi.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},yi.default.createElement("select",{value:a.modelKey,onChange:f=>{let p=f.target.value;if(!p){c("modelKey","");return}if(!i.find(m=>m.value===p)){ie(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:me("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")},yi.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>yi.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),yi.default.createElement("div",{className:me("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")},yi.default.createElement(ki,{className:"tw-size-4"})))),yi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},yi.default.createElement(Ec,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),yi.default.createElement(em,{htmlFor:"showInContextMenu"},"Show in context menu")),yi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},yi.default.createElement(Ec,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),yi.default.createElement(em,{htmlFor:"showInSlashMenu"},"Show in slash menu")),yi.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},yi.default.createElement(he,{variant:"secondary",onClick:n},"Cancel"),yi.default.createElement(he,{variant:"default",onClick:d},"Save")))}var u$=class extends fir.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,pir.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this.root.render(yi.default.createElement(t2n,{commands:this.commands,command:this.command,onConfirm:n,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};var HZ=require("obsidian");xE();var Pc=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,r={}){let n={skipStoreUpdate:!1,autoOrder:!0,...r},o=KH(e.title);try{i$(o);let i=e.order;n.autoOrder&&(i=wbe()),e={...e,order:i};let a=H1();await app.vault.adapte
2025-08-30 08:29:39 +08:00
\`\`\`
2025-09-01 12:32:47 +08:00
`;return i.replaceRange(l,{line:u,ch:0}),!0}),gh(t,pn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().clearIndex(),new Qi.Notice("Cleared local Copilot semantic index.")}catch(n){ie("Error clearing semantic index:",n),new Qi.Notice("Failed to clear semantic index.")}}),gh(t,pn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let o=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().garbageCollectVectorStore();new Qi.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ie("Error during garbage collection:",n),new Qi.Notice("Failed to garbage collect semantic index.")}}),gh(t,pn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(bt(),i8));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore(!1);new Qi.Notice(`Semantic search index refreshed with ${a} documents.`)}else new Qi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ie("Error building index:",n),new Qi.Notice("An error occurred while building the index.")}}),gh(t,pn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(bt(),i8));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore(!0);new Qi.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new Qi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ie("Error rebuilding index:",n),new Qi.Notice("An error occurred while rebuilding the index.")}}),gh(t,pn.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),gh(t,pn.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=await Promise.resolve().then(()=>(rh(),P3t)),{inclusions:s,exclusions:u}=i(),l=t.app.vault.getMarkdownFiles(),c=new Set,d=new Set,f=new Set,p=new Set(o);for(let w of l){if(!a(w,s,u)){f.add(w.path);continue}let S=await t.app.vault.cachedRead(w);!S||S.trim().length===0?c.add(w.path):p.has(w.path)||d.add(w.path)}let h=["# Copilot Files Status",`- Indexed files: ${p.size}`,`- Unindexed files: ${d.size}`,`- Empty files: ${c.size}`,`- Excluded files: ${f.size}`,"","## Indexed Files",...p.size>0?Array.from(p).sort().map(w=>`- [[${w}]]`):["No indexed files found."],"","## Unindexed Files",...d.size>0?Array.from(d).sort().map(w=>`- [[${w}]]`):["No unindexed files found."],"","## Empty Files",...c.size>0?Array.from(c).sort().map(w=>`- [[${w}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...f.size>0?Array.from(f).sort().map(w=>`- [[${w}]]`):["No excluded files."]].join(`
`),g=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,y=t.app.vault.getAbstractFileByPath(g);y?await t.app.vault.modify(y,h):await t.app.vault.create(g,h);let _=t.app.vault.getAbstractFileByPath(g);_&&(await t.app.workspace.getLeaf().openFile(_),new Qi.Notice(`Listed ${p.size} indexed files`))}catch(n){ie("Error listing indexed files:",n),new Qi.Notice("Failed to list indexed files.")}}),gh(t,pn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await b_.getInstance().clearAllCache(),await p4.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(G6e(),xor));o.getInstance().clear(),new Qi.Notice("All Copilot caches cleared successfully")}catch(n){ie("Error clearing Copilot caches:",n),new Qi.Notice("Failed to clear Copilot caches")}}),gh(t,pn.TOGGLE_AUTOCOMPLETE,()=>{let o=!oe().enableAutocomplete;nt("enableAutocomplete",o),new Qi.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),hir(t,pn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=ey();if(o!=="copilot_plus"&&o!=="project"){new Qi.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new Qi.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new Qi.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new Qi.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:dm(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};ytt(c),t.activateView()}),gh(t,pn.ADD_CUSTOM_COMMAND,async()=>{let n=up(),o={...BO};new u$(t.app,n,o,async a=>{await Pc.getInstance().createCommand(a)}).open()}),gh(t,pn.APPLY_CUSTOM_COMMAND,()=>{new Sbe(t.app).open()})}ua();vu();vu();ua();function Obe(){let[t]=Rp(),[e]=Lee(),[r]=Fee();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:a,processingFiles:s}=r;return e||s.length>0?"loading":a.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}Gt();ua();nG();vu();po();var gir=require("obsidian"),l$=j(Y()),yir=j($c());function i2n({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return l$.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},l$.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),l$.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&l$.default.createElement(he,{variant:"secondary",onClick:r},o),n&&l$.default.createElement(he,{variant:"default",onClick:e},n)))}var Tc=class extends gir.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,yir.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(l$.default.createElement(i2n,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};po();var sa=j(Y());var Ac=j(Y(),1);function VZ(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var a2n=j(Y(),1);function bir(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Ebe(...t){return e=>{let r=!1,n=t.map(o=>{let i=bir(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():bir(t[o],null)}}}}var _ir=j(Y(),1),d2n=j(za(),1);var af=j(Y(),1);var JH=j(st(),1),O8e=af.forwardRef((t,e)=>{let{children:r,...n}=t,o=af.Children.toArray(r),i=o.find(u2n);if(i){let a=i.props.children,s=o.map(u=>u===i?af.Children.count(a)>1?af.Children.only(null):af.isValidElement(a)?a.props.children:null:u);return(0,JH.jsx)(C8e,{...n,ref:e,children:af.isValidElement(a)?af.cloneElement(a,void 0,s):null})}return(0,JH.jsx)(C8e,{...n,ref:e,children:r})});O8e.displayName="Slot";var C8e=af.forwardRef((t,e)=>{let{children:r,...n}=t;if(af.isValidEl
.`.concat(e5e,` {
2025-07-05 20:48:33 +08:00
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
2025-09-01 12:32:47 +08:00
body[`).concat(iV,`] {
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-09-01 12:32:47 +08:00
.`).concat(ev,` {
2025-07-05 20:48:33 +08:00
right: `).concat(s,"px ").concat(n,`;
}
2025-09-01 12:32:47 +08:00
.`).concat(tv,` {
2025-07-05 20:48:33 +08:00
margin-right: `).concat(s,"px ").concat(n,`;
}
2025-09-01 12:32:47 +08:00
.`).concat(ev," .").concat(ev,` {
2025-07-05 20:48:33 +08:00
right: 0 `).concat(n,`;
}
2025-09-01 12:32:47 +08:00
.`).concat(tv," .").concat(tv,` {
2025-07-05 20:48:33 +08:00
margin-right: 0 `).concat(n,`;
}
2025-09-01 12:32:47 +08:00
body[`).concat(iV,`] {
`).concat(t5e,": ").concat(s,`px;
2025-07-05 20:48:33 +08:00
}
2025-09-01 12:32:47 +08:00
`)},lsr=function(){var t=parseInt(document.body.getAttribute(iV)||"0",10);return isFinite(t)?t:0},U4n=function(){aV.useEffect(function(){return document.body.setAttribute(iV,(lsr()+1).toString()),function(){var t=lsr()-1;t<=0?document.body.removeAttribute(iV):document.body.setAttribute(iV,t.toString())}},[])},v$=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;U4n();var i=aV.useMemo(function(){return a5e(o)},[o]);return aV.createElement(B4n,{styles:z4n(i,!e,o,r?"":"!important")})};var s5e=!1;if(typeof window<"u")try{eY=Object.defineProperty({},"passive",{get:function(){return s5e=!0,!0}}),window.addEventListener("test",eY,eY),window.removeEventListener("test",eY,eY)}catch{s5e=!1}var eY,w$=s5e?{passive:!1}:!1;var q4n=function(t){return t.tagName==="TEXTAREA"},csr=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!q4n(t)&&r[e]==="visible")},H4n=function(t){return csr(t,"overflowY")},V4n=function(t){return csr(t,"overflowX")},u5e=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=dsr(t,n);if(o){var i=fsr(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},W4n=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},K4n=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},dsr=function(t,e){return t==="v"?H4n(e):V4n(e)},fsr=function(t,e){return t==="v"?W4n(e):K4n(e)},G4n=function(t,e){return t==="h"&&e==="rtl"?-1:1},psr=function(t,e,r,n,o){var i=G4n(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=fsr(t,s),h=p[0],m=p[1],g=p[2],y=m-g-i*h;(h||y)&&dsr(t,s)&&(d+=y,f+=h),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 Ybe=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},msr=function(t){return[t.deltaX,t.deltaY]},hsr=function(t){return t&&"current"in t?t.current:t},J4n=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Z4n=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-09-01 12:32:47 +08:00
`)},Y4n=0,sV=[];function gsr(t){var e=ja.useRef([]),r=ja.useRef([0,0]),n=ja.useRef(),o=ja.useState(Y4n++)[0],i=ja.useState(uA)[0],a=ja.useRef(t);ja.useEffect(function(){a.current=t},[t]),ja.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var m=oV([t.lockRef.current],(t.shards||[]).map(hsr),!0).filter(Boolean);return m.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ja.useCallback(function(m,g){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var y=Ybe(m),_=r.current,w="deltaX"in m?m.deltaX:_[0]-y[0],S="deltaY"in m?m.deltaY:_[1]-y[1],C,E=m.target,P=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&P==="h"&&E.type==="range")return!1;var T=u5e(P,E);if(!T)return!0;if(T?C=P:(C=P==="v"?"h":"v",T=u5e(P,E)),!T)return!1;if(!n.current&&"changedTouches"in m&&(w||S)&&(n.current=C),!C)return!0;var I=n.current||C;return psr(I,g,m,I==="h"?w:S,!0)},[]),u=ja.useCallback(function(m){var g=m;if(!(!sV.length||sV[sV.length-1]!==i)){var y="deltaY"in g?msr(g):Ybe(g),_=e.current.filter(function(C){return C.name===g.type&&(C.target===g.target||g.target===C.shadowParent)&&J4n(C.delta,y)})[0];if(_&&_.should){g.cancelable&&g.preventDefault();return}if(!_){var w=(a.current.shards||[]).map(hsr).filter(Boolean).filter(function(C){return C.contains(g.target)}),S=w.length>0?s(g,w[0]):!a.current.noIsolation;S&&g.cancelable&&g.preventDefault()}}},[]),l=ja.useCallback(function(m,g,y,_){var w={name:m,delta:g,target:y,should:_,shadowParent:X4n(y)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(S){return S!==w})},1)},[]),c=ja.useCallback(function(m){r.current=Ybe(m),n.current=void 0},[]),d=ja.useCallback(function(m){l(m.type,msr(m),m.target,s(m,t.lockRef.current))},[]),f=ja.useCallback(function(m){l(m.type,Ybe(m),m.target,s(m,t.lockRef.current))},[]);ja.useEffect(function(){return sV.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,w$),document.addEventListener("touchmove",u,w$),document.addEventListener("touchstart",c,w$),function(){sV=sV.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,w$),document.removeEventListener("touchmove",u,w$),document.removeEventListener("touchstart",c,w$)}},[]);var p=t.removeScrollBar,h=t.inert;return ja.createElement(ja.Fragment,null,h?ja.createElement(i,{styles:Z4n(o)}):null,p?ja.createElement(v$,{gapMode:t.gapMode}):null)}function X4n(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var ysr=_$(Zbe,gsr);var bsr=Xbe.forwardRef(function(t,e){return Xbe.createElement(QZ,Di({},t,{ref:e,sideCar:ysr}))});bsr.classNames=QZ.classNames;var l5e=bsr;var Yr=j(st(),1),c5e=["Enter"," "],Q4n=["ArrowDown","PageUp","Home"],vsr=["ArrowUp","PageDown","End"],e3n=[...Q4n,...vsr],t3n={ltr:[...c5e,"ArrowRight"],rtl:[...c5e,"ArrowLeft"]},r3n={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oY="Menu",[rY,n3n,o3n]=Cir(oY),[x$,d5e]=Qa(oY,[o3n,q8e,X8e]),iY=q8e(),wsr=X8e(),[xsr,cN]=x$(oY),[i3n,aY]=x$(oY),Ssr=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=iY(e),[u,l]=er.useState(null),c=er.useRef(!1),d=cn(i),f=YH(o);return er.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),(0,Yr.jsx)(V8e,{...s,children:(0,Yr.jsx)(xsr,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Yr.jsx)(i3n,{scope:e,onClose:er.useCallback(()=>d(!1),[d]),isUsingKeyboardRef
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
<${m8}>
2025-08-30 08:29:39 +08:00
<name>${s}</name>
<content>
2025-07-05 20:48:33 +08:00
${l}
2025-08-30 08:29:39 +08:00
</content>
2025-09-01 12:32:47 +08:00
</${m8}>
2025-07-05 20:48:33 +08:00
`)}catch(l){console.error(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
2025-09-01 12:32:47 +08:00
<${m8}>
2025-08-30 08:29:39 +08:00
<name>${s}</name>
<error>Could not process PDF</error>
2025-09-01 12:32:47 +08:00
</${m8}>
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
`)}}return e}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=f8)=>{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(!jh(s)&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new h_e.Notice(iz.NON_MARKDOWN_FILES_RESTRICTED);return}let p=await r.parseFile(d,n);d.extension==="md"&&jh(s)&&(p=await this.processEmbeddedPDFs(p,n,r));let h=await n.adapter.stat(d.path),m=h?new Date(h.ctime).toISOString():"Unknown",g=h?new Date(h.mtime).toISOString():"Unknown";u+=`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
<${f}>
<title>${d.basename}</title>
<path>${d.path}</path>
<ctime>${m}</ctime>
<mtime>${g}</mtime>
<content>
2025-07-05 20:48:33 +08:00
${p}
2025-08-30 08:29:39 +08:00
</content>
2025-07-05 20:48:33 +08:00
</${f}>`}catch(p){console.error(`Error processing file ${d.path}:`,p),u+=`
2025-08-30 08:29:39 +08:00
<${f}_error>
<title>${d.basename}</title>
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
2025-09-01 12:32:47 +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=kj();if(!e||e.length===0)return"";let r="";for(let n of e)r+=`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
<${Tm}>
2025-08-30 08:29:39 +08:00
<title>${n.noteTitle}</title>
<path>${n.notePath}</path>
<start_line>${n.startLine.toString()}</start_line>
<end_line>${n.endLine.toString()}</end_line>
<content>
2025-07-05 20:48:33 +08:00
${n.content}
2025-08-30 08:29:39 +08:00
</content>
2025-09-01 12:32:47 +08:00
</${Tm}>`;return r}};Hye();ir();bt();l7();ir();un();var iWe=require("obsidian"),Lt=j(Y());var zn=j(Y()),ea=j(Rlr());function pN(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 XHn=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","appli
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cVn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function dVn(t){if(Array.isArray(t))return G5e(t)}function Blr(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 zlr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Blr(Object(r),!0).forEach(function(n){Hlr(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Blr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Hlr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mY(t,e){return mVn(t)||pVn(t,e)||Vlr(t,e)||fVn()}function fVn(){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 Vlr(t,e){if(t){if(typeof t=="string")return G5e(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 G5e(t,e)}}function G5e(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 pVn(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 mVn(t){if(Array.isArray(t))return t}var hVn=typeof y_e.default=="function"?y_e.default:y_e.default.default,gVn="file-invalid-type",yVn="file-too-large",bVn="file-too-small",_Vn="too-many-files";var vVn=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:gVn,message:"File type must be ".concat(n)}},Ulr=function(e){return{code:yVn,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},qlr=function(e){return{code:bVn,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},Wlr={code:_Vn,message:"Too many files"};function J5e(t,e){var r=t.type==="application/x-moz-file"||hVn(t,e);return[r,r?null:vVn(e)]}function Z5e(t,e,r){if(O$(t.size))if(O$(e)&&O$(r)){if(t.size>r)return[!1,Ulr(r)];if(t.size<e)return[!1,qlr(e)]}else{if(O$(e)&&t.size<e)return[!1,qlr(e)];if(O$(r)&&t.size>r)return[!1,Ulr(r)]}return[!0,null]}function O$(t){return t!=null}function Klr(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=J5e(u,r),c=mY(l,1),d=c[0],f=Z5e(u,n,o),p=mY(f,1),h=p[0],m=s?s(u):null;return d&&h&&!m})}function hY(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function gY(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 Y5e(t){t.preventDefault()}function wVn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function xVn(t){return t.indexOf("Edge/")!==-1}function Glr(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return wVn(t)||xVn(t)}function ov(){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!hY(n)&&s&&s.apply(void 0,[n].concat(i)),hY(n)})}}function Jlr(){return"showOpenFilePicker"in window}function Zlr(t){if(O$(t)){var e=Object.entries(t).filter(function(r){var n=mY(r,2),o=n[0],i=n[1],a=!0;return ecr(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(tcr))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=mY(n,2),i=o[0],a=o[1];return zlr(zlr({},r),{},Hlr({},i,a))},{});return[{description:"Files",accept:e}]}return t}function Ylr(t){if(O$(t))return Object.entries(t).reduce(function(e,r){var n=mY(r,2),o=n[0],i=n[1];return[].concat($lr(e),[o],$lr(i))},[]).filter(function(e){return ecr(e)||tcr(e)}).join(",")}function Xlr(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function Qlr(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function ecr(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 AVn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function IVn(t){if(Array.isArray(t))return Q5e(t)}function X5e(t,e){return NVn(t)||RVn(t,e)||ocr(t,e)||MVn()}function MVn(){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 ocr(t,e){if(t){if(typeof t=="string")return Q5e(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 Q5e(t,e)}}function Q5e(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 RVn(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 NVn(t){if(Array.isArray(t))return t}function rcr(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 Es(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?rcr(Object(r),!0).forEach(function(n){eWe(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):rcr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function eWe(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function b_e(t,e){if(t==null)return{};var r=jVn(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 jVn(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 rWe=(0,zn.forwardRef)(function(t,e){var r=t.children,n=b_e(t,SVn),o=nWe(n),i=o.open,a=b_e(o,CVn);return(0,zn.useImperativeHandle)(e,function(){return{open:i}},[i]),zn.default.createElement(zn.Fragment,null,r(Es(Es({},a),{},{open:i})))});rWe.displayName="Dropzone";var icr={disabled:!1,getFilesFromEvent:W5e,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};rWe.defaultProps=icr;rWe.propTypes={children:ea.default.func,accept:ea.default.objectOf(ea.default.arrayOf(ea.default.string)),multiple:ea.default.bool,preventDropOnDocument:ea.default.bool,noClick:ea.default.bool,noKeyboard:ea.default.bool,noDrag:ea.default.bool,noDragEventsBubbling:ea.default.bool,minSize:ea.default.number,maxSize:ea.default.number,maxFiles:ea.default.number,disabled:ea.default.bool,getFilesFromEvent:ea.default.func,onFileDialogCancel:ea.default.func,onFileDialogOpen:ea.default.func,useFsAccessApi:ea.default.bool,autoFocus:ea.default.bool,onDragEnter:ea.default.func,onDragLeave:ea.default.func,onDragOver:ea.default.func,onDrop:ea.default.func,onDropAccepted:ea.default.func,onDropRejected:ea.default.func,onError:ea.default.func,validator:ea.default.func};var tWe={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function nWe(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=Es(Es({},icr),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,h=e.onDropRejected,m=e.onFileDialogCancel,g=e.onFileDialogOpen,y=e.useFsAccessApi,_=e.autoFocus,w=e.preventDropOnDocument,S=e.noClick,C=e.noKeyboard,E=e.noDrag,P=e.noDragEventsBubbling,T=e.onError,I=e.validator,N=(0,zn.useMemo)(function(){return Ylr(r)},[r]),M=(0,zn.useMemo)(function(){return Zlr(r)},[r]),D=(0,zn.useMemo)(function(){return typeof g=="function"?g:ncr},[g]),k=(0,zn.useMemo)(function(){return typeof m=="function"?m:ncr},[m]),F=(0,zn.useRef)(null),K=(0,zn.useRef)(null),U=(0,zn
<summary style="${Ot}">${Te}</summary>
<div class="tw-text-muted" style="${jr}">${Ze.trim()}</div>
2025-07-05 20:48:33 +08:00
</details>
2025-09-01 12:32:47 +08:00
`);let Cr=new RegExp(`<${ae}>([\\s\\S]*)$`);return pe=pe.replace(Cr,(Me,Ze)=>`<div style="${ke}">
<div style="${Ot}">${Ae}</div>
<div class="tw-text-muted" style="${jr}">${Ze.trim()}</div>
</div>`),pe}let Vn=new RegExp(`<${ae}>([\\s\\S]*?)<\\/${ae}>`,"g");return pe.replace(Vn,(Xr,Cr)=>`<details style="${ke}">
<summary style="${Ot}">${Te}</summary>
<div class="tw-text-muted" style="${jr}">${Cr.trim()}</div>
2025-07-05 20:48:33 +08:00
</details>
2025-09-01 12:32:47 +08:00
`)},Q=pe=>L(pe,"think","Thought for a while","Thinking..."),z=pe=>{let ae=ke=>{let Ot=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;return ke.replace(Ot,(jr,Mr)=>Mr.trim())},Te=ke=>{if(!r)return ke;let Ot=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;return ke.replace(Ot,(jr,Mr)=>Mr.trim())},Ae=ae(pe);return Ae=Te(Ae),L(Ae,"writeToFile","Generated new content","Generating changes...")},W=(pe,ae,Te)=>pe.split(/(```[\s\S]*?```|`[^`]*`)/g).map((ke,Ot)=>Ot%2===0?ke.replace(ae,(jr,Mr)=>{let Vn=e.metadataCache.getFirstLinkpathDest(Mr,ee);return Vn?Te(Vn):jr}):ke).join(""),V=U.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),q=W(V,/!\[\[(.*?)]]/g,pe=>`![](${e.vault.getResourcePath(pe)})`),H=Q(q),G=z(H),Z=E(G);return W(Z,/(?<!!)\[\[([^\]]+)]]/g,pe=>`<a href="obsidian://open?file=${encodeURIComponent(pe.path)}">${pe.basename}</a>`)},[e,r]),E=U=>{let X=U.split(`
2025-07-05 20:48:33 +08:00
#### Sources:
2025-09-01 12:32:47 +08:00
`);if(X.length!==2)return U;let[ee,L]=X,Q=L.split(`
2025-08-30 08:29:39 +08:00
`).map(z=>{let W=z.match(/- \[\[(.*?)\]\]/);return W?`<li>[[${W[1]}]]</li>`:z}).join(`
`);return ee+`
2025-07-05 20:48:33 +08:00
<br/>
<details><summary>Sources</summary>
<ul>
2025-08-30 08:29:39 +08:00
`+Q+`
2025-07-05 20:48:33 +08:00
</ul>
2025-09-01 12:32:47 +08:00
</details>`};(0,vr.useEffect)(()=>{let U=!1;if(p.current&&t.sender!==Fo){h.current||(h.current=new T$.Component);let X=C(t.message),ee=_ze(X);if(!U){let L=new Set;p.current.querySelectorAll('[id^="tool-call-"]').forEach(q=>{let H=q.id.replace("tool-call-","");L.add(H)}),p.current.querySelectorAll(".message-segment").forEach(q=>q.remove());let W=0;ee.segments.forEach((q,H)=>{if(q.type==="text"&&q.content.trim()){let G=p.current.children[W],Z=document.createElement("div");Z.className="message-segment",G?p.current.insertBefore(Z,G):p.current.appendChild(Z),T$.MarkdownRenderer.renderMarkdown(q.content,Z,"",h.current),W++}else if(q.type==="toolCall"&&q.toolCall){let G=q.toolCall.id;if(document.getElementById(`tool-call-${G}`)){let de=w.current.get(G);de&&de.render(vr.default.createElement(hWe,{toolName:q.toolCall.toolName,displayName:q.toolCall.displayName,emoji:q.toolCall.emoji,isExecuting:q.toolCall.isExecuting,result:q.toolCall.result||null,confirmationMessage:q.toolCall.confirmationMessage})),W++}else{let de=p.current.children[W],pe=document.createElement("div");pe.className="tool-call-container",pe.id=`tool-call-${G}`,de?p.current.insertBefore(pe,de):p.current.appendChild(pe);let ae=Mcr.default.createRoot(pe);w.current.set(G,ae),ae.render(vr.default.createElement(hWe,{toolName:q.toolCall.toolName,displayName:q.toolCall.displayName,emoji:q.toolCall.emoji,isExecuting:q.toolCall.isExecuting,result:q.toolCall.result||null,confirmationMessage:q.toolCall.confirmationMessage})),W++}}});let V=new Set(ee.segments.filter(q=>q.type==="toolCall"&&q.toolCall).map(q=>q.toolCall.id));L.forEach(q=>{if(!V.has(q)){let H=document.getElementById(`tool-call-${q}`);if(H){let G=w.current.get(q);G&&setTimeout(()=>{try{G.unmount()}catch(Z){console.debug("Error unmounting tool call root:",Z)}w.current.delete(q)},0),H.remove()}}})}}return()=>{U=!0}},[t,e,h,r,C]),(0,vr.useEffect)(()=>{let U=h,X=g.current;return(()=>{let L=y(),Q=Date.now()-60*60*1e3;L.forEach((z,W)=>{let V=parseInt(W);!isNaN(V)&&V<Q&&setTimeout(()=>{z.forEach(q=>{try{q.unmount()}catch{}}),L.delete(W)},0)})})(),()=>{setTimeout(()=>{if(U.current&&(U.current.unload(),U.current=null),X.startsWith("temp-")){let L=y(),Q=L.get(X);Q&&(Q.forEach(z=>{try{z.unmount()}catch(W){console.debug("Error unmounting React root during cleanup:",W)}}),L.delete(X))}},0)}},[]),(0,vr.useEffect)(()=>{l&&m.current&&P(m.current)},[l]),(0,vr.useEffect)(()=>{f(t.message)},[t.message]);let P=U=>{U.style.height="auto",U.style.height=`${U.scrollHeight}px`},T=U=>{f(U.target.value),P(U.target)},I=U=>{U.nativeEvent.isComposing||(U.key==="Enter"&&!U.shiftKey?(U.preventDefault(),D()):U.key==="Escape"&&(U.preventDefault(),N()))},N=()=>{c(!1),f(t.message)},M=()=>{c(!0)},D=()=>{c(!1),o&&o(d)},k=()=>{t.sources&&t.sources.length>0&&new x_e(e,t.sources).open()},F=()=>{let U=e.workspace.getMostRecentLeaf();if((!U||!(U.view instanceof T$.MarkdownView))&&(U=e.workspace.getLeaf(!1),!U||!(U.view instanceof T$.MarkdownView)))return;let ee=U.view.editor.getSelection().length>0,L=wee(t.message);u8(L,ee)},K=()=>t.content?vr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((U,X)=>U.type==="text"?vr.default.createElement("div",{key:X},t.sender===Fo&&l?vr.default.createElement("textarea",{ref:m,value:d,onChange:T,onKeyDown:I,autoFocus:!0,className:"edit-textarea"}):t.sender===Fo?vr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):vr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""})):U.type==="image_url"?vr.default.createElement("div",{key:X,className:"message-image-content"},vr.default.createElement("img",{src:U.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===Fo&&l?vr.default.createElement("textarea",{ref:m,value:d,onChange:T,onKeyDown:I,autoFocus:!0,className:"edit-textarea"}):t.sender===Fo?vr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-norm
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-09-01 12:32:47 +08:00
`)},U6n=0,hV=[];function ydr(t){var e=Da.useRef([]),r=Da.useRef([0,0]),n=Da.useRef(),o=Da.useState(U6n++)[0],i=Da.useState(uA)[0],a=Da.useRef(t);Da.useEffect(function(){a.current=t},[t]),Da.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var m=oV([t.lockRef.current],(t.shards||[]).map(gdr),!0).filter(Boolean);return m.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=Da.useCallback(function(m,g){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var y=O_e(m),_=r.current,w="deltaX"in m?m.deltaX:_[0]-y[0],S="deltaY"in m?m.deltaY:_[1]-y[1],C,E=m.target,P=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&P==="h"&&E.type==="range")return!1;var T=NWe(P,E);if(!T)return!0;if(T?C=P:(C=P==="v"?"h":"v",T=NWe(P,E)),!T)return!1;if(!n.current&&"changedTouches"in m&&(w||S)&&(n.current=C),!C)return!0;var I=n.current||C;return mdr(I,g,m,I==="h"?w:S,!0)},[]),u=Da.useCallback(function(m){var g=m;if(!(!hV.length||hV[hV.length-1]!==i)){var y="deltaY"in g?hdr(g):O_e(g),_=e.current.filter(function(C){return C.name===g.type&&(C.target===g.target||g.target===C.shadowParent)&&B6n(C.delta,y)})[0];if(_&&_.should){g.cancelable&&g.preventDefault();return}if(!_){var w=(a.current.shards||[]).map(gdr).filter(Boolean).filter(function(C){return C.contains(g.target)}),S=w.length>0?s(g,w[0]):!a.current.noIsolation;S&&g.cancelable&&g.preventDefault()}}},[]),l=Da.useCallback(function(m,g,y,_){var w={name:m,delta:g,target:y,should:_,shadowParent:q6n(y)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(S){return S!==w})},1)},[]),c=Da.useCallback(function(m){r.current=O_e(m),n.current=void 0},[]),d=Da.useCallback(function(m){l(m.type,hdr(m),m.target,s(m,t.lockRef.current))},[]),f=Da.useCallback(function(m){l(m.type,O_e(m),m.target,s(m,t.lockRef.current))},[]);Da.useEffect(function(){return hV.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,A$),document.addEventListener("touchmove",u,A$),document.addEventListener("touchstart",c,A$),function(){hV=hV.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,A$),document.removeEventListener("touchmove",u,A$),document.removeEventListener("touchstart",c,A$)}},[]);var p=t.removeScrollBar,h=t.inert;return Da.createElement(Da.Fragment,null,h?Da.createElement(i,{styles:z6n(o)}):null,p?Da.createElement(v$,{gapMode:t.gapMode}):null)}function q6n(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var bdr=_$(C_e,ydr);var _dr=E_e.forwardRef(function(t,e){return E_e.createElement(bY,Di({},t,{ref:e,sideCar:bdr}))});_dr.classNames=bY.classNames;var jWe=_dr;var Xl=j(st(),1),DWe="Popover",[vdr,PWi]=Qa(DWe,[PWe]),vY=PWe(),[H6n,gN]=vdr(DWe),wdr=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=vY(e),u=ts.useRef(null),[l,c]=ts.useState(!1),[d=!1,f]=tm({prop:n,defaultProp:o,onChange:i});return(0,Xl.jsx)(adr,{...s,children:(0,Xl.jsx)(H6n,{scope:e,contentId:Jl(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:ts.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:ts.useCallback(()=>c(!0),[]),onCustomAnchorRemove:ts.useCallback(()=>c(!1),[]),modal:a,children:r})})};wdr.displayName=DWe;var xdr="PopoverAnchor",V6n=ts.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=gN(xdr,r),i=vY(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return ts.useEffect(()=>(a(),()=>s()),[a,s]),(0,Xl.jsx)(AWe,{...i,...n,ref:e})});V6n.displayName=xdr;var Sdr="PopoverTrigger",Cdr=ts.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=gN(Sdr,r),i=vY(r),a=sv(e,o.triggerRef),s=(0,Xl.jsx)(im.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Adr(o.open),...n,ref:a,onClick:VO(t.
2025-08-30 08:29:39 +08:00
`).map(_=>{if(!_.trim())return _;try{return new URL(_.trim()),_}catch{return _}});p("contextSource.webUrls",y.join(`
2025-09-01 12:32:47 +08:00
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),rr.default.createElement(Yn,{label:"YouTube URLs"},rr.default.createElement(J_,{value:u.contextSource?.youtubeUrls,onChange:m=>{let y=m.target.value.split(`
2025-08-30 08:29:39 +08:00
`).map(_=>{if(!_.trim())return _;try{let w=new URL(_.trim());return w.hostname.includes("youtube.com")||w.hostname.includes("youtu.be"),_}catch{return _}});p("contextSource.youtubeUrls",y.join(`
2025-09-01 12:32:47 +08:00
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),rr.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},rr.default.createElement(he,{variant:"ghost",onClick:r,disabled:o},"Cancel"),rr.default.createElement(he,{onClick:h,disabled:o||!f()},o?"Saving...":"Save")))}var NY=class extends jV.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,xpr.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(rr.default.createElement(z5n,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};po();var ra=j(Y());var pt=j(Y(),1),$9e=j(za(),1);function h9e(t,[e,r]){return Math.min(r,Math.max(e,t))}function Ks(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var xN=j(Y(),1);var bA=j(Y(),1),Spr=j(st(),1);function Cpr(t,e=[]){let r=[];function n(i,a){let s=bA.createContext(a),u=r.length;r=[...r,a];function l(d){let{scope:f,children:p,...h}=d,m=f?.[t][u]||s,g=bA.useMemo(()=>h,Object.values(h));return(0,Spr.jsx)(m.Provider,{value:g,children:p})}function c(d,f){let p=f?.[t][u]||s,h=bA.useContext(p);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return l.displayName=i+"Provider",[l,c]}let o=()=>{let i=r.map(a=>bA.createContext(a));return function(s){let u=s?.[t]||i;return bA.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,U5n(o,...e)]}function U5n(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return bA.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var mf=j(Y(),1);var DV=j(st(),1),ive=mf.forwardRef((t,e)=>{let{children:r,...n}=t,o=mf.Children.toArray(r),i=o.find(H5n);if(i){let a=i.props.children,s=o.map(u=>u===i?mf.Children.count(a)>1?mf.Children.only(null):mf.isValidElement(a)?a.props.children:null:u);return(0,DV.jsx)(g9e,{...n,ref:e,children:mf.isValidElement(a)?mf.cloneElement(a,void 0,s):null})}return(0,DV.jsx)(g9e,{...n,ref:e,children:r})});ive.displayName="Slot";var g9e=mf.forwardRef((t,e)=>{let{children:r,...n}=t;if(mf.isValidElement(r)){let o=W5n(r);return mf.cloneElement(r,{...V5n(n,r.props),ref:e?r$(e,o):o})}return mf.Children.count(r)>1?mf.Children.only(null):null});g9e.displayName="SlotClone";var q5n=({children:t})=>(0,DV.jsx)(DV.Fragment,{children:t});function H5n(t){return mf.isValidElement(t)&&t.type===q5n}function V5n(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 W5n(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 ave=j(st(),1);function Opr(t){let e=t+"CollectionProvider",[r,n]=Cpr(e),[o,i]=r(e,{collectionRef:{current:null},itemMap:new Map}),a=p=>{let{scope:h,children:m}=p,g=xN.default.useRef(null),y=xN.default.useRef(new Map).current;return(0,ave.jsx)(o,{scope:h,itemMap:y,collectionRef:g,children:m})};a.displayName=e;let s=t+"CollectionSlot",u=xN.default.forwardRef((p,h)=>{let{scope:m,children:g}=p,y=i(s,m),_=Vs(h,y.collectionRef);return(0,ave.jsx)(ive,{ref:_,children:g})});u.displayName=s;let l=t+"CollectionItemSlot",c="data-radix-collection-item",d=xN.default.forwardRef((p,h)=>{let{scope:m,children:g,...y}=p,_=xN.default.useRef(null),w=Vs(h,_),S=i(l,m);return xN.default.useEffect(()=>(S.itemMap.set(_,{ref:_,...y}),()=>void S.itemMap.delete(_))),(0,ave.jsx)(ive,{[c]:"",ref:w,children:g})});d.displayName=l;function f(p){let h=i(t+"CollectionConsumer",p);return xN.default.u
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-09-01 12:32:47 +08:00
`)},MWn=0,FV=[];function cmr(t){var e=La.useRef([]),r=La.useRef([0,0]),n=La.useRef(),o=La.useState(MWn++)[0],i=La.useState(uA)[0],a=La.useRef(t);La.useEffect(function(){a.current=t},[t]),La.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var m=oV([t.lockRef.current],(t.shards||[]).map(lmr),!0).filter(Boolean);return m.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=La.useCallback(function(m,g){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var y=lve(m),_=r.current,w="deltaX"in m?m.deltaX:_[0]-y[0],S="deltaY"in m?m.deltaY:_[1]-y[1],C,E=m.target,P=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&P==="h"&&E.type==="range")return!1;var T=N9e(P,E);if(!T)return!0;if(T?C=P:(C=P==="v"?"h":"v",T=N9e(P,E)),!T)return!1;if(!n.current&&"changedTouches"in m&&(w||S)&&(n.current=C),!C)return!0;var I=n.current||C;return smr(I,g,m,I==="h"?w:S,!0)},[]),u=La.useCallback(function(m){var g=m;if(!(!FV.length||FV[FV.length-1]!==i)){var y="deltaY"in g?umr(g):lve(g),_=e.current.filter(function(C){return C.name===g.type&&(C.target===g.target||g.target===C.shadowParent)&&AWn(C.delta,y)})[0];if(_&&_.should){g.cancelable&&g.preventDefault();return}if(!_){var w=(a.current.shards||[]).map(lmr).filter(Boolean).filter(function(C){return C.contains(g.target)}),S=w.length>0?s(g,w[0]):!a.current.noIsolation;S&&g.cancelable&&g.preventDefault()}}},[]),l=La.useCallback(function(m,g,y,_){var w={name:m,delta:g,target:y,should:_,shadowParent:RWn(y)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(S){return S!==w})},1)},[]),c=La.useCallback(function(m){r.current=lve(m),n.current=void 0},[]),d=La.useCallback(function(m){l(m.type,umr(m),m.target,s(m,t.lockRef.current))},[]),f=La.useCallback(function(m){l(m.type,lve(m),m.target,s(m,t.lockRef.current))},[]);La.useEffect(function(){return FV.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,$$),document.addEventListener("touchmove",u,$$),document.addEventListener("touchstart",c,$$),function(){FV=FV.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,$$),document.removeEventListener("touchmove",u,$$),document.removeEventListener("touchstart",c,$$)}},[]);var p=t.removeScrollBar,h=t.inert;return La.createElement(La.Fragment,null,h?La.createElement(i,{styles:IWn(o)}):null,p?La.createElement(v$,{gapMode:t.gapMode}):null)}function RWn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var dmr=_$(uve,cmr);var fmr=cve.forwardRef(function(t,e){return cve.createElement(jY,Di({},t,{ref:e,sideCar:dmr}))});fmr.classNames=jY.classNames;var LY=fmr;var wr=j(st(),1),NWn=[" ","Enter","ArrowUp","ArrowDown"],jWn=[" ","Enter"],kY="Select",[fve,pve,DWn]=Opr(kY),[kV,d7i]=Qa(kY,[DWn,O9e]),mve=O9e(),[LWn,ON]=kV(kY),[FWn,kWn]=kV(kY),pmr=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:h}=t,m=mve(e),[g,y]=pt.useState(null),[_,w]=pt.useState(null),[S,C]=pt.useState(!1),E=YH(l),[P=!1,T]=tm({prop:n,defaultProp:o,onChange:i}),[I,N]=tm({prop:a,defaultProp:s,onChange:u}),M=pt.useRef(null),D=g?h||!!g.closest("form"):!0,[k,F]=pt.useState(new Set),K=Array.from(k).map(U=>U.props.value).join(";");return(0,wr.jsx)(Zpr,{...m,children:(0,wr.jsxs)(LWn,{required:p,scope:e,trigger:g,onTriggerChange:y,valueNode:_,onValueNodeChange:w,valueNodeHasChildren:S,onValueNodeHasChildrenChange:C,contentId:Jl(),value:I,onValueChange:N,open:P,onOpenChange:T,dir:E,triggerPointerDownPosRef:M,disabled:f,children:[(0,wr.jsx)(fve.Provider,{scope:e,children:(0,wr.jsx)(FWn,{scope:t.__scopeSelect,onNativeOptionAdd:pt.useCallback(U=>{F(X=>new Set(X).add(U))},[]),onNativeOption
2025-08-30 08:29:39 +08:00
- a positive number
2025-09-01 12:32:47 +08:00
- less than the value passed to \`max\` (or ${X9e} if no \`max\` prop is set)
2025-08-30 08:29:39 +08:00
- \`null\` or \`undefined\` if the progress is indeterminate.
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
Defaulting to \`null\`.`}var Q9e=ohr,uhr=ahr;xn();var eKe=$Y.forwardRef(({className:t,value:e,...r},n)=>$Y.createElement(Q9e,{ref:n,className:me("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...r},$Y.createElement(uhr,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));eKe.displayName=Q9e.displayName;un();ua();po();Gt();function rKe({plugin:t,setHiddenCard:e}){let[r]=Fee(),n=r.total,o=r.success,i=r.failed,a=r.processingFiles,[s,u]=(0,tKe.useState)(!1),[l,c]=(0,tKe.useState)(!1),d=o.length+i.length,f=n.length>0?Math.round(d/n.length*100):0,p=m=>m.path,h=async m=>{if(!t?.projectManager){ie("ProjectManager not available");return}try{await t.projectManager.retryFailedItem(m)}catch(g){ie(`Error retrying failed item: ${g}`)}};return Ur.createElement(I$,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},Ur.createElement(M$,null,Ur.createElement(SY,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Ur.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ur.createElement(Fm,{className:"tw-size-5"}),"Context Loading"),Ur.createElement(he,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},Ur.createElement(vi,{className:"tw-size-4"})))),Ur.createElement(R$,{className:"tw-space-y-6"},Ur.createElement("div",{className:"tw-space-y-2"},Ur.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},Ur.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ur.createElement("span",{className:"tw-text-muted"},"Total progress"),Ur.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",Ur.createElement("span",{className:"tw-font-medium tw-text-success"},o.length),", Failed: ",Ur.createElement("span",{className:"tw-font-medium tw-text-error"},i.length),")")),Ur.createElement("span",{className:"tw-font-medium"},d,"/",n.length," (",f,"%)")),Ur.createElement(eKe,{value:f,className:"tw-h-2"})),a.length>0&&Ur.createElement("div",{className:"tw-space-y-3"},Ur.createElement("div",{className:"tw--m-1 tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-muted/10",onClick:()=>u(!s)},Ur.createElement(nu,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),Ur.createElement("span",{className:"tw-text-sm tw-font-medium"},"Processing"),s?Ur.createElement(ki,{className:"tw-ml-auto tw-size-4"}):Ur.createElement(Lm,{className:"tw-ml-auto tw-size-4"})),s&&Ur.createElement("div",{className:"tw-max-h-32 tw-space-y-2 tw-overflow-y-auto"},a.map((m,g)=>Ur.createElement("div",{key:g,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2 tw-text-sm tw-bg-faint/10"},Ur.createElement("div",{className:"tw-size-2 tw-animate-pulse tw-rounded-full tw-bg-interactive-accent"}),Ur.createElement(xh,{className:"tw-flex-1",title:m},m))))),i.length>0&&Ur.createElement("div",{className:"tw-space-y-3"},Ur.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ur.createElement("div",{className:"-tw-m-1 tw-flex tw-flex-1 tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-muted/10",onClick:()=>c(!l)},Ur.createElement(zv,{className:"tw-size-4 tw-text-error"}),Ur.createElement("span",{className:"tw-text-sm tw-font-medium"},"Failed"),Ur.createElement(cp,{variant:"destructive",className:"tw-text-xs"},i.length," files"),l?Ur.createElement(ki,{className:"tw-ml-auto tw-size-4"}):Ur.createElement(Lm,{className:"tw-ml-auto tw-size-4"}))),l&&Ur.createElement("div",{className:"tw-max-h-32 tw-space-y-2 tw-overflow-y-auto"},i.map((m,g)=>Ur.createElement("div",{key:g,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2 tw-text-sm tw-bg-faint/10"},Ur.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-1"},Ur.createElement("div",{className:"tw-flex tw-items-
`));let bf={notes:Ii,urls:jh(d)?ne||[]:[],selectedTextContexts:ee};m(""),M([]),X.setLoading(!0),X.setLoadingMessage(Iv.DEFAULT);let mp=await i.sendMessage(_i,bf,d,T,ze.length>0?ze:void 0);h&&r(h),a.autosaveChat&&Te();let Hi=i.getLLMMessage(mp);Hi&&await nKe(Hi,t,l,X.setCurrentAiMessage,y,{debug:a.debug,updateLoadingMessage:X.setLoadingMessage}),a.autosaveChat&&Te()}catch(ze){console.error("Error sending message:",ze),new Ql.Notice("Failed to send message. Please try again.")}finally{X.setLoading(!1),X.setLoadingMessage(Iv.DEFAULT)}},Te=(0,nr.useCallback)(async()=>{if(!pe){console.error("App instance is not available.");return}try{await i.saveChat(c)}catch(le){console.error("Error saving chat as note:",eo(le)),new Ql.Notice("Failed to save chat as note. Check console for details.")}},[pe,i,c]),Ae=(0,nr.useCallback)(le=>{g.current&&(B(`stopping generation..., reason: ${le}`),g.current.abort(le),X.setLoading(!1),X.setLoadingMessage(Iv.DEFAULT))},[X]);(0,nr.useEffect)(()=>(U.current=!0,()=>{U.current=!1,g.current&&g.current.abort("component-unmount")}),[]);let ke=(0,nr.useCallback)(async le=>{if(le<=0){new Ql.Notice("Cannot regenerate the first message.");return}let ne=u[le];if(!ne){new Ql.Notice("Message not found.");return}X.setCurrentAiMessage(""),X.setLoading(!0);try{await i.regenerateMessage(ne.id,X.setCurrentAiMessage,l)?a.debug&&console.log("Message regenerated successfully"):new Ql.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&Te()}catch(fe){console.error("Error regenerating message:",fe),new Ql.Notice("Failed to regenerate message. Please try again.")}finally{X.setLoading(!1)}},[u,i,a.debug,a.autosaveChat,Te,l,X]),Ot=(0,nr.useCallback)(async(le,ne)=>{let fe=u[le];if(!(!fe||fe.message===ne))try{if(!await i.editMessage(fe.id,ne,d,T)){new Ql.Notice("Failed to edit message. Please try again.");return}if(fe.sender===Fo){let ye=le<u.length-1;if(await i.truncateAfterMessageId(fe.id),ye){X.setLoading(!0);try{let ze=i.getLLMMessage(fe.id);ze&&await nKe(ze,t,l,X.setCurrentAiMessage,y,{debug:a.debug,updateLoadingMessage:X.setLoadingMessage})}catch(ze){console.error("Error regenerating AI response:",ze),new Ql.Notice("Failed to regenerate AI response. Please try again.")}finally{X.setLoading(!1)}}}a.autosaveChat&&Te()}catch(be){console.error("Error editing message:",be),new Ql.Notice("Failed to edit message. Please try again.")}},[u,i,d,T,l,t,a.debug,a.autosaveChat,Te,X,y]);(0,nr.useEffect)(()=>{e&&e(Te)},[e,Te]);let jr=(0,nr.useCallback)(le=>{let ne=a.projectList||[];if(ne.findIndex(ze=>ze.name===le.name)>=0)throw new Error(`Project "${le.name}" already exists, please use a different name`);let be=[...ne,le];return nt("projectList",be),wu()?.id===le.id?c_e().then(()=>{new Ql.Notice(`${le.name} added and context loaded`)}).catch(ze=>{console.error("Error loading project context:",ze),new Ql.Notice(`${le.name} added but context loading failed`)}):new Ql.Notice(`${le.name} added successfully`),!0},[a.projectList]),Mr=(0,nr.useCallback)((le,ne)=>{let fe=a.projectList||[];if(!fe.find(hr=>hr.name===le.name))throw new Error(`Project "${le.name}" does not exist`);let ye=fe.map(hr=>hr.name===le.name?ne:hr);return nt("projectList",ye),wu()?.id===le.id?(Lj(ne),c_e().then(()=>{new Ql.Notice(`${le.name} updated and context reloaded`)}).catch(hr=>{console.error("Error reloading project context:",hr),new Ql.Notice(`${le.name} updated but context reload failed`)})):new Ql.Notice(`${le.name} updated successfully`),!0},[a.projectList]),Vn=(0,nr.useCallback)(le=>{m(ne=>`${ne} ${le} `)},[]),Xr=(0,nr.useCallback)(le=>{btt(le)},[]),Cr=(0,nr.useCallback)(async le=>{let ne=u[le];if(!ne){new Ql.Notice("Message not found.");return}try{await i.deleteMessage(ne.id)||new Ql.Notice("Failed to delete message. Please try again.")}catch(fe){console.error("Error deleting message:",fe),new Ql.Notice("Failed to delete message. Please try again.")}},[u,i]),Me=(0,nr.useCallback)(async()=>{Ae("new-chat"),a.autosaveChat&&await Te(),i.clearMessages(),X.setCurrentAiMessage(""),P([]),_tt(),V!=="copilot_plus"?I(!1):I(a.includeActiveNoteAsCon
2025-07-05 20:48:33 +08:00
Original name: ${a.title}
2025-09-01 12:32:47 +08:00
${a.content}`}):e.push(a)}await Pc.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 ${H1()}.`;r.length>0&&(await m9n(r),i+=`
2025-07-05 20:48:33 +08:00
2025-09-01 12:32:47 +08:00
We found ${r.length} unsupported commands. They are saved in ${H1()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),nt("inlineEditCommands",[]),new Tc(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function oKe(){let t=up(),e=uir.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Pc.getInstance().updateCommands(r)}async function bhr(){if(oe().suggestedDefaultCommands)return;up().length===0&&(new Tc(app,()=>{oKe()},"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(),nt("suggestedDefaultCommands",!0))}var rs=j(Y()),BY=require("obsidian"),_hr=j($c());po();ua();function h9n({plugin:t,onRemove:e}){let[r,n]=(0,rs.useState)(""),[o,i]=(0,rs.useState)(!0),[a,s]=(0,rs.useState)(""),[u]=oI(),[l,c]=(0,rs.useState)(u),d=(0,rs.useRef)(null);(0,rs.useEffect)(()=>{let m=t.app.workspace.getActiveViewOfType(BY.MarkdownView);if(m&&m.editor){let g=m.editor.getSelection();s(g)}},[t.app]),(0,rs.useEffect)(()=>{d.current&&d.current.focus()},[]);let f=async()=>{if(!r.trim()){new BY.Notice("Please enter a prompt");return}let m=`
2025-08-30 08:29:39 +08:00
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`,g=r;if(o){let w=g.includes("{}"),S=/\{activenote\}/i.test(g),C=[];w||C.push("{}"),S||C.push("{activeNote}"),C.length>0&&(g+=`
${C.join(`
2025-09-01 12:32:47 +08:00
`)}`)}let y={title:"Quick Command",content:g,showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:l,lastUsedMs:Date.now()};new V1(t.app,{selectedText:a,command:y,systemPrompt:m}).open(),e()},p=()=>{e()};return rs.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4",onKeyDown:m=>{m.key==="Escape"?(m.preventDefault(),p()):m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),f())}},rs.default.createElement("div",{className:"tw-space-y-4"},rs.default.createElement(J_,{ref:d,value:r,onChange:m=>n(m.target.value),placeholder:"Ask me anything...",className:"tw-min-h-24 tw-resize-none",rows:3}),rs.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4"},rs.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4"},rs.default.createElement(m_e,{size:"sm",variant:"ghost",value:l,onChange:c}),rs.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},rs.default.createElement(Ec,{id:"includeActiveNote",checked:o,onCheckedChange:m=>i(!!m)}),rs.default.createElement("label",{htmlFor:"includeActiveNote",className:"tw-cursor-pointer tw-text-sm tw-text-muted"},"Include note context"))),rs.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},rs.default.createElement(he,{variant:"secondary",onClick:p,size:"sm"},"Cancel"),rs.default.createElement(he,{onClick:f,size:"sm"},"Submit")))))}function vhr({plugin:t,element:e}){let r=document.createElement("div");e.appendChild(r);let n=(0,_hr.createRoot)(r),o=()=>{let i=t.app.workspace.getActiveViewOfType(BY.MarkdownView);i&&i.editor&&xbe(i.editor),n.unmount(),r.remove()};return n.render(rs.default.createElement(h9n,{plugin:t,onRemove:o})),{root:n,container:r}}or();bt();Gt();ua();vu();Gt();Mde();ir();var _ve=class t{constructor(){this.contextProcessor=fV.getInstance(),this.mention=fR.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a){try{B(`[ContextManager] Processing context for message ${e.id}`);let s=e.originalMessage||e.message,{processedPrompt:u,includedFiles:l}=await w8e(s,"",n,a),c=o==="copilot_plus"?await this.mention.processUrls(s):{urlContext:"",imageUrls:[]},d=new Set(l.map(y=>y.path)),p=[...e.context?.notes||[]];i&&o!=="project"&&a&&!p.some(y=>y.path===a.path)&&p.push(a);let h=await this.contextProcessor.processContextNotes(d,r,n,p,i,a,o),m=this.contextProcessor.processSelectedTextContexts(),g=u+c.urlContext+h+m;return B(`[ContextManager] Successfully processed context for message ${e.id}`),g}catch(s){return B(`[ContextManager] Error processing context for message ${e.id}:`,s),e.originalMessage||e.message}}async reprocessMessageContext(e,r,n,o,i,a,s){let u=r.getMessage(e);if(!u||u.sender!=="user"||!u.id)return;B(`[ContextManager] Reprocessing context for message ${e}`);let l=await this.processMessageContext(u,n,o,i,a,s);r.updateProcessedText(u.id,l),B(`[ContextManager] Completed context reprocessing for message ${e}`)}createMessageContext(e,r,n=kj()){return{notes:e,urls:r,selectedTextContexts:n}}async extractContextNotes(e,r,n=[]){return[...await Jg(e,r),...n].filter((s,u,l)=>l.findIndex(c=>c.path===s.path)===u)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return kj()}};ir();Gt();var $V=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}addMessage(e,r,n,o,i){let a=this.generateId(),s=tu(new Date),u={id:a,displayText:e,processedText:r,sender:n,timestamp:s,context:o,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(u),B(`[MessageRepository] Added message with ID: ${a}`),a}addDisplayOnlyMessage(e,r,n){if(n){let o=tu(new Date),i={id:n,displayText:e,processedText:e,sender:r,timestamp:o,isVisible:!0,isErrorMessage:!1};return this.messages.push(i),B(`[MessageRepository] Added display-only message with ID: ${n}`),n}return this.addMessage(e,e,r)}addFullMessage(e){let r=e.id||this.generateId(),n=e.timestamp||tu(new Date),o={id:r,displa
2025-08-12 16:40:13 +08:00
[Timestamp: ${n}]`}).join(`
2025-09-01 12:32:47 +08:00
`)}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"?Fo:Zg,u=a[2].trim(),l=u.split(`
2025-08-30 08:29:39 +08:00
`),c=u,d="Unknown time",f=l.length-1;if(f>0&&l[f].startsWith("[Timestamp: ")){let h=l[f].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],c=l.slice(0,f).join(`
`).trim())}let p;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(p=h.getTime())}r.push({message:c,sender:s,isVisible:!0,timestamp:p?{epoch:p,display:d,fileName:""}:null})}return r}async findFileByEpoch(e){let r=await this.getChatHistoryFiles();for(let n of r)if(this.app.metadataCache.getFileCache(n)?.frontmatter?.epoch===e)return n;return null}async generateAITopic(e){if(this.chainManager)try{let r=this.chainManager.chatModelManager.getChatModel();if(!r)return;let n=6,o=200,a=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.
Conversation:
${e.reduce((l,c,d)=>d>=n?l:l+(l?`
2025-09-01 12:32:47 +08:00
`:"")+`${c.sender}: ${c.message.slice(0,o)}`,"")}`;return(await r.invoke(a)).content.toString().trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(r){ie("[ChatPersistenceManager] Error generating AI topic:",r);return}}generateFileName(e,r,n){let o=oe(),a=tu(new Date(r)).fileName,s;if(n)s=n;else{let f=e.find(p=>p.sender===Fo);s=f?f.message.split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|]/g,"").trim():"Untitled Chat"}let u=o.defaultConversationNoteName||"{$date}_{$time}__{$topic}";u=u.replace("{$topic}",s.slice(0,100).replace(/\s+/g,"_")).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let l=u.replace(/[\\/:*?"<>|]/g,"_"),c=wu(),d=c?`${c.id}__`:"";return`${o.defaultSaveFolder}/${d}${l}.md`}generateNoteContent(e,r,n,o){let i=oe(),a=wu();return`---
2025-08-12 16:40:13 +08:00
epoch: ${r}
modelKey: ${n}
2025-08-30 08:29:39 +08:00
${o?`topic: "${o}"`:""}
${a?`projectId: ${a.id}`:""}
${a?`projectName: ${a.name}`:""}
2025-08-12 16:40:13 +08:00
tags:
2025-08-30 08:29:39 +08:00
- ${i.defaultConversationTag}
2025-08-12 16:40:13 +08:00
---
2025-09-01 12:32:47 +08:00
${e}`}};or();var vve=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=_ve.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new zY(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(B(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){B(`[ChatManager] Creating new message repository for project: ${r}`);let o=new $V;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new zY(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async sendMessage(e,r,n,o=!1,i){try{B(`[ChatManager] Sending message: "${e}"`);let a=this.plugin.app.workspace.getActiveFile(),s={...r};if(o&&a){let f=r.notes||[],p=f.some(h=>h.path===a.path);s.notes=p?f:[...f,a]}let u=this.getCurrentMessageRepo(),l=u.addMessage(e,e,Fo,s,i);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(l);let c=u.getMessage(l);if(!c)throw new Error(`Failed to retrieve message ${l}`);let d=await this.contextManager.processMessageContext(c,this.fileParserManager,this.plugin.app.vault,n,o,a);return u.updateProcessedText(l,d),B(`[ChatManager] Successfully sent message ${l}`),l}catch(a){throw B("[ChatManager] Error sending message:",a),a}}async editMessage(e,r,n,o=!1){try{B(`[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(),B(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return B(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{B(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return B(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return B("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Fo)return B("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return B("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return B("[ChatManager] LLM message not found for regeneration"),!1;let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:oe().debug}),B(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return B(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return B(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),B(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return B(`[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(),B("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.updateChainMemory(),B(`[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();a
2025-08-30 08:29:39 +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-09-01 12:32:47 +08:00
`},C9n={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 O9n(t){let{announcements:e=C9n,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=S9n}=t,{announce:i,announcement:a}=Rhr(),s=H$("DndLiveRegion"),[u,l]=(0,Re.useState)(!1);if((0,Re.useEffect)(()=>{l(!0)},[]),w9n((0,Re.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=Re.default.createElement(Re.default.Fragment,null,Re.default.createElement(Ihr,{id:n,value:o.draggable}),Re.default.createElement(Mhr,{id:s,announcement:a}));return r?(0,G$.createPortal)(c,r):c}var Rc;(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"})(Rc||(Rc={}));function Tve(){}function HV(t,e){return(0,Re.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function Ive(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Re.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var dv=Object.freeze({x:0,y:0});function Whr(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Khr(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function E9n(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function Nhr(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 hKe(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function jhr(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 QY=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=jhr(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=Whr(jhr(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(Khr)},Ghr=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Nhr(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=Nhr(u),c=o.reduce((f,p,h)=>f+Whr(l[h],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(Khr)};function P9n(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 T9n=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=P9n(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(E9n)};function A9n(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function Jhr(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:dv}function I9n(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 M9n=I9n(1);function R9n(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-08-30 08:29:39 +08:00
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
2025-09-01 12:32:47 +08:00
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return ya.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},fGn="DialogDescriptionWarning",pGn=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Ggr(fGn).contentName}}.`;return ya.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},Jgr=jgr,Zgr=Lgr,Ygr=kgr,AKe=$gr,IKe=Bgr,MKe=Ugr,RKe=Hgr,Xgr=Wgr;un();xn();var Bve=Jgr,Qgr=Zgr,hGn=Ygr;var eyr=yf.forwardRef(({className:t,...e},r)=>yf.createElement(AKe,{ref:r,className:me("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}));eyr.displayName=AKe.displayName;var aX=yf.forwardRef(({className:t,children:e,container:r,...n},o)=>yf.createElement(hGn,{container:r},yf.createElement(eyr,null),yf.createElement(IKe,{ref:o,className:me("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,yf.createElement(Xgr,{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"},yf.createElement(vi,{className:"tw-size-4"}),yf.createElement("span",{className:"tw-sr-only"},"Close")))));aX.displayName=IKe.displayName;var sX=({className:t,...e})=>yf.createElement("div",{className:me("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});sX.displayName="DialogHeader";var gGn=({className:t,...e})=>yf.createElement("div",{className:me("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});gGn.displayName="DialogFooter";var uX=yf.forwardRef(({className:t,...e},r)=>yf.createElement(MKe,{ref:r,className:me("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));uX.displayName=MKe.displayName;var lX=yf.forwardRef(({className:t,...e},r)=>yf.createElement(RKe,{ref:r,className:me("tw-text-sm tw-text-muted",t),...e}));lX.displayName=RKe.displayName;ir();function qr(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=BV(),a="onChange"in t?t.onChange:void 0,s=(0,Fa.useMemo)(()=>{if(a)return xee(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return Fa.default.createElement(gi,{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 Fa.default.createElement(JO,{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 Fa.default.createElement(J_,{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 Fa.default.createElement(uV,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Fa.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Fa.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:me("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-
2025-08-30 08:29:39 +08:00
detail: `+K)}return F}finally{clearTimeout(k)}},T;try{T=await P(!1)}catch(M){console.log("First fetch attempt failed, trying with safeFetch...");try{T=await P(!0)}catch(D){let k=`
2025-09-01 12:32:47 +08:00
without CORS Error: `+eo(M)+`
with CORS Error: `+eo(D);throw new Error(k)}}let I=await T.json(),N=ayr(w,I);i(M=>({...M,[w]:N})),s(null)}catch(C){console.error(`Error fetching models for ${w}:`,C),l(w),s(null),new LN.Notice(`Failed to load models for ${Mp(w)}: ${eo(C)}`,5e3)}},_=async()=>{if(!c){new LN.Notice("Please select a model first");return}p(!0);try{let w=h(c.provider),S={name:c.name,provider:c.provider,apiKey:w,enabled:!0};if(await Vd.instance.getCurrentChainManager().chatModelManager.ping(S),e.activeModels.find(E=>E.name===c.name&&E.provider===c.provider))new LN.Notice(`Model ${c.name} verified successfully! It already exists in your models list.`);else{let E=[...e.activeModels,S];nt("activeModels",E),new LN.Notice(`Model ${c.name} verified successfully and added to your models list!`)}}catch(w){console.error("Model verification failed:",w),new LN.Notice("Model verification failed: "+eo(w),1e4)}finally{p(!1)}};return Nr.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Nr.default.createElement("div",{className:"tw-mb-4"},Nr.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Nr.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Nr.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Nr.default.createElement("div",{className:"tw-space-y-4"},m.map(w=>Nr.default.createElement(Nr.default.Fragment,{key:w.provider},Nr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Nr.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Nr.default.createElement("div",{className:"tw-truncate"},Mp(w.provider))),Nr.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Nr.default.createElement("div",{className:"tw-flex-1"},Nr.default.createElement(JO,{className:"tw-max-w-full",value:w.apiKey,onChange:S=>g(w.provider,S)})),Nr.default.createElement("div",{className:""},Nr.default.createElement(he,{onClick:()=>{let S=r===w.provider?null:w.provider;n(S),S&&w.apiKey&&o[w.provider]===void 0&&a!==w.provider&&u!==w.provider&&y(w.provider,w.apiKey)},disabled:!w.apiKey,variant:"secondary",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-2 tw-whitespace-nowrap tw-px-4 tw-py-2"},"Add Model",r===w.provider?Nr.default.createElement(Hb,{className:"tw-ml-1 tw-size-4"}):Nr.default.createElement(ki,{className:"tw-ml-1 tw-size-4"})))),Nr.default.createElement("div",null,SE(w.provider).keyManagementURL&&Nr.default.createElement("a",{href:SE(w.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",Mp(w.provider)," Key"))),Nr.default.createElement(iv,{open:r===w.provider,className:"tw-mt-2"},Nr.default.createElement(av,{className:"tw-rounded-md tw-p-3"},Nr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Nr.default.createElement(Yn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Nr.default.createElement("div",null,Nr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Nr.default.createElement("div",{className:"tw-flex-1"},Nr.default.createElement(Y_e,{options:o[w.provider]?.sort((S,C)=>S.name.localeCompare(C.name)).map(S=>({label:S.name,value:S.id}))||[],onChange:S=>{let C=S.target.value,E=o[w.provider]?.find(P=>P.id===C);E&&d({id:E.id,name:E.name,provider:w.provider})},onClick:()=>{w.apiKey&&o[w.provider]===void 0&&a!==w.provider&&u!==w.provider&&y(w.provider,w.apiKey)},value:c?.provider===w.provider?c.id:"",placeholder:"Select Model",disabled:!w.apiKey||a===w.provider||u===w.provider&&o[w.provider]!==null})),Nr.default.createElement("div",{className:"tw-w-[72px]"},Nr.default.createElement(he,{onClick:_,disabled:!c||c.provider!==w.provider||f,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},f?Nr.default.createElement(nu,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}
2025-08-30 08:29:39 +08:00
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
2025-09-01 12:32:47 +08:00
Your existing index will be preserved but not used.`,i=n?"Enable Semantic Search":"Disable Semantic Search",a=n?"Enable":"Disable";super(e,r,o,i,a,"Cancel")}};po();or();bt();un();var Wt=j(Y()),vyr=()=>{let t=vn(),e=async r=>{r!==t.embeddingModelKey&&new Zve(app,async()=>{nt("embeddingModelKey",r),await(await Promise.resolve().then(()=>(Jc(),Qf))).default.getInstance().indexVaultToVectorStore()}).open()};return Wt.default.createElement("div",{className:"tw-space-y-4"},Wt.default.createElement("section",null,Wt.default.createElement("div",{className:"tw-space-y-4"},Wt.default.createElement(qr,{type:"switch",title:"Enable Semantic Search",description:"Enable semantic search for meaning-based document retrieval. When disabled, uses fast lexical search only. Use 'Refresh Vault Index' or 'Force Reindex Vault' to build the embedding index.",checked:t.enableSemanticSearchV3,onCheckedChange:r=>{new Yve(app,()=>nt("enableSemanticSearchV3",r),r).open()}}),t.enableSemanticSearchV3&&Wt.default.createElement(qr,{type:"select",title:"Embedding Model",description:Wt.default.createElement("div",{className:"tw-space-y-2"},Wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Wt.default.createElement("span",{className:"tw-font-medium tw-leading-none tw-text-accent"},"Powers Semantic Local Vault Search"),Wt.default.createElement(so,{delayDuration:0},Wt.default.createElement(St,null,Wt.default.createElement(Ct,{asChild:!0},Wt.default.createElement($i,{className:"tw-size-4"})),Wt.default.createElement(_t,{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},Wt.default.createElement("div",{className:"tw-pt-2 tw-text-sm tw-text-muted"},"This model converts text into vector representations, essential for semantic search and Question Answering (QA) functionality. Changing the embedding model will:"),Wt.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},Wt.default.createElement("li",null,"Require rebuilding your vault's vector index"),Wt.default.createElement("li",null,"Affect semantic search quality"),Wt.default.createElement("li",null,"Impact Question Answering feature performance"))))))),value:t.embeddingModelKey,onChange:e,options:t.activeEmbeddingModels.map(r=>({label:qH(r),value:tn(r)})),placeholder:"Model"}),Wt.default.createElement(qr,{type:"select",title:"Auto-Index Strategy",description:Wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Wt.default.createElement("span",{className:"tw-leading-none"},"Decide when you want the vault to be indexed."),Wt.default.createElement(so,{delayDuration:0},Wt.default.createElement(St,null,Wt.default.createElement(Ct,{asChild:!0},Wt.default.createElement($i,{className:"tw-size-4"})),Wt.default.createElement(_t,null,Wt.default.createElement("div",{className:"tw-space-y-2 tw-py-2"},Wt.default.createElement("div",{className:"tw-space-y-1"},Wt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Choose when to index your vault:"),Wt.default.createElement("ul",{className:"tw-list-disc tw-space-y-1 tw-pl-2 tw-text-sm"},Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"NEVER:"),Wt.default.createElement("span",null,"Manual indexing via command or refresh only"))),Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON STARTUP:"),Wt.default.createElement("span",null,"Index updates when plugin loads or reloads"))),Wt.default.createElement("li",null,Wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Wt.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON MODE SWITCH:"),Wt.default.createElement("span",null,"Updates when entering QA mode (Recommended)"))))),Wt.default.createElement("p",{className:"tw-text-sm tw-text-callout-warning"},"Warning: Cost implications for large vaul
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.
*)
2025-08-30 08:29:39 +08:00
lucide-react/dist/esm/icons/brain.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-07-05 20:48:33 +08:00
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.
*)
2025-08-30 08:29:39 +08:00
lucide-react/dist/esm/icons/circle-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/circle-check-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/circle-dashed.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-07-05 20:48:33 +08:00
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/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.
*)
2025-08-30 08:29:39 +08:00
lucide-react/dist/esm/icons/rotate-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.
*)
2025-07-05 20:48:33 +08:00
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
2025-08-30 08:29:39 +08:00
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap-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/zap.js:
(**
* @license lucide-react v0.462.0 - ISC
2025-07-05 20:48:33 +08:00
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/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 */