3444 lines
5.2 MiB
JavaScript
3444 lines
5.2 MiB
JavaScript
/*
|
|||
|
|
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
|
||
|
|
if you want to view the source, please visit the github repository of this plugin
|
||
|
|
*/
|
||
|
|
|
||
|
|
// Polyfill for import.meta in CommonJS context
|
||
|
|
if (typeof import_meta === 'undefined') {
|
||
|
|
var import_meta = {
|
||
|
|
url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
var Yln=Object.create;var SQ=Object.defineProperty;var Qln=Object.getOwnPropertyDescriptor;var ecn=Object.getOwnPropertyNames;var tcn=Object.getPrototypeOf,rcn=Object.prototype.hasOwnProperty;var B0t=t=>{throw TypeError(t)};var ncn=(t,e,r)=>e in t?SQ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),En=(t,e)=>{for(var r in e)SQ(t,r,{get:e[r],enumerable:!0})},U0t=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ecn(e))!rcn.call(t,o)&&o!==r&&SQ(t,o,{get:()=>e[o],enumerable:!(n=Qln(e,o))||n.enumerable});return t};var $=(t,e,r)=>(r=t!=null?Yln(tcn(t)):{},U0t(e||!t||!t.__esModule?SQ(r,"default",{value:t,enumerable:!0}):r,t)),wpe=t=>U0t(SQ({},"__esModule",{value:!0}),t);var x=(t,e,r)=>ncn(t,typeof e!="symbol"?e+"":e,r),ocn=(t,e,r)=>e.has(t)||B0t("Cannot "+r);var PBe=(t,e,r)=>e.has(t)?B0t("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var z0t=(t,e,r)=>(ocn(t,e,"access private method"),r);var V0t,H0t=v(()=>{V0t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function icn(t){return typeof t=="string"&&V0t.test(t)}var j6,W0t=v(()=>{H0t();j6=icn});function Spe(t,e=0){return(hg[t[e+0]]+hg[t[e+1]]+hg[t[e+2]]+hg[t[e+3]]+"-"+hg[t[e+4]]+hg[t[e+5]]+"-"+hg[t[e+6]]+hg[t[e+7]]+"-"+hg[t[e+8]]+hg[t[e+9]]+"-"+hg[t[e+10]]+hg[t[e+11]]+hg[t[e+12]]+hg[t[e+13]]+hg[t[e+14]]+hg[t[e+15]]).toLowerCase()}var hg,MBe=v(()=>{hg=[];for(let t=0;t<256;++t)hg.push((t+256).toString(16).slice(1))});function $6(){if(!RBe){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");RBe=crypto.getRandomValues.bind(crypto)}return RBe(acn)}var RBe,acn,IBe=v(()=>{acn=new Uint8Array(16)});var scn,ABe,J0t=v(()=>{scn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ABe={randomUUID:scn}});function ucn(t,e,r){if(ABe.randomUUID&&!e&&!t)return ABe.randomUUID();t=t||{};let n=t.random??t.rng?.()??$6();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[r+o]=n[o];return e}return Spe(n)}var gu,K0t=v(()=>{J0t();IBe();MBe();gu=ucn});function lcn(t,e,r){let n;if(t)n=G0t(t.random??t.rng?.()??$6(),t.msecs,t.seq,e,r);else{let o=Date.now(),i=$6();ccn(NBe,o,i),n=G0t(i,NBe.msecs,NBe.seq,e,r)}return e??Spe(n)}function ccn(t,e,r){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function G0t(t,e,r,n,o=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),o=0;else if(o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return e??(e=Date.now()),r??(r=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),n[o++]=e/1099511627776&255,n[o++]=e/4294967296&255,n[o++]=e/16777216&255,n[o++]=e/65536&255,n[o++]=e/256&255,n[o++]=e&255,n[o++]=112|r>>>28&15,n[o++]=r>>>20&255,n[o++]=128|r>>>14&63,n[o++]=r>>>6&255,n[o++]=r<<2&255|t[10]&3,n[o++]=t[11],n[o++]=t[12],n[o++]=t[13],n[o++]=t[14],n[o++]=t[15],n}var NBe,FT,X0t=v(()=>{IBe();MBe();NBe={};FT=lcn});var y_=v(()=>{K0t();X0t();W0t()});var Z0t,Uo,zo=v(()=>{Z0t=Object.defineProperty,Uo=(t,e)=>{let r={};for(var n in t)Z0t(r,n,{get:t[n],enumerable:!0});return e||Z0t(r,Symbol.toStringTag,{value:"Module"}),r}});function Cpe(t,e=L6){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
|
||
|
|
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
||
|
|
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function fcn(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function o(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let c="",d=!1;for(;r<e.length;){let f=e[r];if(d){if(f==="n")c+=`
|
||
|
|
`;else if(f==="t")c+=" ";else if(f==="r")c+="\r";else if(f==="\\")c+="\\";else if(f==='"')c+='"';else if(f==="b")c+="\b";else if(f==="f")c+="\f";else if(f==="/")c+="/";else if(f==="u"){let p=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?c+=String.fromCharCode(Number.parseInt(p,16)):c+=`u${p}`,r+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,c;c+=f}r+=1}return d&&(c+="\\"),c}function i(){let c=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`Invalid number at position ${c}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=c,new Error(`Invalid number '${d}' at position ${c}`);return f}function a(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);let c=e[r];if(c==="{")return u();if(c==="[")return s();if(c==='"')return o();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(c==="-"||c>="0"&&c<="9")return i();throw new Error(`Unexpected character '${c}' at position ${r}`)}function s(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);let c=[];if(r+=1,n(),r>=e.length)return c;if(e[r]==="]")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length||(c.push(a()),n(),r>=e.length))return c;if(e[r]==="]")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return c}function u(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);let c={};if(r+=1,n(),r>=e.length)return c;if(e[r]==="}")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length)return c;let d=o();if(n(),r>=e.length)return c;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(c[d]=a(),n(),r>=e.length))return c;if(e[r]==="}")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return c}let l=a();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return l}function L6(t){try{return typeof t>"u"?null:fcn(t)}catch{return null}}var CQ=v(()=>{});function Y0t(t){let e=Symbol.for(t);return{brand(r,n){var a,s;let o=n?Symbol.for(`${t}.${n}`):e;class i extends(s=r,a=o,s){constructor(...c){super(...c);x(this,a,!0)}static isInstance(c){return typeof c=="object"&&c!==null&&o in c&&c[o]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return Y0t(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}var Q0t,eCt=v(()=>{Q0t=Y0t("langchain")});function AL(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
||
|
|
|
||
|
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
||
|
|
`,t}var DBe,tCt,jBe,aCi,F6=v(()=>{zo();eCt();DBe=Q0t.sub("error"),tCt=class extends DBe.brand(Error){constructor(e){super(e);x(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},jBe=class extends DBe.brand(tCt,"model-abort"){constructor(e,r){super(e);x(this,"name","ModelAbortError");x(this,"partialOutput");this.partialOutput=r}},aCi=class rCt extends DBe.brand(tCt,"context-overflow"){constructor(r){super(r??"Input exceeded the model's context window.");x(this,"name","ContextOverflowError");x(this,"cause")}static fromError(r){let n=new rCt(r.message);return n.cause=r,n}}});function NL(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function nCt(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 xQ,xpe=v(()=>{xQ=class extends Error{constructor(e,r){super(e);x(this,"output");this.output=r}}});var iCt=S((mCi,oCt)=>{"use strict";oCt.exports=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});var fCt=S((hCi,$Be)=>{"use strict";var pcn=/[\p{Lu}]/u,mcn=/[\p{Ll}]/u,aCt=/^[\p{Lu}](?![\p{Lu}])/gu,lCt=/([\p{Alpha}\p{N}_]|$)/u,cCt=/[_.\- ]+/,hcn=new RegExp("^"+cCt.source),sCt=new RegExp(cCt.source+lCt.source,"gu"),uCt=new RegExp("\\d+"+lCt.source,"gu"),gcn=(t,e,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a<t.length;a++){let s=t[a];n&&pcn.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&mcn.test(s)?(t=t.slice(0,a-1)+"-"+t.slice(a-1),i=o,o=!1,n=!0):(n=e(s)===s&&r(s)!==s,i=o,o=r(s)===s&&e(s)!==s)}return t},ycn=(t,e)=>(aCt.lastIndex=0,t.replace(aCt,r=>e(r))),bcn=(t,e)=>(sCt.lastIndex=0,uCt.lastIndex=0,t.replace(sCt,(r,n)=>e(n)).replace(uCt,r=>e(r))),dCt=(t,e)=>{if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(i=>i.trim()).filter(i=>i.length).join("-"):t=t.trim(),t.length===0)return"";let r=e.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(e.locale),n=e.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(e.locale);return t.length===1?e.pascalCase?n(t):r(t):(t!==r(t)&&(t=gcn(t,r,n)),t=t.replace(hcn,""),e.preserveConsecutiveUppercase?t=ycn(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),bcn(t,n))};$Be.exports=dCt;$Be.exports.default=dCt});function mCt(t,e){return e?.[t]||(0,pCt.default)(t)}function hCt(t,e,r){let n={};for(let o in t)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);return n}var pCt,_cn,gCt=v(()=>{pCt=$(iCt(),1),_cn=$(fCt(),1)});function vcn(t){return"lc"in t||Object.keys(t).length===1&&yCt in t}function wcn(t){return{[yCt]:t}}function Scn(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Ccn(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Tpe(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Ccn(t);if(Scn(t))return t;e.add(t);let r=t;if(vcn(r))return e.delete(t),wcn(r);let n={};for(let[o,i]of Object.entries(r))n[o]=Tpe(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Tpe(r,e)):t}var yCt,bCt=v(()=>{yCt="__lc_escaped__"});function _Ct(t){return Array.isArray(t)?[...t]:{...t}}function xcn(t,e){let r=_Ct(t);for(let[n,o]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),s=r;for(let u of a.reverse()){if(s[u]===void 0)break;s[u]=_Ct(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function LBe(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var b_,DL=v(()=>{zo();gCt();bCt();b_=class vCt{constructor(e,...r){x(this,"lc_serializable",!1);x(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this
|
||
|
|
`)}var NCt=v(()=>{});function _b(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>py(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?_z(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>py(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function JBe(t,e){return t==="error"||e==="error"?"error":"success"}function Ncn(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 pc(t,e,r){let n=r?.ignoreKeys??$Ct;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let o={...t};for(let[i,a]of Object.entries(e))if(o[i]==null)o[i]=a;else{if(a==null)continue;if(typeof o[i]!=typeof a||Array.isArray(o[i])!==Array.isArray(a))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof o[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))a&&(o[i]=a);else{if(n.includes(i))continue;o[i]+=a}}else if(typeof o[i]=="number"){if(n.includes(i))continue;o[i]=o[i]+a}else if(typeof o[i]=="object"&&!Array.isArray(o[i]))o[i]=pc(o[i],a,r);else if(Array.isArray(o[i]))o[i]=_z(o[i],a,r);else{if(o[i]===a)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return o}function Dcn(t){return typeof t=="number"||typeof t=="string"}function DCt(t){return typeof t!="object"||t===null||!("index"in t)?!1:Dcn(t.index)}function _z(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let n=[...t];for(let o of e)if(DCt(o)){let i=n.findIndex(a=>{if(!DCt(a))return!1;let s=a.index===o.index,u=a.id!=null&&o.id!=null&&a.id===o.id,l=a.id==null||o.id==null;return s&&(u||l)});i!==-1&&typeof n[i]=="object"&&n[i]!==null?n[i]=pc(n[i],o,r):n.push(o)}else{if(typeof o=="object"&&o!==null&&"text"in o&&o.text==="")continue;n.push(o)}return n}}}function KBe(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
||
|
|
Left ${typeof t}
|
||
|
|
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return _z(t,e,r);if(typeof t=="object"&&typeof e=="object")return pc(t,e,r);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
||
|
|
Left ${t}
|
||
|
|
Right ${e}`)}}function GBe(t){return typeof t.role=="string"}function pS(t){return typeof t?._getType=="function"}function Mpe(t){return __.isInstance(t)}var WBe,jCt,Sm,$Ct,__,my=v(()=>{DL();PQ();BBe();UBe();zBe();HBe();NCt();WBe=Symbol.for("langchain.message");Sm=class extends b_{constructor(e){let r=typeof e=="string"||Array.isArray(e)?{content:e}:e;r.additional_kwargs||(r.additional_kwargs={}),r.response_metadata||(r.response_metadata={});super(r);x(this,"lc_namespace",["langchain_core","messages"]);x(this,"lc_serializable",!0);x(this,jCt,!0);x(this,"id");x(this,"name");x(this,"content");x(this,"additional_kwargs");x(this,"response_metadata");this.name=r.name,r.content===void 0&&r.contentBlocks!==void 0?(this.content=r.contentBlocks,this.response_metadata={output_version:"v1",...r.response_metadata}):r.content!==void 0?(this.content=r.content??[],this.response_metadata=r.response_metadata):(this.content=[],this.response_metadata=r.response_metadata),this.additional_kwargs=r.additional_kwargs,this.id=r.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}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(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ECt,Ppe,TCt].reduce((r,n)=>n(r),e)}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}}static isInstance(e){return typeof e=="object"&&e!==null&&WBe in e&&e[WBe]===!0&&VBe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(jCt=WBe,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=Ncn(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}toFormattedString(e="pretty"){return ACt(this,e)}},$Ct=["index","created","timestamp"];__=class LCt extends Sm{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===LCt.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}}});function XBe(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function ZBe(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);e.push({name:o||"",args:i||{},id:n.id})}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function YBe(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}var Kv,$L,k6=v(()=>{zo();my();Kv=class extends Sm{constructor(e,r,n){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:r}:e;super(o);x(this,"lc_direct_tool_output",!0);x(this,"type","tool");x(this,"status");x(this,"tool_call_id");x(this,"metadata");x(this,"artifact");this.tool_call_id=o.tool_call_id,this.artifact=o.artifact,this.status=o.status,this.metadata=o.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},$L=class extends __{constructor(e){super(e);x(this,"type","tool");x(this,"tool_call_id");x(this,"status");x(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let r=this.constructor;return new r({content:_b(this.content,e.content),additional_kwargs:pc(this.additional_kwargs,e.additional_kwargs),response_metadata:pc(this.response_metadata,e.response_metadata),artifact:KBe(this.artifact,e.artifact),tool_call_id:this.tool_call_id
|
||
|
|
|
||
|
|
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&o===void 0){let[i,a]=ZBe(n);r.tool_calls=i??[],r.invalid_tool_calls=a??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}if(r.response_metadata!==void 0&&"output_version"in r.response_metadata&&r.response_metadata.output_version==="v1"&&(r.contentBlocks=r.content,r.content=void 0),r.contentBlocks!==void 0){r.tool_calls&&r.contentBlocks.push(...r.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));let i=r.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!r.tool_calls?.some(s=>s.id===a.id&&s.name===a.name));i.length>0&&(r.tool_calls=i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"usage_metadata");typeof r!="string"&&(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",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=eUe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let r=this.tool_calls.filter(n=>!e.some(o=>o.id===n.id&&o.name===n.name));e.push(...r.map(n=>({type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};Hr=class extends __{constructor(e){let r;if(typeof e=="string"||Array.isArray(e))r={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===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=rUe(e.tool_call_chunks??[]);r={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"tool_call_chunks",[]);x(this,"usage_metadata");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",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=eUe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let r=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(let n of this.tool_calls)n.id&&!r.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_
|
||
|
|
|
||
|
|
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function OC(t){if(typeof t=="string")return new Au(t);if(pS(t))return t;if(Array.isArray(t)){let[e,r]=t;return nUe({type:e,content:r})}else if(GBe(t)){let{role:e,...r}=t;return nUe({...r,type:e})}else return nUe(t)}function Ll(t,e="Human",r="AI"){let n=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=r;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o.type}`);let a=o.name?`${o.name}, `:"",s=o.text,u=`${i}: ${a}${s}`;if(o.type==="ai"){let l=o;l.tool_calls&&l.tool_calls.length>0?u+=JSON.stringify(l.tool_calls):l.additional_kwargs&&"function_call"in l.additional_kwargs&&(u+=JSON.stringify(l.additional_kwargs.function_call))}n.push(u)}return n.join(`
|
||
|
|
`)}function $pe(t){let e=t._getType();if(e==="human")return new BT({...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 Hr({...r})}else{if(e==="system")return new UT({...t});if(e==="function")return new qT({...t});if(hy.isInstance(t))return new kT({...t});throw new Error("Unknown message type.")}}function rUe(t){let e=t.reduce((o,i)=>{let a=o.findIndex(([s])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===s.id&&i.index===s.index:"id"in i&&i.id?i.id===s.id:"index"in i&&i.index!==void 0?i.index===s.index:!1);return a!==-1?o[a].push(i):o.push([i]),o},[]),r=[],n=[];for(let o of e){let i=null,a=o[0]?.name??"",s=o.map(c=>c.args||"").join("").trim(),u=s.length?s:"{}",l=o[0]?.id;try{if(i=L6(u),!l||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");r.push({name:a,args:i,id:l,type:"tool_call"})}catch{n.push({name:a,args:u,id:l,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}var oUe,TC=v(()=>{F6();xpe();CQ();my();k6();mS();RQ();Ape();LL();Dpe();IQ();oUe=t=>t()});function fxt(){return iUe===void 0&&(iUe={library:"langchain-js",runtime:sUe()}),iUe}function un(t){try{return typeof process<"u"?process.env?.[t]:aUe()?Deno?.env.get(t):void 0}catch{return}}var Ucn,zcn,Vcn,aUe,Hcn,sUe,iUe,su=v(()=>{zo();Ucn=()=>typeof window<"u"&&typeof window.document<"u",zcn=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Vcn=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),aUe=()=>typeof Deno<"u",Hcn=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!aUe(),sUe=()=>{let t;return Ucn()?t="browser":Hcn()?t="node":zcn()?t="webworker":Vcn()?t="jsdom":aUe()?t="deno":t="other",t}});function uUe(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Wcn,q6,pxt,AQ=v(()=>{zo();DL();su();y_();Wcn=class{};q6=class extends Wcn{constructor(e){super();x(this,"lc_serializable",!1);x(this,"lc_kwargs");x(this,"ignoreLLM",!1);x(this,"ignoreChain",!1);x(this,"ignoreAgent",!1);x(this,"ignoreRetriever",!1);x(this,"ignoreCustomEvent",!1);x(this,"raiseError",!1);x(this,"awaitHandlers",un("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,LBe(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return b_.prototype.toJSON.call(this)}toJSONNotImplemented(){return b_.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class r extends q6{constructor(){super();x(this,"name",FT());Object.assign(this,e)}}return new r}},pxt=t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"}});var mxt,hxt=v(()=>{mxt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function Jcn(t){return typeof t=="string"&&mxt.test(t)}var gxt,yxt=v(()=>{hxt();gxt=Jcn});function Kcn(t){if(!gxt(t))throw TypeError("Invalid UUID");var e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]
|
||
|
|
Context: ${e}`:""}`),Sme("[Unserializable]");td("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
||
|
|
Context: ${e}`:""}`),typeof o>"u"&&(o=nhn()),xze(t,"",0,[],void 0,0,o);let a;try{W6.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,ihn(r),n)}catch{return Sme("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Cme.length!==0;){let s=Cme.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return Sme(a)}}function Cze(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),Cme.push([n,r,e,o])):W6.push([e,r,t]):(n[r]=t,Cme.push([n,r,e]))}function xze(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){Cze(thn,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Cze(LEt,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Cze(LEt,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)xze(t[s],s,s,n,t,i,a);else{t=FEt(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];xze(t[l],l,s,n,t,i,a)}}n.pop()}}function ihn(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(W6.length>0)for(var n=0;n<W6.length;n++){var o=W6[n];if(o[1]===e&&o[0]===r){r=o[2],W6.splice(n,1);break}}return t.call(this,e,r)}}var LEt,thn,Cme,W6,rhn,kEt=v(()=>{NN();LEt="[...]",thn={result:"[Circular]"},Cme=[],W6=[],rhn=new TextEncoder});function qEt(t,e,r){if(r)return t;let n=Qpe(),o=e??AUe(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...a}},t}async function uhn(t){let e=[];for await(let r of t)e.push(r);return e}function xme(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function BEt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function zEt(t){return"dataset_id"in t||"dataset_name"in t}var ahn,shn,lhn,chn,VEt,dhn,fhn,UEt,Tze,Cz,EUe=v(()=>{qpe();MTt();qUe();zTt();VTt();NN();Ype();Kpe();Bpe();DEt();Sze();OUe();vUe();kEt();ahn=t=>{let e=t?.toString()??td("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},shn=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};lhn=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};chn=24*1024*1024,VEt=1024*1024*1024,dhn=1e4,fhn=100,UEt="https://api.smith.langchain.com",Tze=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??VEt}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=w_(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),r(),n):(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({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),o+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),o+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},Cz=class t{get _fetch(){ret
|
||
|
|
=== LangSmith Server Configuration ===
|
||
|
|
`+JSON.stringify(r,null,2)+`
|
||
|
|
`),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(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}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(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=tme(),r=ETt();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=qEt(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let s=w_(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Dr(u,"create run",!0),u})}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(w_(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),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Dr(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(let d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;let l=[],c=[];for(let[d,f]of[["post",i],["patch",
|
||
|
|
`])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
|
||
|
|
`,`Content-Type: ${a.payload.type}\r
|
||
|
|
\r
|
||
|
|
`])),n.push(a.payload),n.push(new Blob([`\r
|
||
|
|
`]));return n.push(new Blob([`--${r}--\r
|
||
|
|
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=async s=>{typeof s=="string"?i.enqueue(n.encode(s)):i.enqueue(s)};for(let s of e){await a(`--${r}\r
|
||
|
|
`),await a(`Content-Disposition: form-data; name="${s.name}"\r
|
||
|
|
`),await a(`Content-Type: ${s.payload.type}\r
|
||
|
|
\r
|
||
|
|
`);let l=s.payload.stream().getReader();try{let c;for(;!(c=await l.read()).done;)i.enqueue(c.value)}finally{l.releaseLock()}await a(`\r
|
||
|
|
`)}await a(`--${r}--\r
|
||
|
|
`),i.close()}})}async _sendMultipartRequest(e,r,n){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),a=()=>this._createMultipartStream(e,o),s=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await u(),c={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};n?.apiKey!==void 0&&(c["x-api-key"]=n.apiKey);let d=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(d=l.pipeThrough(new CompressionStream("gzip")),c["Content-Encoding"]="gzip");let f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:c,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Dr(f,"Failed to send multipart request",!0),f});try{let u,l=!1;iTt()&&!this.multipartStreamingDisabled&&IUe()!=="bun"?(l=!0,u=await s(a)):u=await s(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==UEt&&(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,u=await s(i))}catch(u){if(wze(u))throw u;console.warn(`${u.message.trim()}
|
||
|
|
|
||
|
|
Context: ${r}`)}}async updateRun(e,r,n){No(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),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=w_(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Dr(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){No(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:td("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 uhn(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(o[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:y,limit:g,select:b,order:_}=e,w=[];if(r&&(w=Array.isArray(r)?r:[r]),n){let P=Array.isArray(n)?n:[n],R=await Promise.all(P.map(I=>this.readProject({projectName:I}).then(A=>A.id)));w.push(...R)}let T=["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"],O={session:w.length?w:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:y,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:b||T,is_root:l,order:_};O.select.includes("child_run_ids")&&wz("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let E=0;for await(let P of this._getCursorPaginatedList("/runs/query",O))if(g){if(E>=g)break;if(P.length+E>g){yield*P.slice(0,g-E);break}E+=P.length,yield*P}else yield*P}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:o,filter:i,startTime:a,endTime:s,limit:u,offset:l}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:o,filter:i,start_time:a?a.toISOString():null,end_time:s?s.toISOString():null,limit:Number(u)||100},f=Number(l)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},y
|
||
|
|
Status: ${i.status}
|
||
|
|
Message: ${Array.isArray(a.detail)?a.detail.join(`
|
||
|
|
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=JSON.stringify(c);return await(await this.caller.call(async()=>{let m=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await Dr(m,"create project"),m})).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=JSON.stringify({name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Dr(f,"update project"),f})).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)No(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(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Dr(a,"has project"),a});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)No(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,includeStats:a,datasetVersion:s,referenceFree:u,metadata:l}={}){let c=new URLSearchParams;if(e!==void 0)for(let d of e)c.append("id",d);if(r!==void 0&&c.append("name",r),n!==void 0&&c.append("name_contains",n),o!==void 0)c.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});c.append("reference_dataset",d.id)}a!==void 0&&c.append("include_stats",a.toString()),s!==void 0&&c.append("dataset_version",s),u!==void 0&&c.append("reference_free",u.toString()),l!==void 0&&c.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",c))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectNa
|
||
|
|
`).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;No(i);let a=JSON.stringify(o);return await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Dr(u,"update dataset"),u})).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;No(a);let s=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Dr(u,"update dataset tags",!0),u})}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)No(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Dr(i,`delete ${n}`,!0),i})}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),No(o);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Dr(u,"index dataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),No(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await Dr(l,"fetch similar examples"),l})).json()).examples}async createExample(e,r,n){if(zEt(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;zEt(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]??vz())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let b=e,_=b[0].dataset_id,w=b[0].dat
|
||
|
|
|
||
|
|
Current tenant: ${n.tenant_handle}
|
||
|
|
|
||
|
|
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Dr(o,"get latest commit hash"),o})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=jN(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Dr(u,`${r?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[r,n,o]=jN(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]=jN(e),a=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return s?.status===404?null:(await Dr(s,"get prompt"),s)}))?.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
|
||
|
|
|
||
|
|
creating a LangChain Hub handle.
|
||
|
|
You can add a handle by creating a public prompt at:
|
||
|
|
|
||
|
|
https://smith.langchain.com/prompts`);let[o,i,a]=jN(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=JSON.stringify(s),l=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await Dr(d,"create prompt"),d}),{repo:c}=await l.json();return c}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]=jN(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=JSON.stringify(u),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Dr(f,"create commit"),f})).json();return this._getPromptUrl(`${o}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())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,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=w_(u,`Serializing body for example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=w_(a.inputs,`Serializing inputs for example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=w_(a.outputs,`Serializing outputs whle updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${s}.attachment.${d}`,h)}if(a.attachments_operations){let d=w_(a.attachments_operations,`Serializing attachments while updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}let o=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await Dr(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())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 i of r){let a=(i.id??vz()).toString(),s={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},u=w_(s,`Serializing body for uploaded example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(n.append(a,l),i.inputs){let c=w_(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.inputs`,d)}if(i.outputs){let c=w_(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.outputs`,d)}if(i.attachme
|
||
|
|
|
||
|
|
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:n}=Pze(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.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=r,o._serialized_start_time=n),this.usesRunTreeMap){let a=Rze(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,l){let c=this._getExecutionOrder(o),d=Date.now(),f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:r,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:a?{...l,metadata:a}:{...l},tags:i||[]};return this._addRunToRunMap(f)}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=Mze(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Mze(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=Mze(i.inputs,"input")),await this.onChainError?.(a),await
|
||
|
|
|
||
|
|
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Mme(t){return typeof t=="function"&&"langsmith:traceable"in t}var Lze,$ze,xhn,Fze,Thn,NPi,sPt=v(()=>{Lze=class{getStore(){}run(e,r){return r()}},$ze=Symbol.for("ls:tracing_async_local_storage"),xhn=new Lze,Fze=class{getInstance(){return globalThis[$ze]??xhn}initializeGlobalInstance(e){globalThis[$ze]===void 0&&(globalThis[$ze]=e)}},Thn=new Fze;NPi=Symbol.for("langsmith:traceable:root")});var kze=v(()=>{sPt()});function Ohn(t){let e;for(let r of t)for(let n of r)uo.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=MQ(e,n.message.usage_metadata));return e}var qze,lPt=v(()=>{zo();Rpe();mS();Tz();jze();Eme();Pme();kze();qze=class uPt extends KT{constructor(r={}){super(r);x(this,"name","langchain_tracer");x(this,"projectName");x(this,"exampleId");x(this,"client");x(this,"replicas");x(this,"usesRunTreeMap",!0);let{exampleId:n,projectName:o,client:i,replicas:a}=r;this.projectName=o??DQ(),this.replicas=a,this.exampleId=n,this.client=i??Dze();let s=uPt.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(r){}async onRunCreate(r){r.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(r.id)?.postRun()}async onRunUpdate(r){let n=this.getRunTreeWithTracingConfig(r.id);r.extra?.lc_defers_inputs?await n?.postRun():await n?.patchRun()}onLLMEnd(r){let n=r.outputs;if(n?.generations){let o=Ohn(n.generations);if(o!==void 0){r.extra=r.extra??{};let i=r.extra.metadata??{};i.usage_metadata=o,r.extra.metadata=i}}}getRun(r){return this.runTreeMap.get(r)}updateFromRunTree(r){this.runTreeMap.set(r.id,r);let n=r,o=new Set;for(;n.parent_run&&!(o.has(n.id)||(o.add(n.id),!n.parent_run));)n=n.parent_run;o.clear();let i=[n];for(;i.length>0;){let a=i.shift();!a||o.has(a.id)||(o.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=r.client??this.client,this.replicas=r.replicas??this.replicas,this.projectName=r.project_name??this.projectName,this.exampleId=r.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(r){let n=this.runTreeMap.get(r);if(n)return new PC({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return aPt(!0)}catch{return}}}});var dPt=S((JPi,Ime)=>{"use strict";var Ehn=WUe(),Rme=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},cPt=(t,e,r)=>new Promise((n,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(u){o(u)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,s=r instanceof Error?r:new Rme(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);Ehn(t.then(n,o),()=>{clearTimeout(i)})});Ime.exports=cPt;Ime.exports.default=cPt;Ime.exports.TimeoutError=Rme});var fPt=S(Bze=>{"use strict";Object.defineProperty(Bze,"__esModule",{value:!0});function Phn(t,e,r){let n=0,o=t.length;for(;o>0;){let i=o/2|0,a=n+i;r(t[a],e)<=0?(n=++a,o-=i+1):o=i}return n}Bze.default=Phn});var pPt=S(zze=>{"use strict";Object.defineProperty(zze,"__esModule",{value:!0});var Mhn=fPt(),Uze=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let o=Mhn.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(o,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};zze.default=Uze});var Wze=S(Hze=>{"use strict";Object.defineProperty(Hze,"__esModule",{value:!0});var Rhn=HUe(),mPt=dPt(),Ihn=pPt(),Ame=()=>{},Ahn=new mPt.TimeoutError,Vze=class extends Rhn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Ame,this._resolveIdle=Ame,e=Objec
|
||
|
|
`)}var zhn,Bme,Ume=v(()=>{zhn=Object.prototype.hasOwnProperty;Bme=class extends Error{constructor(t,e,r,n,o){super(xPt(t,{name:e,index:r,operation:n,tree:o})),this.name=e,this.index=r,this.operation=n,this.tree=o,Object.setPrototypeOf(this,new.target.prototype),this.message=xPt(t,{name:e,index:r,operation:n,tree:o})}}});function zme(t,e){if(e=="")return t;var r={op:"_get",path:e};return Mz(t,r),r.value}function Mz(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Vme(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=zme(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=GQ(t,e.value),a.test===!1)throw new Dc("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 Dc("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=xb(t));let a=(e.path||"").split("/"),s=t,u=1,l=a.length,c,d,f;for(typeof r=="function"?f=r:f=Vme;;){if(d=a[u],d&&d.indexOf("~")!=-1&&(d=qme(d)),o&&(d=="__proto__"||d=="prototype"&&u>0&&a[u-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&&c===void 0&&(s[d]===void 0?c=a.slice(0,u).join("/"):u==l-1&&(c=e.path),c!==void 0&&f(e,0,t,c)),u++,Array.isArray(s)){if(d==="-")d=s.length;else{if(r&&!kme(d))throw new Dc("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);kme(d)&&(d=~~d)}if(u>=l){if(r&&e.op==="add"&&d>s.length)throw new Dc("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let p=Hhn[e.op].call(e,s,d,t);if(p.test===!1)throw new Dc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}}else if(u>=l){let p=X6[e.op].call(e,s,d,t);if(p.test===!1)throw new Dc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}if(s=s[d],r&&u<l&&(!s||typeof s!="object"))throw new Dc("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Rz(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Dc("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=xb(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=Mz(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Whn(t,e,r){let n=Mz(t,e);if(n.test===!1)throw new Dc("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Vme(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Dc("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(X6[t.op]){if(typeof t.path!="string")throw new Dc("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Dc('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 Dc("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)throw new Dc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&$me(t.value))throw new Dc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,i=n.split("/").length;if(o!==i+1&&o!==i)throw new Dc("Cannot pe
|
||
|
|
`)}var zPt,uee,tJ,b4e=v(()=>{Y6();zn();zPt=(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,s4e,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},uee=Te("$ZodError",zPt),tJ=Te("$ZodError",zPt,{Parent:Error})});var Zme,Dz,Yme,jz,Qme,_4e,ehe,v4e,the=v(()=>{Y6();b4e();zn();Zme=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 YT;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>Xv(u,i,vd())));throw Xme(s,o?.callee),s}return a.value},Dz=Zme(tJ),Yme=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=>Xv(u,i,vd())));throw Xme(s,o?.callee),s}return a.value},jz=Yme(tJ),Qme=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 YT;return i.issues.length?{success:!1,error:new(t??uee)(i.issues.map(a=>Xv(a,o,vd())))}:{success:!0,data:i.value}},_4e=Qme(tJ),ehe=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?{success:!1,error:new t(i.issues.map(a=>Xv(a,o,vd())))}:{success:!0,data:i.value}},v4e=ehe(tJ)});var Lz={};En(Lz,{_emoji:()=>HPt,base64:()=>j4e,base64url:()=>rhe,bigint:()=>U4e,boolean:()=>H4e,browserEmail:()=>Mgn,cidrv4:()=>N4e,cidrv6:()=>D4e,cuid:()=>w4e,cuid2:()=>S4e,date:()=>F4e,datetime:()=>q4e,domain:()=>Rgn,duration:()=>E4e,e164:()=>L4e,email:()=>M4e,emoji:()=>R4e,extendedDuration:()=>Sgn,guid:()=>P4e,hostname:()=>$4e,html5Email:()=>Ogn,integer:()=>z4e,ipv4:()=>I4e,ipv6:()=>A4e,ksuid:()=>T4e,lowercase:()=>K4e,nanoid:()=>O4e,null:()=>W4e,number:()=>V4e,rfc5322Email:()=>Egn,string:()=>B4e,time:()=>k4e,ulid:()=>C4e,undefined:()=>J4e,unicodeEmail:()=>Pgn,uppercase:()=>G4e,uuid:()=>$z,uuid4:()=>Cgn,uuid6:()=>xgn,uuid7:()=>Tgn,xid:()=>x4e});function R4e(){return new RegExp(HPt,"u")}function JPt(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function k4e(t){return new RegExp(`^${JPt(t)}$`)}function q4e(t){let e=JPt({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${WPt}T(?:${n})$`)}var w4e,S4e,C4e,x4e,T4e,O4e,E4e,Sgn,P4e,$z,Cgn,xgn,Tgn,M4e,Ogn,Egn,Pgn,Mgn,HPt,I4e,A4e,N4e,D4e,j4e,rhe,$4e,Rgn,L4e,WPt,F4e,B4e,U4e,z4e,V4e,H4e,W4e,J4e,K4e,G4e,nhe=v(()=>{w4e=/^[cC][^\s-]{8,}$/,S4e=/^[0-9a-z]+$/,C4e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,x4e=/^[0-9a-vA-V]{20}$/,T4e=/^[A-Za-z0-9]{27}$/,O4e=/^[a-zA-Z0-9_-]{21}$/,E4e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sgn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,P4e=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,$z=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Cgn=$z(4),xgn=$z(6),Tgn=$z(7),M4e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ogn=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Egn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0
|
||
|
|
`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
|
||
|
|
`))}}});var h2e,g2e=v(()=>{h2e={major:4,minor:0,patch:0}});function L2e(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function uMt(t){if(!rhe.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return L2e(r)}function lMt(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function ZPt(t,e,r){t.issues.length&&e.issues.push(...O_(r,t.issues)),e.value[r]=t.value}function she(t,e,r){t.issues.length&&e.issues.push(...O_(r,t.issues)),e.value[r]=t.value}function YPt(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...O_(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function QPt(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>Xv(i,n,vd())))}),e}function y2e(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(eJ(t)&&eJ(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=y2e(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=y2e(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function eMt(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Nz(t))return t;let n=y2e(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function uhe(t,e,r){t.issues.length&&e.issues.push(...O_(r,t.issues)),e.value[r]=t.value}function tMt(t,e,r,n,o,i,a){t.issues.length&&(iee.has(typeof n)?r.issues.push(...O_(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(s=>Xv(s,a,vd()))})),e.issues.length&&(iee.has(typeof n)?r.issues.push(...O_(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(s=>Xv(s,a,vd()))})),r.value.set(t.value,e.value)}function rMt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function nMt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function oMt(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function iMt(t,e,r){return Nz(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function aMt(t){return t.value=Object.freeze(t.value),t}function sMt(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(h4e(o))}}var lo,Fz,Nu,b2e,_2e,v2e,w2e,S2e,C2e,x2e,T2e,O2e,E2e,P2e,M2e,R2e,I2e,A2e,N2e,D2e,j2e,$2e,F2e,k2e,q2e,B2e,U2e,lhe,z2e,fee,che,V2e,H2e,W2e,J2e,K2e,kz,pee,G2e,X2e,mee,Z2e,dhe,Y2e,Q2e,qz,eVe,tVe,rVe,nVe,oVe,iVe,hee,fhe,aVe,sVe,uVe,lVe,cVe,dVe,fVe,gee,pVe,mVe,hVe,gVe,yVe,yee=v(()=>{ahe();Y6();m2e();the();nhe();zn();g2e();zn();lo=Te("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=h2e;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,s)=>{let u=Nz(i),l;for(let c of a){if(c._zod.def.when){if(!c._zod.def.when(i))continue}else if(u)continue;let d=i.issues.length,f=c._zod.check(i);if(f instanceof Promise&&s?.async===!1)throw new YT;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{awa
|
||
|
|
if (${_}.issues.length) {
|
||
|
|
if (input[${w}] === undefined) {
|
||
|
|
if (${w} in input) {
|
||
|
|
newResult[${w}] = undefined;
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
payload.issues = payload.issues.concat(
|
||
|
|
${_}.issues.map((iss) => ({
|
||
|
|
...iss,
|
||
|
|
path: iss.path ? [${w}, ...iss.path] : [${w}],
|
||
|
|
}))
|
||
|
|
);
|
||
|
|
}
|
||
|
|
} else if (${_}.value === undefined) {
|
||
|
|
if (${w} in input) newResult[${w}] = undefined;
|
||
|
|
} else {
|
||
|
|
newResult[${w}] = ${_}.value;
|
||
|
|
}
|
||
|
|
`)}else{let _=h[b];f.write(`const ${_} = ${m(b)};`),f.write(`
|
||
|
|
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
||
|
|
...iss,
|
||
|
|
path: iss.path ? [${Az(b)}, ...iss.path] : [${Az(b)}]
|
||
|
|
})));`),f.write(`newResult[${Az(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let g=f.compile();return(b,_)=>g(d,b,_)},o,i=Q6,a=!eee.jitless,u=a&&c4e.value,l=e.catchall,c;t._zod.parse=(d,f)=>{c??(c=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(a&&u&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let _=c.shape;for(let w of c.keys){let T=_[w],O=T._zod.run({value:p[w],issues:[]},f),E=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(P=>E?YPt(P,d,w,p):she(P,d,w))):E?YPt(O,d,w,p):she(O,d,w)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=c.keySet,g=l._zod,b=g.def.type;for(let _ of Object.keys(p)){if(y.has(_))continue;if(b==="never"){h.push(_);continue}let w=g.run({value:p[_],issues:[]},f);w instanceof Promise?m.push(w.then(T=>she(T,d,_))):she(w,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});dhe=Te("$ZodUnion",(t,e)=>{lo.init(t,e),Bs(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Bs(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Bs(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Bs(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>oee(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,i=[];for(let a of e.options){let s=a._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)i.push(s),o=!0;else{if(s.issues.length===0)return s;i.push(s)}}return o?Promise.all(i).then(a=>QPt(a,r,t,n)):QPt(i,r,t,n)}}),Y2e=Te("$ZodDiscriminatedUnion",(t,e)=>{dhe.init(t,e);let r=t._zod.parse;Bs(t._zod,"propValues",()=>{let o={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[s,u]of Object.entries(a)){o[s]||(o[s]=new Set);for(let l of u)o[s].add(l)}}return o});let n=nee(()=>{let o=e.options,i=new Map;for(let a of o){let s=a._zod.propValues[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let u of s){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,a)}}return i});t._zod.parse=(o,i)=>{let a=o.value;if(!Q6(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let s=n.value.get(a?.[e.discriminator]);return s?s._zod.run(o,i):e.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),o)}}),Q2e=Te("$ZodIntersection",(t,e)=>{lo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>eMt(r,u,l)):eMt(r,i,a)}});qz=Te("$ZodTuple",(t,e)=>{lo.init(t,e);let r=e.items,n=r.length-[...r].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let s=[];if(!e.rest){let l=a.length>r.length,c=a.length<n-1;if(l||c)return o.issues.push({input:a,inst:t,origin:"array",...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),o}let u=-1;for(let l of r){if(u++,u>=a.length&&u>=n)continue;let c=l._zod.run({value:a[u],issues:[]},i);c instanceof Promise?s.push(c.then(d=>uhe(d,o,u))):uhe(c,o,u)}if(e.rest){let l=a.slice(r.length);for(let c of l){u++;let d=e.rest._zod.run({value:c,issues:[]},i);d instanceof Promise?s.push(d.then(f=>uhe(f,o,u))):uhe(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});eVe=Te("$ZodRecord",(t,e)=>{lo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!eJ(o))return r.issues.p
|
||
|
|
|
||
|
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let c of this.seen.entries()){let d=c[1];if(e===c[0]){a(c);continue}if(n.external){let p=n.external.registry.get(c[0])?.id;if(e!==c[0]&&p){a(c);continue}}if(this.metadataRegistry.get(c[0])?.id){a(c);continue}if(d.cycle){a(c);continue}if(d.count>1&&n.reused==="ref"){a(c);continue}}let s=(c,d)=>{let f=this.seen.get(c),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){s(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(y)):(Object.assign(p,y),Object.assign(p,m))}f.isParent||this.override({zodSchema:c,jsonSchema:p,path:f.path??[]})};for(let c of[...this.seen.entries()].reverse())s(c[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let c=n.external.registry.get(e)?.id;if(!c)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(c)}Object.assign(u,o.def);let l=n.external?.defs??{};for(let c of this.seen.entries()){let d=c[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}});var LRt={};var FRt=v(()=>{});var UN={};En(UN,{$ZodAny:()=>K2e,$ZodArray:()=>mee,$ZodAsyncError:()=>YT,$ZodBase64:()=>F2e,$ZodBase64URL:()=>k2e,$ZodBigInt:()=>che,$ZodBigIntFormat:()=>V2e,$ZodBoolean:()=>fee,$ZodCIDRv4:()=>j2e,$ZodCIDRv6:()=>$2e,$ZodCUID:()=>x2e,$ZodCUID2:()=>T2e,$ZodCatch:()=>dVe,$ZodCheck:()=>hc,$ZodCheckBigIntFormat:()=>Y4e,$ZodCheckEndsWith:()=>c2e,$ZodCheckGreaterThan:()=>ihe,$ZodCheckIncludes:()=>u2e,$ZodCheckLengthEquals:()=>o2e,$ZodCheckLessThan:()=>ohe,$ZodCheckLowerCase:()=>a2e,$ZodCheckMaxLength:()=>r2e,$ZodCheckMaxSize:()=>Q4e,$ZodCheckMimeType:()=>f2e,$ZodCheckMinLength:()=>n2e,$ZodCheckMinSize:()=>e2e,$ZodCheckMultipleOf:()=>X4e,$ZodCheckNumberFormat:()=>Z4e,$ZodCheckOverwrite:()=>p2e,$ZodCheckProperty:()=>d2e,$ZodCheckRegex:()=>i2e,$ZodCheckSizeEquals:()=>t2e,$ZodCheckStartsWith:()=>l2e,$ZodCheckStringFormat:()=>rJ,$ZodCheckUpperCase:()=>s2e,$ZodCustom:()=>yVe,$ZodCustomStringFormat:()=>U2e,$ZodDate:()=>X2e,$ZodDefault:()=>sVe,$ZodDiscriminatedUnion:()=>Y2e,$ZodE164:()=>q2e,$ZodEmail:()=>v2e,$ZodEmoji:()=>S2e,$ZodEnum:()=>nVe,$ZodError:()=>uee,$ZodFile:()=>iVe,$ZodFunction:()=>$he,$ZodGUID:()=>b2e,$ZodIPv4:()=>N2e,$ZodIPv6:()=>D2e,$ZodISODate:()=>R2e,$ZodISODateTime:()=>M2e,$ZodISODuration:()=>A2e,$ZodISOTime:()=>I2e,$ZodIntersection:()=>Q2e,$ZodJWT:()=>B2e,$ZodKSUID:()=>P2e,$ZodLazy:()=>gVe,$ZodLiteral:()=>oVe,$ZodMap:()=>tVe,$ZodNaN:()=>fVe,$ZodNanoID:()=>C2e,$ZodNever:()=>pee,$ZodNonOptional:()=>lVe,$ZodNull:()=>J2e,$ZodNullable:()=>aVe,$ZodNumber:()=>lhe,$ZodNumberFormat:()=>z2e,$ZodObject:()=>Z2e,$ZodOptional:()=>fhe,$ZodPipe:()=>gee,$ZodPrefault:()=>uVe,$ZodPromise:()=>hVe,$ZodReadonly:()=>pVe,$ZodRealError:()=>tJ,$ZodRecord:()=>eVe,$ZodRegistry:()=>nJ,$ZodSet:()=>rVe,$ZodString:()=>Fz,$ZodStringFormat:()=>Nu,$ZodSuccess:()=>cVe,$ZodSymbol:()=>H2e,$ZodTemplateLiteral:()=>mVe,$ZodTransform:()=>hee,$ZodTuple:()=>qz,$ZodType:()=>lo,$ZodULID:()=>O2e,$ZodURL:()=>w2e,$ZodUUID:()=>_2e,$ZodUndefined:()=>W2e,$ZodUnion:()=>dhe,$ZodUnknown:()=>kz,$ZodVoid:()=>G2e,$ZodXID:()=>E2e,$brand:()=>o4e,$constructor:()=>Te,$input:()=>wVe,$output:()=>vVe,Doc:()=>dee,JSONSchema:()=>LRt,JSONSchemaGenerator:()=>Dee,NEVER:()=>n4e,TimePrecision:()=>TVe,_any:()=>WVe,_array:()=>Nee,_base64:()=>Ahe,_base64url:()=>Nhe,_bigint:()=>kVe,_boolean:()=>LVe,_catch:()=>Dyn,_cidrv4:()=>Rhe,_cidrv6:()=>Ihe,_coercedBigint:()=>qVe,_coercedBoolean:()=>FVe,_coercedDate:()=>GVe,_coercedNumber:()=>IVe,_coercedString:()=>xVe,_cuid:()=>Che,_cuid2:()=>xhe,_custom:()=>oHe,_date:()=>KVe,_default:()=>Iyn,_discriminatedUnion:()=>vyn,_e164:()=>Dhe,_email:()=>hhe,_emoji:()=>whe,_endsWith:()=>Eee,_enum:(
|
||
|
|
`;return e}function BRt(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
|
||
|
|
graph TD;
|
||
|
|
`:`graph TD;
|
||
|
|
`;if(a){let m="default",h={[m]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[y,g]of Object.entries(t)){let b=g.name.split(":").pop()??"",_=Uyn.some(T=>b.startsWith(T)&&b.endsWith(T))?`<p>${b}</p>`:b;Object.keys(g.metadata??{}).length&&(_+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([T,O])=>`${T} = ${O}`).join(`
|
||
|
|
`)}</em></small>`);let w=(h[y]??h[m]).replace("{0}",pHe(y)).replace("{1}",_);l+=` ${w}
|
||
|
|
`}}let c={};for(let m of e){let h=m.source.split(":"),y=m.target.split(":"),g=h.filter((b,_)=>b===y[_]).join(":");c[g]||(c[g]=[]),c[g].push(m)}let d=new Set;function f(m){return[...m].sort((h,y)=>h.split(":").length-y.split(":").length)}function p(m,h){let y=m.length===1&&m[0].source===m[0].target;if(h&&!y){let b=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${b}' at '${h} -- 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(h),l+=` subgraph ${b}
|
||
|
|
`}let g=f(Object.keys(c).filter(b=>b.startsWith(`${h}:`)&&b!==h&&b.split(":").length===h.split(":").length+1));for(let b of g)p(c[b],b);for(let b of m){let{source:_,target:w,data:T,conditional:O}=b,E="";if(T!==void 0){let P=T,R=P.split(" ");R.length>u&&(P=Array.from({length:Math.ceil(R.length/u)},(I,A)=>R.slice(A*u,(A+1)*u).join(" ")).join(" <br> ")),E=O?` -. ${P} .-> `:` -- ${P} --> `}else E=O?" -.-> ":" --> ";l+=` ${pHe(_)}${E}${pHe(w)};
|
||
|
|
`}h&&!y&&(l+=` end
|
||
|
|
`)}p(c[""]??[],"");for(let m in c)!m.includes(":")&&m!==""&&p(c[m],m);return a&&(l+=zyn(i??{})),l}async function URt(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",o=UPt(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let i=`https://mermaid.ink/img/${o}?bgColor=${r}&type=${n}`,a=await fetch(i);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
|
||
|
|
`));return await a.blob()}var Uyn,zRt=v(()=>{Gme();Uyn=["*","_","`"]});var HRt,VRt,WRt,Lhe=v(()=>{HRt=Symbol("Let zodToJsonSchema decide on which parser to use"),VRt={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},WRt=t=>typeof t=="string"?{...VRt,name:t}:{...VRt,...t}});var JRt,mHe=v(()=>{Lhe();JRt=t=>{let e=WRt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},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}]))}}});var Fhe,khe=v(()=>{Fhe=(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("/")}});function Fl(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Fhe(e,t.currentPath):e.join("/")}}var _S=v(()=>{khe()});function hHe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Wi(t,e,r,n,o){t[e]=r,hHe(t,e,n,o)}var WL=v(()=>{});var Ri,gHe,dr,QT,Lee=v(()=>{(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})(Ri||(Ri={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(gHe||(gHe={}));dr=Ri.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),QT=t=>{switch(typeof t){case"undefined":return dr.undefined;case"string":return dr.string;case"number":return Number.isNaN(t)?dr.nan:dr.number;case"boolean":return dr.boolean;case"function":return dr.function;case"bigint":return dr.bigint;case"symbol":return dr.symbol;case"object":return Array.isArray(t)?dr.array:t===null?dr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?dr.promise:typeof Map<"u"&&t instanceof Map?dr.map:typeof Set<"u"&&t instanceof Set?dr.set:typeof Date<"u"&&t instanceof Date?dr.date:dr.object;default:return dr.unknown}}});var ut,Vyn,P_,qhe=v(()=>{Lee();ut=Ri.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","invalid_intersection_types","not_multiple_of","not_finite"]),Vyn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),P_=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issue
|
||
|
|
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
|
||
|
|
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
|
||
|
|
`:`[${n[u]}\r
|
||
|
|
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var AHe,NC,r_n,Xhe=v(()=>{WL();NC={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:()=>(AHe===void 0&&(AHe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),AHe),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-_]*$/};r_n=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Zhe(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===Ne.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Fn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Fl(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Fn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ne.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ghe(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Ne.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ne.ZodBranded&&t.keyType._def.type._def.typeName===Ne.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Jhe(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Yhe=v(()=>{_S();Khe();Xhe();Sd();rO()});function bIt(t,e){return e.mapStrategy==="record"?Zhe(t,e):{type:"array",maxItems:125,items:{type:"array",items:[Fn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Fl(e),Fn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Fl(e)],minItems:2,maxItems:2}}}var DHe=v(()=>{_S();Yhe();Sd()});function _It(t){let e=t.values,r=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(r.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],e
|
||
|
|
Known schemas:
|
||
|
|
- ${Object.keys(n).join(`
|
||
|
|
- `)}`,new Error(He)}let Rt=`${s}/$ref`,ze=fl(t,Ve,r,n,o,i,a,Rt,u);if(ze.valid||$e.push({instanceLocation:a,keyword:"$ref",keywordLocation:Rt,error:"A subschema had errors."},...ze.errors),r==="4"||r==="7")return{valid:$e.length===0,errors:$e}}if(Array.isArray(m)){let ft=m.length,Ve=!1;for(let Rt=0;Rt<ft;Rt++)if(c===m[Rt]||m[Rt]==="integer"&&c==="number"&&t%1===0&&t===t){Ve=!0;break}Ve||$e.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(c!=="number"||t%1||t!==t)&&$e.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&$e.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?KN(t,h)||$e.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&$e.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),y!==void 0&&(c==="object"||c==="array"?y.some(ft=>KN(t,ft))||$e.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(ft=>t===ft)||$e.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),b!==void 0){let ft=`${s}/not`;fl(t,b,r,n,o,i,a,ft).valid&&$e.push({instanceLocation:a,keyword:"not",keywordLocation:ft,error:'Instance matched "not" schema.'})}let Fr=[];if(_!==void 0){let ft=`${s}/anyOf`,Ve=$e.length,Rt=!1;for(let ze=0;ze<_.length;ze++){let He=_[ze],We=Object.create(u),Jt=fl(t,He,r,n,o,p===!0?i:null,a,`${ft}/${ze}`,We);$e.push(...Jt.errors),Rt=Rt||Jt.valid,Jt.valid&&Fr.push(We)}Rt?$e.length=Ve:$e.splice(Ve,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:ft,error:"Instance does not match any subschemas."})}if(w!==void 0){let ft=`${s}/allOf`,Ve=$e.length,Rt=!0;for(let ze=0;ze<w.length;ze++){let He=w[ze],We=Object.create(u),Jt=fl(t,He,r,n,o,p===!0?i:null,a,`${ft}/${ze}`,We);$e.push(...Jt.errors),Rt=Rt&&Jt.valid,Jt.valid&&Fr.push(We)}Rt?$e.length=Ve:$e.splice(Ve,0,{instanceLocation:a,keyword:"allOf",keywordLocation:ft,error:"Instance does not match every subschema."})}if(T!==void 0){let ft=`${s}/oneOf`,Ve=$e.length,Rt=T.filter((ze,He)=>{let We=Object.create(u),Jt=fl(t,ze,r,n,o,p===!0?i:null,a,`${ft}/${He}`,We);return $e.push(...Jt.errors),Jt.valid&&Fr.push(We),Jt.valid}).length;Rt===1?$e.length=Ve:$e.splice(Ve,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:ft,error:`Instance does not match exactly one subschema (${Rt} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Fr),O!==void 0){let ft=`${s}/if`;if(fl(t,O,r,n,o,i,a,ft,u).valid){if(E!==void 0){let Rt=fl(t,E,r,n,o,i,a,`${s}/then`,u);Rt.valid||$e.push({instanceLocation:a,keyword:"if",keywordLocation:ft,error:'Instance does not match "then" schema.'},...Rt.errors)}}else if(P!==void 0){let Rt=fl(t,P,r,n,o,i,a,`${s}/else`,u);Rt.valid||$e.push({instanceLocation:a,keyword:"if",keywordLocation:ft,error:'Instance does not match "else" schema.'},...Rt.errors)}}if(c==="object"){if(g!==void 0)for(let ze of g)ze in t||$e.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${ze}".`});let ft=Object.keys(t);if(q!==void 0&&ft.length<q&&$e.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${q} properties.`}),Z!==void 0&&ft.length>Z&&$e.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${Z} properties.`}),V!==void 0){let ze=`${s}/propertyNames`;for(let He in t){let We=`${a}/${Yv(He)}`,Jt=fl(He,V,r,n,o,i,We,ze);Jt.valid||$e.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ze,error:`Property name "${He}" does not
|
||
|
|
data: ${JSON.stringify(o)}
|
||
|
|
|
||
|
|
`));n.enqueue(e.encode(`event: end
|
||
|
|
|
||
|
|
`)),n.close()}});return T_.fromReadableStream(r)}var GIt=v(()=>{XT()});function nWe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function nge(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function ZIt(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function YIt(t,e){try{let r=await t.next();for(;!r.done;)await e?.(r.value),r=await t.next();return r.value}finally{await t.return?.(void 0)}}function*oWe(t,e){for(;;){let{value:r,done:n}=yg.runWithConfig(x_(t),e.next.bind(e),!0);if(n)break;yield r}}async function*oge(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await yg.runWithConfig(x_(t),r.next.bind(e),!0);if(o)break;yield n}}var XIt,iWe=v(()=>{Oz();Ez();GT();XIt=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Om(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function V_n(t){if(Mme(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function XN(t){if(typeof t=="function")return new YN({func:t});if(Ti.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=XN(n);return new hJ({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
||
|
|
Instead got an unsupported type.`)}function H_n(t,e){let r=e.name??t.getName(),n=e.description??Kz(e.schema);return $ee(e.schema)?new aWe({name:r,description:n,schema:Ae.object({input:Ae.string()}).transform(o=>o.input),bound:t}):new aWe({name:r,description:n,schema:e.schema,bound:t})}var Ti,ZN,sWe,gc,hJ,z_n,YN,nAt,ige,oAt,aWe,_g=v(()=>{xpe();DL();Oz();Ez();GT();G6();XT();IPt();$Pt();t4e();Iz();qPt();Gme();zN();JIt();GIt();iWe();y_();kze();rO();Ti=class extends b_{constructor(){super(...arguments);x(this,"lc_runnable",!0);x(this,"name")}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}withRetry(e){return new sWe({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new ZN({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new nAt({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(vi);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)=>vi(i===0?e:n))}return Array.from({length:r},()=>vi(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=new IC({maxConcurrency:o[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:s=>{throw s}}),a=e.map((s,u)=>i.call(async()=>{try{return await this.invoke(s,o[u])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(a)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=vi(r),o=new Pz({generator:this._streamIterator(e,n),config:n});return await o.setup,T_.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=vi(e):r=vi({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=vi(n),i=await(await C_(o))?.handleChainStart(this.toJSON(),Om(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let a;try{a=await MC(e.call(this,r,o,i),n?.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(Om(a,"output")),a}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(C_)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),Om(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{u=await MC(e.call(this,r,i,s,o),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(Om(u,"output")))),u}_concatOutputChunks(e,r){return RC(e,r)}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=vi(n),l=await C_(u),c=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=c._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await CPt(r.bind(this),d(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName(),void 0,{lc_defers_inputs:!0}),n?.signal,u);delete u.runId,f=p.setup;let m=f?.handlers.find(DPt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let y=f?.handlers.find(RPt);y!==void 0&&f!==void 0&&(h=y.tapOutputIterable(f.runId,h));for await(let g of h)if(yield g,s)if(a===void 0)a=g;else try{a=this._concatOutputChunks(a,g)}catch{a=void 0,s=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:Om(o,"input"
|
||
|
|
|
||
|
|
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
||
|
|
|
||
|
|
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
||
|
|
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
||
|
|
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
||
|
|
|
||
|
|
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
||
|
|
|
||
|
|
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
||
|
|
\`\`\`json
|
||
|
|
${JSON.stringify(Ii(this.schema))}
|
||
|
|
\`\`\`
|
||
|
|
`}async parse(e){try{let r=e.trim(),n=(r.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||r.match(/```json\s*([\s\S]*?)```/)?.[1]||r).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Jz(this.schema,JSON.parse(n))}catch(r){throw new CS(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var lWe=v(()=>{zo();XQ();ZQ();Zze()});var ew,cWe=v(()=>{CQ();ZQ();ZL();lWe();ew=class extends _J{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers"]);x(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,r){return this.diff?super._concatOutputChunks(e,r):r}_diff(e,r){if(r)return e?Hme(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return Cpe(e[0].text)}async parse(e){return Cpe(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}}});var K_n,G_n,bAt=v(()=>{K_n=function(){let t={};t.parser=function(D,N){return new r(D,N)},t.SAXParser=r,t.SAXStream=l,t.createStream=u,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(D,N){if(!(this instanceof r))return new r(D,N);var z=this;o(z),z.q=z.c="",z.bufferCheckPosition=t.MAX_BUFFER_LENGTH,z.opt=N||{},z.opt.lowercase=z.opt.lowercase||z.opt.lowercasetags,z.looseCase=z.opt.lowercase?"toLowerCase":"toUpperCase",z.tags=[],z.closed=z.closedRoot=z.sawRoot=!1,z.tag=z.error=null,z.strict=!!D,z.noscript=!!(D||z.opt.noscript),z.state=P.BEGIN,z.strictEntities=z.opt.strictEntities,z.ENTITIES=z.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),z.attribList=[],z.opt.xmlns&&(z.ns=Object.create(m)),z.trackPosition=z.opt.position!==!1,z.trackPosition&&(z.position=z.line=z.column=0),I(z,"onready")}Object.create||(Object.create=function(D){function N(){}return N.prototype=D,new N}),Object.keys||(Object.keys=function(D){var N=[];for(var z in D)D.hasOwnProperty(z)&&N.push(z);return N});function n(D){for(var N=Math.max(t.MAX_BUFFER_LENGTH,10),z=0,H=0,oe=e.length;H<oe;H++){var Q=D[e[H]].length;if(Q>N)switch(e[H]){case"textNode":B(D);break;case"cdata":A(D,"oncdata",D.cdata),D.cdata="";break;case"script":A(D,"onscript",D.script),D.script="";break;default:q(D,"Max buffer length exceeded: "+e[H])}z=Math.max(z,Q)}D.bufferCheckPosition=t.MAX_BUFFER_LENGTH-z+D.position}function o(D){for(var N=0,z=e.length;N<z;N++)D[e[N]]=""}function i(D){B(D),D.cdata!==""&&(A(D,"oncdata",D.cdata),D.cdata=""),D.script!==""&&(A(D,"onscript",D.script),D.script="")}r.prototype={end:function(){Z(this)},write:ne,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var a=ReadableStream;a||(a=function(){});var s=t.EVENTS.filter(function(D){return D!=="error"&&D!=="end"});function u(D,N){return new l(D,N)}function l(D,N){if(!(this instanceof l))return new l(D,N);a.apply(this),this._parser=new r(D,N),this.writable=!0,this.readable=!0;var z=this;this._parser.onend=function(){z.emit("end")},this._parser.onerror=function(H){z.emit("error",H),z._parser.error=null},this._decoder=null,s.forEach(function(H){Object.defineProperty(z,"on"+H,{get:function(){return z._parser["on"+H]},set:function(oe){if(!oe)return z.removeAllListeners(H),z._parser["on"+H]=oe,oe;z.on(H,oe)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototype.write=function(D){return this._parser.write(D.toString()),this.emit("data",D),!0},l.prototype.end=function(D){return D&&D.length&&this.write(D),this._parser.end(),!0},l.prototype.on=function(D,N){var z=this;return!z._parser["on"+D]&&s.indexOf(D)!==-1&&(z._parser["on"+D]=function(){var H=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);H.splice(0,0,D),z.emit.apply(z,H)
|
||
|
|
`||D==="\r"||D===" "}function w(D){return D==='"'||D==="'"}function T(D){return D===">"||_(D)}function O(D,N){return D.test(N)}function E(D,N){return!O(D,N)}var P=0;t.STATE={BEGIN:P++,BEGIN_WHITESPACE:P++,TEXT:P++,TEXT_ENTITY:P++,OPEN_WAKA:P++,SGML_DECL:P++,SGML_DECL_QUOTED:P++,DOCTYPE:P++,DOCTYPE_QUOTED:P++,DOCTYPE_DTD:P++,DOCTYPE_DTD_QUOTED:P++,COMMENT_STARTING:P++,COMMENT:P++,COMMENT_ENDING:P++,COMMENT_ENDED:P++,CDATA:P++,CDATA_ENDING:P++,CDATA_ENDING_2:P++,PROC_INST:P++,PROC_INST_BODY:P++,PROC_INST_ENDING:P++,OPEN_TAG:P++,OPEN_TAG_SLASH:P++,ATTRIB:P++,ATTRIB_NAME:P++,ATTRIB_NAME_SAW_WHITE:P++,ATTRIB_VALUE:P++,ATTRIB_VALUE_QUOTED:P++,ATTRIB_VALUE_CLOSED:P++,ATTRIB_VALUE_UNQUOTED:P++,ATTRIB_VALUE_ENTITY_Q:P++,ATTRIB_VALUE_ENTITY_U:P++,CLOSE_TAG:P++,CLOSE_TAG_SAW_WHITE:P++,SCRIPT:P++,SCRIPT_ENDING:P++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(D){var N=t.ENTITIES[D],z=typeof N=="number"?String.fromCharCode(N):N;t.ENTITIES[D]=z});for(var R in t.STATE)t.STATE[t.STATE[R]]=R;P=t.STATE;function I(D,N,z){D[N]&&D[N](z)}function A(D,N,z){D.textNode&&B(D),I(D,N,z)}function B(D){D.textNode=k(D.opt,D.textNode),D.textNode&&I(D,"ontext",D.textNode),D.textNode=""}function k(D,N){return D.trim&&(N=N.trim()),D.normalize&&(N=N.replace(/\s+/g," ")),N}function q(D,N){return B(D),D.trackPosition&&(N+=`
|
||
|
|
Line: `+D.line+`
|
||
|
|
Column: `+D.column+`
|
||
|
|
Char: `+D.c),N=new Error(N),D.error=N,I(D,"onerror",N),D}function Z(D){return D.sawRoot&&!D.closedRoot&&V(D,"Unclosed root tag"),D.state!==P.BEGIN&&D.state!==P.BEGIN_WHITESPACE&&D.state!==P.TEXT&&q(D,"Unexpected end"),B(D),D.c="",D.closed=!0,I(D,"onend"),r.call(D,D.strict,D.opt),D}function V(D,N){if(typeof D!="object"||!(D instanceof r))throw new Error("bad call to strictFail");D.strict&&q(D,N)}function Y(D){D.strict||(D.tagName=D.tagName[D.looseCase]());var N=D.tags[D.tags.length-1]||D,z=D.tag={name:D.tagName,attributes:{}};D.opt.xmlns&&(z.ns=N.ns),D.attribList.length=0,A(D,"onopentagstart",z)}function X(D,N){var z=D.indexOf(":")<0?["",D]:D.split(":"),H=z[0],oe=z[1];return N&&D==="xmlns"&&(H="xmlns",oe=""),{prefix:H,local:oe}}function W(D){if(D.strict||(D.attribName=D.attribName[D.looseCase]()),D.attribList.indexOf(D.attribName)!==-1||D.tag.attributes.hasOwnProperty(D.attribName)){D.attribName=D.attribValue="";return}if(D.opt.xmlns){var N=X(D.attribName,!0),z=N.prefix,H=N.local;if(z==="xmlns")if(H==="xml"&&D.attribValue!==f)V(D,"xml: prefix must be bound to "+f+`
|
||
|
|
Actual: `+D.attribValue);else if(H==="xmlns"&&D.attribValue!==p)V(D,"xmlns: prefix must be bound to "+p+`
|
||
|
|
Actual: `+D.attribValue);else{var oe=D.tag,Q=D.tags[D.tags.length-1]||D;oe.ns===Q.ns&&(oe.ns=Object.create(Q.ns)),oe.ns[H]=D.attribValue}D.attribList.push([D.attribName,D.attribValue])}else D.tag.attributes[D.attribName]=D.attribValue,A(D,"onattribute",{name:D.attribName,value:D.attribValue});D.attribName=D.attribValue=""}function re(D,N){if(D.opt.xmlns){var z=D.tag,H=X(D.tagName);z.prefix=H.prefix,z.local=H.local,z.uri=z.ns[H.prefix]||"",z.prefix&&!z.uri&&(V(D,"Unbound namespace prefix: "+JSON.stringify(D.tagName)),z.uri=H.prefix);var oe=D.tags[D.tags.length-1]||D;z.ns&&oe.ns!==z.ns&&Object.keys(z.ns).forEach(function(Fr){A(D,"onopennamespace",{prefix:Fr,uri:z.ns[Fr]})});for(var Q=0,de=D.attribList.length;Q<de;Q++){var fe=D.attribList[Q],De=fe[0],st=fe[1],Le=X(De,!0),Bt=Le.prefix,Pt=Le.local,Nt=Bt===""?"":z.ns[Bt]||"",$e={name:De,value:st,prefix:Bt,local:Pt,uri:Nt};Bt&&Bt!=="xmlns"&&!Nt&&(V(D,"Unbound namespace prefix: "+JSON.stringify(Bt)),$e.uri=Bt),D.tag.attributes[De]=$e,A(D,"onattribute",$e)}D.attribList.length=0}D.tag.isSelfClosing=!!N,D.sawRoot=!0,D.tags.push(D.tag),A(D,"onopentag",D.tag),N||(!D.noscript&&D.tagName.toLowerCase()==="script"?D.state=P.SCRIPT:D.state=P.TEXT,D.tag=null,D.tagName=""),D.attribName=D.attribValue="",D.attribList.length=0}function ue(D){if(!D.tagName){V(D,"Weird empty close tag."),D.textNode+="</>",D.state=P.TEXT;return}if(D.script){if(D.tagName!=="script"){D.script+="</"+D.tagName+">",D.tagName="",D.state=P.SCRIPT;return}A(D,"onscript",D.script),D.script=""}var N=D.tags.length,z=D.tagName;D.strict||(z=z[D.looseCase]());for(var H=z;N--&&D.tags[N].name!==H;)V(D,"Unexpected close tag");if(N<0){V(D,"Unmatched closing tag: "+D.tagName),D.textNode+="</"+D.tagName+">",D.state=P.TEXT;return}D.tagName=z;for(var oe=D.tags.length;oe-- >N;){var Q=D.tag=D.tags.pop();D.tagName=D.tag.name,A(D,"onclosetag",D.tagName);var de={};for(var fe in Q.ns)de[fe]=Q.ns[fe];var De=D.tags[D.tags.length-1]||D;D.opt.xmlns&&Q.ns!==De.ns&&Object.keys(Q.ns).forEach(function(st){var Le=Q.ns[st];A(D,"onclosenamespace",{prefix:st,uri:Le})})}N===0&&(D.closedRoot=!0),D.tagName=D.attribValue=D.attribName="",D.attribList.length=0,D.state=P.TEXT}function le(D){var N=D.entity,z=N.toLowerCase(),H,oe="";return D.ENTITIES[N]?D.ENTITIES[N]:D.ENTITIES[z]?D.ENTITIES[z]:(N=z,N.charAt(0)==="#"&&(N.charAt(1)==="x"?(N=N.slice(2),H=parseInt(N,16),oe=H.toString(16)):(N=N.slice(1),H=parseInt(N,10),oe=H.toString(10))),N=N.replace(/^0+/,""),isNaN(H)||oe.toLowerCase()!==N?(V(D,"Invalid character entity"),"&"+D.entity+";"):String.fromCodePoint(H))}function L(D,N){N==="<"?(D.state=P.OPEN_WAKA,D.startTagPosition=D.position):_(N)||(V(D,"Non-whitespace before first tag."),D.textNode=N,D.state=P.TEXT)}function J(D,N){var z="";return N<D.length&&(z=D.charAt(N)),z}function ne(D){var N=this;if(this.error)throw this.error;if(N.closed)return q(N,"Cannot write after close. Assign an onready handler.");if(D===null)return Z(N);typeof D=="object"&&(D=D.toString());for(var z=0,H="";H=J(D,z++),N.c=H,!!H;)switch(N.trackPosition&&(N.position++,H===`
|
||
|
|
`?(N.line++,N.column=0):N.column++),N.state){case P.BEGIN:if(N.state=P.BEGIN_WHITESPACE,H==="\uFEFF")continue;L(N,H);continue;case P.BEGIN_WHITESPACE:L(N,H);continue;case P.TEXT:if(N.sawRoot&&!N.closedRoot){for(var oe=z-1;H&&H!=="<"&&H!=="&";)H=J(D,z++),H&&N.trackPosition&&(N.position++,H===`
|
||
|
|
`?(N.line++,N.column=0):N.column++);N.textNode+=D.substring(oe,z-1)}H==="<"&&!(N.sawRoot&&N.closedRoot&&!N.strict)?(N.state=P.OPEN_WAKA,N.startTagPosition=N.position):(!_(H)&&(!N.sawRoot||N.closedRoot)&&V(N,"Text data outside of root node."),H==="&"?N.state=P.TEXT_ENTITY:N.textNode+=H);continue;case P.SCRIPT:H==="<"?N.state=P.SCRIPT_ENDING:N.script+=H;continue;case P.SCRIPT_ENDING:H==="/"?N.state=P.CLOSE_TAG:(N.script+="<"+H,N.state=P.SCRIPT);continue;case P.OPEN_WAKA:if(H==="!")N.state=P.SGML_DECL,N.sgmlDecl="";else if(!_(H))if(O(h,H))N.state=P.OPEN_TAG,N.tagName=H;else if(H==="/")N.state=P.CLOSE_TAG,N.tagName="";else if(H==="?")N.state=P.PROC_INST,N.procInstName=N.procInstBody="";else{if(V(N,"Unencoded <"),N.startTagPosition+1<N.position){var Q=N.position-N.startTagPosition;H=new Array(Q).join(" ")+H}N.textNode+="<"+H,N.state=P.TEXT}continue;case P.SGML_DECL:(N.sgmlDecl+H).toUpperCase()===c?(A(N,"onopencdata"),N.state=P.CDATA,N.sgmlDecl="",N.cdata=""):N.sgmlDecl+H==="--"?(N.state=P.COMMENT,N.comment="",N.sgmlDecl=""):(N.sgmlDecl+H).toUpperCase()===d?(N.state=P.DOCTYPE,(N.doctype||N.sawRoot)&&V(N,"Inappropriately located doctype declaration"),N.doctype="",N.sgmlDecl=""):H===">"?(A(N,"onsgmldeclaration",N.sgmlDecl),N.sgmlDecl="",N.state=P.TEXT):(w(H)&&(N.state=P.SGML_DECL_QUOTED),N.sgmlDecl+=H);continue;case P.SGML_DECL_QUOTED:H===N.q&&(N.state=P.SGML_DECL,N.q=""),N.sgmlDecl+=H;continue;case P.DOCTYPE:H===">"?(N.state=P.TEXT,A(N,"ondoctype",N.doctype),N.doctype=!0):(N.doctype+=H,H==="["?N.state=P.DOCTYPE_DTD:w(H)&&(N.state=P.DOCTYPE_QUOTED,N.q=H));continue;case P.DOCTYPE_QUOTED:N.doctype+=H,H===N.q&&(N.q="",N.state=P.DOCTYPE);continue;case P.DOCTYPE_DTD:N.doctype+=H,H==="]"?N.state=P.DOCTYPE:w(H)&&(N.state=P.DOCTYPE_DTD_QUOTED,N.q=H);continue;case P.DOCTYPE_DTD_QUOTED:N.doctype+=H,H===N.q&&(N.state=P.DOCTYPE_DTD,N.q="");continue;case P.COMMENT:H==="-"?N.state=P.COMMENT_ENDING:N.comment+=H;continue;case P.COMMENT_ENDING:H==="-"?(N.state=P.COMMENT_ENDED,N.comment=k(N.opt,N.comment),N.comment&&A(N,"oncomment",N.comment),N.comment=""):(N.comment+="-"+H,N.state=P.COMMENT);continue;case P.COMMENT_ENDED:H!==">"?(V(N,"Malformed comment"),N.comment+="--"+H,N.state=P.COMMENT):N.state=P.TEXT;continue;case P.CDATA:H==="]"?N.state=P.CDATA_ENDING:N.cdata+=H;continue;case P.CDATA_ENDING:H==="]"?N.state=P.CDATA_ENDING_2:(N.cdata+="]"+H,N.state=P.CDATA);continue;case P.CDATA_ENDING_2:H===">"?(N.cdata&&A(N,"oncdata",N.cdata),A(N,"onclosecdata"),N.cdata="",N.state=P.TEXT):H==="]"?N.cdata+="]":(N.cdata+="]]"+H,N.state=P.CDATA);continue;case P.PROC_INST:H==="?"?N.state=P.PROC_INST_ENDING:_(H)?N.state=P.PROC_INST_BODY:N.procInstName+=H;continue;case P.PROC_INST_BODY:if(!N.procInstBody&&_(H))continue;H==="?"?N.state=P.PROC_INST_ENDING:N.procInstBody+=H;continue;case P.PROC_INST_ENDING:H===">"?(A(N,"onprocessinginstruction",{name:N.procInstName,body:N.procInstBody}),N.procInstName=N.procInstBody="",N.state=P.TEXT):(N.procInstBody+="?"+H,N.state=P.PROC_INST_BODY);continue;case P.OPEN_TAG:O(y,H)?N.tagName+=H:(Y(N),H===">"?re(N):H==="/"?N.state=P.OPEN_TAG_SLASH:(_(H)||V(N,"Invalid character in tag name"),N.state=P.ATTRIB));continue;case P.OPEN_TAG_SLASH:H===">"?(re(N,!0),ue(N)):(V(N,"Forward-slash in opening tag not followed by >"),N.state=P.ATTRIB);continue;case P.ATTRIB:if(_(H))continue;H===">"?re(N):H==="/"?N.state=P.OPEN_TAG_SLASH:O(h,H)?(N.attribName=H,N.attribValue="",N.state=P.ATTRIB_NAME):V(N,"Invalid attribute name");continue;case P.ATTRIB_NAME:H==="="?N.state=P.ATTRIB_VALUE:H===">"?(V(N,"Attribute without value"),N.attribValue=N.attribName,W(N),re(N)):_(H)?N.state=P.ATTRIB_NAME_SAW_WHITE:O(y,H)?N.attribName+=H:V(N,"Invalid attribute name");continue;case P.ATTRIB_NAME_SAW_WHITE:if(H==="=")N.state=P.ATTRIB_VALUE;else{if(_(H))continue;V(N,"Attribute without value"),N.tag.attributes[N.attribName]="",N.attribValue="",A(N,"onattribute",{name:N.attribName,value:""}),N.attribName="",H===">"?re(N):O(h,H)?(N.attribName=H,N.state=P.ATTRIB_NAME):(V(N,"Invalid attribute name"),N.state=P.ATTRIB)}continue;case P.ATTRIB_VALUE:if(_(H))continue;w(H)?(N.q
|
||
|
|
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(uvn)||"name",h.scan(ivn),g==="="?(b=h.scanUntil(SAt),h.scan(SAt),h.scanUntil(f)):g==="{"?(b=h.scanUntil(p),h.scan(svn),h.scanUntil(f),g="&"):b=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?w=[g,b,y,h.pos,u,l,r]:w=[g,b,y,h.pos],l++,o.push(w),g==="#"||g==="^")n.push(w);else if(g==="/"){if(T=n.pop(),!T)throw new Error('Unopened section "'+b+'" at '+y);if(T[1]!==b)throw new Error('Unclosed section "'+T[1]+'" at '+y)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(b)}if(c(),T=n.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+h.pos);return dvn(cvn(o))}function cvn(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 dvn(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 Kee(t){this.string=t,this.tail=t,this.pos=0}function wJ(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Ob(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var X_n,SJ,Q_n,tvn,nvn,ivn,avn,SAt,svn,uvn,xS,Jee,lge,CAt=v(()=>{X_n=Object.prototype.toString,SJ=Array.isArray||function(e){return X_n.call(e)==="[object Array]"};Q_n=RegExp.prototype.test;tvn=/\S/;nvn={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};ivn=/\s*/,avn=/\s+/,SAt=/\s*=/,svn=/\s*\}/,uvn=/#|\^|\/|>|\{|&|=|!/;Kee.prototype.eos=function(){return this.tail===""};Kee.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};Kee.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};wJ.prototype.push=function(e){return new wJ(e,this)};wJ.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=wAt(i,a[s])||Y_n(i,a[s])),i=i[a[s++]];else i=o.view[e],u=wAt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return pWe(n)&&(n=n.call(this.view)),n};Ob.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Ob.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||xS.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=lvn(e,r),i&&n.set(o,a)),a};Ob.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof wJ?r:new wJ(r,void 0);return this.renderTokens(a,s,n,e,o)};Ob.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};Ob.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(SJ(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(pWe(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}};Ob.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||SJ(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};Ob.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
|
||
|
|
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=o+i[a]);return i.join(`
|
||
|
|
`)};Ob.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=pWe(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)}}};Ob.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Ob.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||xS.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===xS.escape?String(i):o(i)};Ob.prototype.rawValue=function(e){return e[1]};Ob.prototype.getConfigTags=function(e){return SJ(e)?e:e&&typeof e=="object"?e.tags:void 0};Ob.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!SJ(e))return e.escape};xS={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){Jee.templateCache=t},get templateCache(){return Jee.templateCache}},Jee=new Ob;xS.clearCache=function(){return Jee.clearCache()};xS.parse=function(e,r){return Jee.parse(e,r)};xS.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Z_n(e)+'" was given as the first argument for mustache#render(template, view, partials)');return Jee.render(e,r,n,o)};xS.escape=ovn;xS.Scanner=Kee;xS.Context=wJ;xS.Writer=Ob;lge=xS});function xAt(){lge.escape=t=>t}var CJ,TAt,Gee,OAt,EAt,cge,PAt,tw,xJ,TJ,p4=v(()=>{F6();CAt();CJ=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},TAt=(t,e=[])=>{let r=[];for(let n of t)if(n[0]==="name"){let o=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let o=[...e,n[1]],i=TAt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},Gee=t=>(xAt(),TAt(lge.parse(t))),OAt=(t,e)=>CJ(t).reduce((r,n)=>{if(n.type==="variable"){if(n.name in e)return r+(typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]));throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),EAt=(t,e)=>(xAt(),lge.render(t,e)),cge={"f-string":OAt,mustache:EAt},PAt={"f-string":CJ,mustache:Gee},tw=(t,e,r)=>{try{return cge[e](t,r)}catch(n){throw AL(n,"INVALID_PROMPT_INPUT")}},xJ=(t,e)=>PAt[e](t),TJ=(t,e,r)=>{if(!(e in cge)){let n=Object.keys(cge);throw new Error(`Invalid template format. Got \`${e}\`;
|
||
|
|
should be one of ${n}`)}try{let n=Object.fromEntries(r.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")tw(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")tw(o.image_url,e,n);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;tw(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):tw(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var Ku,dge=v(()=>{Wee();p4();Ku=class Xee extends f4{constructor(r){super(r);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),TJ(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return tw(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
|
||
|
|
|
||
|
|
`,a=""){return new Xee({inputVariables:o,template:[a,...r,n].join(i)})}static fromTemplate(r,n){let{templateFormat:o="f-string",...i}=n??{},a=new Set;return xJ(r,o).forEach(s=>{s.type==="variable"&&a.add(s.name)}),new Xee({inputVariables:[...a],templateFormat:o,template:r,...i})}async partial(r){let n=this.inputVariables.filter(i=>!(i in r)),o={...this.partialVariables??{},...r};return new Xee({...this,inputVariables:n,partialVariables: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(r){if(!r.template)throw new Error("Prompt template must have a template");return new Xee({inputVariables:r.input_variables,template:r.template,templateFormat:r.template_format})}}});var Zee,mWe=v(()=>{Hee();vJ();p4();Zee=class MAt extends oO{constructor(r){super(r);x(this,"lc_namespace",["langchain_core","prompts","image"]);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(this.template=r.template,this.templateFormat=r.templateFormat??this.templateFormat,this.validateTemplate=r.validateTemplate??this.validateTemplate,this.additionalContentFields=r.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),TJ([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(r){let n=this.inputVariables.filter(i=>!(i in r)),o={...this.partialVariables??{},...r};return new MAt({...this,inputVariables:n,partialVariables:o})}async format(r){let n={};for(let[s,u]of Object.entries(this.template))typeof u=="string"?n[s]=tw(u,this.templateFormat,r):n[s]=u;let o=r.url||n.url,i=r.detail||n.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let a={url:o};return i&&(a.detail=i),a}async formatPromptValue(r){return new vAt(await this.format(r))}}});function hWe(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")xJ(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?xJ(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...hWe(o,e));else typeof n=="object"&&n!==null&&r.push(...hWe(n,e));return Array.from(new Set(r))}function gWe(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=tw(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(tw(s,r,e)):typeof s=="object"&&a.push(gWe(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=gWe(i,e,r):n[o]=i;return n}var fge,yWe=v(()=>{_g();p4();fge=class extends Ti{constructor(e){let r=e.templateFormat??"f-string",n=hWe(e.template,r);super({inputVariables:n,...e});x(this,"lc_namespace",["langchain_core","prompts","dict"]);x(this,"lc_serializable",!0);x(this,"template");x(this,"templateFormat");x(this,"inputVariables");this.template=e.template,this.templateFormat=r,this.inputVariables=n}static lc_name(){return"DictPromptTemplate"}async format(e){return gWe(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function fvn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function pvn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function mvn(t){return typeof t.formatMessages=="function"}function hvn(t,e){if(mvn(t)||pS(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}")return new QN({varia
|
||
|
|
|
||
|
|
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},RAt=class extends mge{constructor(e){"prompt"in e||(e={prompt:e});super(e);x(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},bWe=class extends oO{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new uge(await this.formatMessages(t))}},IAt=class extends RAt{constructor(e,r){"prompt"in e||(e={prompt:e,role:r});super(e);x(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new hy(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(Ku.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};_We=class extends mge{constructor(e,r){"prompt"in e||(e={prompt:e});super(e);x(this,"lc_namespace",["langchain_core","prompts","chat"]);x(this,"lc_serializable",!0);x(this,"inputVariables",[]);x(this,"additionalOptions",{});x(this,"prompt");x(this,"messageClass");x(this,"chatMessageClass");if(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}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let r=this.constructor;if(r._messageClass())return new(r._messageClass())({content:e});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(Ku.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(Ku.fromTemplate(o,r));else if(o!==null)if(fvn(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(Ku.fromTemplate(i,a))}else if(pvn(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=Gee(i):u=CJ(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
|
||
|
|
Got: ${l}
|
||
|
|
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new Zee({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=Gee(i.url):u=CJ(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new Zee({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 fge({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof f4){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 f4){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),i!==""&&r.push({...a,type:"text",text:i})}else if(n instanceof Zee){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 fge){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)]}},rw=class extends _We{static _messageClass(){return Au}static lc_name(){return"HumanMessagePromptTemplate"}},vWe=class extends _We{static _messageClass(){return uo}static lc_name(){return"AIMessagePromptTemplate"}},$C=class extends _We{static _messageClass(){return v_}static lc_name(){return"SystemMessagePromptTemplate"}};Eb=class pge extends bWe{constructor(r){super(r);x(this,"promptMessages");x(this,"validateTemplate",!0);x(this,"templateFormat","f-string");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){let n=new Set;for(let u of this.promptMessages)if(!(u instanceof Sm))for(let l of u.inputVariables)n.add(l);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),a=new Set([...i].filter(u=>!n.has(u)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);let s=new Set([...n].filter(u=>!i.has(u)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(r,n){return typeof r.content=="string"||(r.content=await Promise.all(r.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(i=o.image_url.url);let a=await Ku.fromTemplate(i,{templateFormat:this.templateFormat}).format(n);return typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url?o.image_url.url=a:o.image_url=a,o}))),r}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=[];for(let i of this.promptMessages)if(i instanceof Sm)o.push(await this._parseImagePrompts(i,n));else{let a;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(l in n)&&!(gvn(i)&&i.optional))throw AL(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return u[l]=n[l],u},{});let s=await i.formatMessages(a);o=o.concat(s)}return o}async partial(r){let n=this.inputVariables.filter(i=>!(i in r)),o={...this.partialVariables??{},...r};return new pge({...this,inputVariables:n,partialVariables:o})}static fromTemplate(r,n){let o=new rw({prompt:Ku.fromTemplate(r,n)});return this.fromMessages([o])}static fromMessages(r,n){let o=r.reduce((s,u)=>s.concat(u instanceof pge?u.promptMessages:[hvn(u,n)]),[]),i=r.reduce((s,u)=>u instanceof pge?Object
|
||
|
|
|
||
|
|
`)});function yc(t,e){let r=`atom${++_vn}`,n={toString(){return(kl.env?kl.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=vvn,n.write=wvn),e&&(n.write=e),n}function vvn(t){return t(this)}function wvn(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var kl,_vn,jAt,SWe,CWe,yge,TWe,Svn,Cvn,OWe,$At,gge,kAt,LAt,EJ,xWe,xvn,Tvn,FAt,YL,qAt,QL,ete,BAt,EWe=v(()=>{kl={},_vn=0;jAt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,SWe=t=>"init"in t,CWe=t=>!!t.write,yge=new WeakMap,TWe=t=>{var e;return OWe(t)&&!((e=yge.get(t))!=null&&e[1])},Svn=(t,e)=>{let r=yge.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((kl.env?kl.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Cvn=t=>{if(yge.has(t))return;let e=[new Set,!1];yge.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},OWe=t=>typeof t?.then=="function",$At=t=>"v"in t||"e"in t,gge=t=>{if("e"in t)throw t.e;if((kl.env?kl.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},kAt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},LAt=(t,e,r,n,o)=>{var i;if((kl.env?kl.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),TWe(r.v)&&kAt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&xvn(t,n,e)},EJ=()=>[new Map,new Map,new Set],xWe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},xvn=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},Tvn=(t,e)=>t[0].get(e),FAt=(t,e)=>{t[2].add(e)},YL=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},qAt=(...[t,e,r,n])=>{let o;(kl.env?kl.env.MODE:void 0)!=="production"&&(o=new Set);let i=(_,w,T)=>{let O="v"in w,E=w.v,P=TWe(w.v)?w.v:null;if(OWe(T)){Cvn(T);for(let R of w.d.keys())kAt(_,T,t(R));w.v=T,delete w.e}else w.v=T,delete w.e;(!O||!Object.is(E,w.v))&&(++w.n,P&&Svn(P,T))},a=(_,w,T)=>{var O;let E=t(w);if($At(E)&&(E.m&&!T?.has(w)||Array.from(E.d).every(([k,q])=>a(_,k,T).n===q)))return E;E.d.clear();let P=!0,R=k=>{if(jAt(w,k)){let Z=t(k);if(!$At(Z))if(SWe(k))i(k,Z,k.init);else throw new Error("no atom init");return gge(Z)}let q=a(_,k,T);try{return gge(q)}finally{if(P)LAt(_,w,E,k,q);else{let Z=EJ();LAt(Z,w,E,k,q),p(Z,w,E),YL(Z)}}},I,A,B={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(kl.env?kl.env.MODE:void 0)!=="production"&&!CWe(w)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&CWe(w)&&(A=(...k)=>{if((kl.env?kl.env.MODE:void 0)!=="production"&&P&&console.warn("setSelf function cannot be called in sync"),!P)return f(w,...k)}),A}};try{let k=e(w,R,B);if(i(w,E,k),OWe(k)){(O=k.onCancel)==null||O.call(k,()=>I?.abort());let q=()=>{if(E.m){let Z=EJ();p(Z,w,E),YL(Z)}};k.then(q,q)}return E}catch(k){return delete E.v,E.e=k,++E.n,E}finally{P=!1}},s=_=>gge(a(void 0,_)),u=(_,w,T)=>{var O,E;let P=new Map;for(let R of((O=T.m)==null?void 0:O.t)||[])P.set(R,t(R));for(let R of T.p)P.set(R,t(R));return(E=Tvn(_,w))==null||E.forEach(R=>{P.set(R,t(R))}),P};function l(_,w,T){let O=[],E=new Set,P=new Set,R=[[w,T]];for(;R.length>0;){let[I,A]=R[R.length-1];if(P.has(I)){R.pop();continue}if(E.has(I)){O.push([I,A,A.n]),P.add(I),R.pop();continue}E.add(I);for(let[B,k]of u(_,I,A))I!==B&&!E.has(B)&&R.push([B,k])}return[O,P]}let c=(_,w,T)=>{let[O,E]=l(_,w,T),P=new Set([w]);for(let R=O.length-1;R>=0;--R){let[I,A,B]=O[R],k=!1;for(let q of A.d.keys())if(q!==I&&P.has(q)){k=!0;break}k&&(a(_,I,E),p(_,I,A),B!==A.n&&(xWe(_,I,A),P.add(I))),E.delete(I)}},d=(_,w,...T)=>{let O=!0,E=R=>gge(a(_,R)),P=(R,...I)=>{let A=t(R);try{if(jAt(w,R)){if(!SWe(R))throw new Error("atom not writable");let B=A.n,k=I[0];i(R,A,k),p(_,R,A),B!==A.n&&(xWe(_,R,A),c(_,R,A));return}else return d(_,R,...I)}finally{O||YL(_)}};try{return r(w,E,P,...T)}finally{O=!1}},f=(_,...w)=>{let T=EJ();try{return d
|
||
|
|
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var FWe=v(()=>{});var kWe,Em,h4=v(()=>{FWe();Dt();Qe();kWe=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let r=Wr(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(r))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let r=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(r??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let r=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return r.length<=this.maxLineChars?r:r.slice(0,this.maxLineChars)+` \u2026 [truncated ${r.length-this.maxLineChars} chars]`}async append(e,...r){await this.ensureInitialized();let n=new Date().toISOString(),o=r.map(a=>this.sanitizeForSingleLine(a)),i=`${n} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"<").replace(/>/g,">")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let r of e){let n=typeof r=="string"?r:String(r??"");this.buffer.push(n),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){if(this.hasVault()&&!this.flushing){this.flushing=!0;try{let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let r=this.buffer.join(`
|
||
|
|
`)+(this.buffer.length?`
|
||
|
|
`:"");await app.vault.adapter.write(e,r)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=ee();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>this.removeKeysRecursive(r));if(typeof e=="object"&&e.constructor===Object){let r={},n=e;for(let[o,i]of Object.entries(n))/apiKey$/i.test(o)||/licenseKey$/i.test(o)||/_api_key$/i.test(o)||/_license_key$/i.test(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(r[o]=this.removeKeysRecursive(i));return r}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),r=[...this.buffer];try{let o=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(o,null,2).split(`
|
||
|
|
`),"```"];r.push(...a)}catch{}try{let o=r.join(`
|
||
|
|
`)+(r.length?`
|
||
|
|
`:""),i=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";i&&await ql(i),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,o):await app.vault.create(e,o)}catch{}let n=app.vault.getAbstractFileByPath(e);try{n&&await app.workspace.getLeaf(!0).openFile(n)}catch{}}},Em=kWe.getInstance()});function F(...t){ee().debug&&console.log(...t),Em.append("INFO",...t)}function ie(...t){ee().debug&&console.error(...t),Em.append("ERROR",...t)}function Ce(...t){ee().debug&&console.warn(...t),Em.append("WARN",...t)}function xge(t){Em.appendMarkdownBlock(t)}function sNt(t,e){if(ee().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}F("Table:",JSON.stringify(t))}var Xe=v(()=>{Qe();h4()});var uNt=S((qWe,AJ)=>{(function(t,e){typeof qWe=="object"&&typeof AJ<"u"?AJ.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(qWe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(C){t=C}function n(C){return C instanceof Array||Object.prototype.toString.call(C)==="[object Array]"}function o(C){return C!=null&&Object.prototype.toString.call(C)==="[object Object]"}function i(C,M){return Object.prototype.hasOwnProperty.call(C,M)}function a(C){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(C).length===0;var M;for(M in C)if(i(C,M))return!1;return!0}function s(C){return C===void 0}function u(C){return typeof C=="number"||Object.prototype.toString.call(C)==="[object Number]"}function l(C){return C instanceof Date||Object.prototype.toString.call(C)==="[object Date]"}function c(C,M){var j=[],U,G=C.length;for(U=0;U<G;++U)j.push(M(C[U],U));return j}function d(C,M){for(var j in M)i(M,j)&&(C[j]=M[j]);return i(M,"toString")&&(C.toString=M.toString),i(M,"valueOf")&&(C.valueOf=M.valueOf),C}function f(C,M,j,U){return _0t(C,M,j,U,!0).utc()}function p(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(C){return C._pf==null&&(C._pf=p()),C._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(C){var M=Object(this),j=M.length>>>0,U;for(U=0;U<j;U++)if(U in M&&C.call(this,M[U],U,M))return!0;return!1};function y(C){if(C._isValid==null){var M=m(C),j=h.call(M.parsedDateParts,function(G){return G!=null}),U=!isNaN(C._d.getTime())&&M.overflow<0&&!M.empty&&!M.invalidEra&&!M.invalidMonth&&!M.invalidWeekday&&!M.weekdayMismatch&&!M.nullInput&&!M.invalidFormat&&!M.userInvalidated&&(!M.meridiem||M.meridiem&&j);if(C._strict&&(U=U&&M.charsLeftOver===0&&M.unusedTokens.length===0&&M.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(C))C._isValid=U;else return U}return C._isValid}function g(C){var M=f(NaN);return C!=null?d(m(M),C):m(M).userInvalidated=!0,M}var b=e.momentProperties=[],_=!1;function w(C,M){var j,U,G,pe=b.length;if(s(M._isAMomentObject)||(C._isAMomentObject=M._isAMomentObject),s(M._i)||(C._i=M._i),s(M._f)||(C._f=M._f),s(M._l)||(C._l=M._l),s(M._strict)||(C._strict=M._strict),s(M._tzm)||(C._tzm=M._tzm),s(M._isUTC)||(C._isUTC=M._isUTC),s(M._offset)||(C._offset=M._offset),s(M._pf)||(C._pf=m(M)),s(M._locale)||(C._locale=M._locale),pe>0)for(j=0;j<pe;j++)U=b[j],G=M[U],s(G)||(C[U]=G);return C}function T(C){w(this,C),this._d=new Date(C._d!=null?C._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),_===!1&&(_=!0,e.updateOffset(this),_=!1)}function O(C){return C instanceof T||C!=null&&C._isAMomentObject!=null}function E(C){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+C)}function P(C,M){var j=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,C),j){var U=[],G,pe,Fe,sn=arguments.length;for(pe=0;pe<sn;pe++){if(G="",typeof arguments[pe]=="object"){G+=`
|
||
|
|
[`+pe+"] ";for(Fe in arguments[0])i(arguments[0],Fe)&&(G+=Fe+": "+arguments[0][Fe]+", ");G=G.slice(0,-2)}else G=arguments[pe];U.push(G)}E(C+`
|
||
|
|
Arguments: `+Array.prototype.slice.call(U).join("")+`
|
||
|
|
`+new Error().stack),j=!1}return M.apply(this,arguments)},M)}var R={};function I(C,M){e.deprecationHandler!=null&&e.deprecationHandler(C,M),R[C]||(E(M),R[C]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function A(C){return typeof Function<"u"&&C instanceof Function||Object.prototype.toString.call(C)==="[object Function]"}function B(C){var M,j;for(j in C)i(C,j)&&(M=C[j],A(M)?this[j]=M:this["_"+j]=M);this._config=C,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function k(C,M){var j=d({},C),U;for(U in M)i(M,U)&&(o(C[U])&&o(M[U])?(j[U]={},d(j[U],C[U]),d(j[U],M[U])):M[U]!=null?j[U]=M[U]:delete j[U]);for(U in C)i(C,U)&&!i(M,U)&&o(C[U])&&(j[U]=d({},j[U]));return j}function q(C){C!=null&&this.set(C)}var Z;Object.keys?Z=Object.keys:Z=function(C){var M,j=[];for(M in C)i(C,M)&&j.push(M);return j};var V={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Y(C,M,j){var U=this._calendar[C]||this._calendar.sameElse;return A(U)?U.call(M,j):U}function X(C,M,j){var U=""+Math.abs(C),G=M-U.length,pe=C>=0;return(pe?j?"+":"":"-")+Math.pow(10,Math.max(0,G)).toString().substr(1)+U}var W=/(\[[^\[]*\])|(\\)?([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,re=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,ue={},le={};function L(C,M,j,U){var G=U;typeof U=="string"&&(G=function(){return this[U]()}),C&&(le[C]=G),M&&(le[M[0]]=function(){return X(G.apply(this,arguments),M[1],M[2])}),j&&(le[j]=function(){return this.localeData().ordinal(G.apply(this,arguments),C)})}function J(C){return C.match(/\[[\s\S]/)?C.replace(/^\[|\]$/g,""):C.replace(/\\/g,"")}function ne(C){var M=C.match(W),j,U;for(j=0,U=M.length;j<U;j++)le[M[j]]?M[j]=le[M[j]]:M[j]=J(M[j]);return function(G){var pe="",Fe;for(Fe=0;Fe<U;Fe++)pe+=A(M[Fe])?M[Fe].call(G,C):M[Fe];return pe}}function D(C,M){return C.isValid()?(M=N(M,C.localeData()),ue[M]=ue[M]||ne(M),ue[M](C)):C.localeData().invalidDate()}function N(C,M){var j=5;function U(G){return M.longDateFormat(G)||G}for(re.lastIndex=0;j>=0&&re.test(C);)C=C.replace(re,U),re.lastIndex=0,j-=1;return C}var z={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 H(C){var M=this._longDateFormat[C],j=this._longDateFormat[C.toUpperCase()];return M||!j?M:(this._longDateFormat[C]=j.match(W).map(function(U){return U==="MMMM"||U==="MM"||U==="DD"||U==="dddd"?U.slice(1):U}).join(""),this._longDateFormat[C])}var oe="Invalid date";function Q(){return this._invalidDate}var de="%d",fe=/\d{1,2}/;function De(C){return this._ordinal.replace("%d",C)}var st={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 Le(C,M,j,U){var G=this._relativeTime[j];return A(G)?G(C,M,j,U):G.replace(/%d/i,C)}function Bt(C,M){var j=this._relativeTime[C>0?"future":"past"];return A(j)?j(M):j.replace(/%s/i,M)}var Pt={};function Nt(C,M){var j=C.toLowerCase();Pt[j]=Pt[j+"s"]=Pt[M]=C}function $e(C){return typeof C=="string"?Pt[C]||Pt[C.toLowerCase()]:void 0}function Fr(C){var M={},j,U;for(U in C)i(C,U)&&(j=$e(U),j&&(M[j]=C[U]));return M}var ft={};function Ve(C,M){ft[C]=M}function Rt(C){var M=[],j;for(j in C)i(C,j)&&M.push({unit:j,priority:ft[j]});return M.sort(function(U,G){return U.priority-G.priority}),M}function ze(C){return C%4===0&&C%100!==0||C%400===0}function He(C){return C<0?Math.ceil(C)||0:Math.floor(C)}function We(C){var M=+C,j=0;return M!==0&&isFinite(M)&&(j=He(M)),j}function Jt(C,M){return function(j){return j!=null?(au(this,C,j),e.updateOffset(this,M),this):so(this,C)}}function so(C,M){return C.isValid()?C._d["get"+(C._isUTC?"UTC":"")+M]():NaN}function au(C,M,j){C.isValid()&&!isNaN(j)&&(M==="FullYe
|
||
|
|
`)?o.slice(2):o.startsWith(`
|
||
|
|
`)||o.startsWith("\r")?o.slice(1):o}}return t}function sO(t,e=!0){let r=app.metadataCache.getFileCache(t),n=r?.frontmatter?.tags,o=new Set;if(!e){let i=r?.tags?.map(a=>a.tag);i&&i.forEach(a=>o.add(DJ(a)))}return n&&(Array.isArray(n)?n.forEach(i=>{typeof i=="string"&&o.add(DJ(i))}):typeof n=="string"&&o.add(DJ(n))),Array.from(o)}function Oge(t,e,r){if(e.length===0)return[];e=e.map(i=>DJ(i));let n=r&&r.length>0?r:ite(t,"/"),o=[];for(let i of n){let a=sO(i);e.some(s=>a.includes(s))&&o.push(i)}return o}async function ql(t){let e=(0,xy.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;let r=e.split("/").filter(Boolean),n="";for(let o of r){n=n?`${n}/${o}`:o;let i=app.vault.getAbstractFileByPath(n);if(i){if(i instanceof xy.TFile)throw new Error(`Path conflict: "${n}" exists as a file, expected folder.`);continue}await app.vault.adapter.mkdir(n)}}function Ege(t){return t?GWe.includes(t.extension):!1}async function $J(t,e){return Ege(t)?await e.read(t):null}function Pge(t){return t.basename}function uO(t){return t?PNt.includes(t.extension):!1}function Rb(t){return t==="copilot_plus"||t==="project"}function LJ(t,e){return t?Ege(t)?!0:Rb(e):!1}function hNt(t,e){return!t||!e?!1:t.includes(VWe)&&e.includes(VWe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function Mge(t){let e=[],{history:r}=t;for(let n=0;n<r.length;n+=2){let o=r[n]?.content||"",i=r[n+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function gNt(t,e){let r=new Map;return t.forEach(n=>{let o=e.getAbstractFileByPath(n);if(o instanceof xy.TFile)r.set(o.path,o);else{let a=e.getMarkdownFiles().filter(s=>s.basename===n);a.length>0&&(ewn(n,e)?r.set(a[0].path,a[0]):console.warn(`Found multiple files with title "${n}". Expected a full path for duplicate titles.`))}}),Array.from(r.values())}function ES(t,e){let r=/\[\[(.*?)\]\]/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(2,-2));return gNt(o,e)}function yNt(t,e){let r=/\{\[\[(.*?)\]\]\}/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(3,-3));return gNt(o,e)}function ewn(t,e){return e.getMarkdownFiles().filter(n=>n.basename===t).length===1}function bNt(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function _Nt(t){let e=new Set;return t.forEach(r=>{r.metadata?.title&&e.add(r.metadata?.title)}),Array.from(e)}function HWe(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let r=WWe(e);return r?/^[a-zA-Z0-9_-]{11}$/.test(r)?{isValid:!0,videoId:r}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function WWe(t){try{let e=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(let r of e){let n=t.match(r);if(n&&n[1])return n[1]}return null}catch{return null}}function vNt(t){return`https://www.youtube.com/watch?v=${t}`}function wNt(t){return HWe(t).isValid}function SNt(t){if(!t||typeof t!="string")return!1;try{let e=new URL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}function CNt(t){let e=t.matchAll(new RegExp(twn,"g"));return Array.from(e,r=>r[0])}async function hl(t,e={}){let{throwOnHttpError:r=!0}=e,n=new Headers(e.headers),o=Object.fromEntries(n.entries());delete o["content-length"],F("safeFetch request");let i=e.method?.toUpperCase()||"POST",s=await(0,xy.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&{body:e.body?.toString()},throw:!1});if(r&&s.status>=400){let u;try{u=typeof s.json=="string"?JSON.parse(s.json):s.json}catch{try{u=typeof s.text=="string"?JSON.parse(s.text):s.text}catch{u=null}}let l=new Error(zWe.REQUEST_FAILED(s.status));if(l.json=u,u?.detail?.reason==="Invalid license key"||u?.reason==="Invalid license key")l.message="Invalid license key";else if(u?.detail?.message||u
|
||
|
|
|
||
|
|
`),e=e.trim(),e}async function FJ(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new xy.Notice("No active leaf found.");return}if(r.view instanceof xy.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof xy.MarkdownView)){new xy.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=lO(t),s=a.split(`
|
||
|
|
`),u=(b,_)=>{let w=_.length-1;return w===0?{line:b.line,ch:b.ch+(_[0]?.length??0)}:{line:b.line+w,ch:_[_.length-1]?.length??0}},l=()=>{let b=e?o:i;n.replaceRange(a,b,i),n.setSelection(b,u(b,s))},c=()=>{n.focus(),new xy.Notice("Message inserted into the active note.")},d=n.cm;if(!(d?.state?.doc&&typeof d.dispatch=="function")){l(),c();return}let{from:p,to:m}=d.state.selection.main,h=e?p:m,y=d.state.toText(a),g=h+y.length;try{d.dispatch({changes:{from:h,to:m,insert:y},selection:{anchor:h,head:g}})}catch(b){Ce("CM6 dispatch failed, falling back to Obsidian API",b),l()}c()}function Ige(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function Age(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 xNt(){try{return{version:(await(0,xy.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 ste(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 nwn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function kJ(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=ste(e),n=nwn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4")||e.startsWith("claude-opus-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function ute(t,e="system"){return ste(t)?"human":e}function JWe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(qC).filter(e=>!t.includes(e))}function qJ(t,e){if(t.provider==="amazon-bedrock")return t.apiKey||e.amazonBedrockApiKey?{hasApiKey:!0}:{hasApiKey:!1,errorNotice:"Amazon Bedrock API key is missing. Please add a key in Settings > API Keys or update the model configuration."};if(t.provider==="github-copilot")return!(t.apiKey||e.githubCopilotToken||e.githubCopilotAccessToken)?{hasApiKey:!1,errorNotice:"GitHub Copilot is not authenticated. Please connect it in Settings > Copilot > Basic Tab > Set Keys."}:{hasApiKey:!0};let r=!!JWe().find(o=>o===t.provider),n=!nw(t.provider,t);return r&&n?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
|
||
|
|
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function tF(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function lte(t){let r=tF(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function Nge(t){return tF(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function TNt(){return crypto.randomUUID()}async function Ib(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 ONt(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(OS(),cNt)),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 cte(){let t=app.workspace.getActiveViewOfType(xy.MarkdownView);return t?t.getState().source===!0:!0}function b4(t){return new TextEncoder().encode(t).length}function ote(t,e){if(e<=0)return"";let r=new TextEncoder;if(r.encode(t).length<=e)return t;let o=0,i=t.length,a="";for(;o<=i;){let s=Math.floor((o+i)/2),u=t.substring(0,s);r.encode(u).length<=e?(a=u,o=s+1):i=s-1}return a}function KWe(t){let e=t.split("/"),r=e[e.length-1];if(b4(r)<=UWe)return t;let n=r.lastIndexOf("."),o=n>=0?r.substring(n):"",i=n>=0?r.substring(0,n):r,a=b4(o),s=UWe-a;return s<=0?e[e.length-1]=ote(r,UWe):e[e.length-1]=ote(i,s)+o,e.join("/")}async function ENt(t,e=!0){let r=null;app.workspace.iterateAllLeaves(n=>{if(n.view.getViewType()==="markdown"||n.view.getViewType()==="pdf"||n.view.getViewType()==="canvas"){let o=n.view.file;o&&o.path===t.path&&(r=n)}}),r&&e?app.workspace.setActiveLeaf(r,{focus:!0}):r||await app.workspace.getLeaf("tab").openFile(t)}var dNt,xy,zWe,ite,Yvn,Qvn,mNt,vg,twn,UWe,Dt=v(()=>{rd();gr();Xe();dNt=$(uNt()),xy=require("obsidian");g4();FWe();zWe={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}`};ite=(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})};Yvn=t=>t.last?.modelName||t.last?.model,Qvn=t=>t.last?.retriever!==void 0,mNt=t=>Yvn(t)||Qvn(t),vg=(t,e="local")=>{let r=(0,dNt.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};twn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;UWe=255});var BJ,XWe,dte,rd=v(()=>{nO();TS();Qv();wWe();Dt();BJ=class BJ{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=gc.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return BJ.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=BJ.instances.get("llm_chain");return r||(r=BJ.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=Ku.fromTemplate(`Given the following conversation and a follow up question,
|
||
|
|
summarize the conversation as context and keep the follow up question unchanged, in its original language.
|
||
|
|
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
|
||
|
|
If it is related, then combine the summary and the follow up question to construct a standalone question.
|
||
|
|
Make sure to keep any [[]] wrapped note titles in the question unchanged.
|
||
|
|
|
||
|
|
Chat History:
|
||
|
|
{chat_history}
|
||
|
|
Follow Up Input: {question}
|
||
|
|
Standalone question:`),c=Ku.fromTemplate(`{system_message}
|
||
|
|
|
||
|
|
Answer the question with as detailed as possible based only on the following context:
|
||
|
|
{context}
|
||
|
|
|
||
|
|
Question: {question}
|
||
|
|
`),d=y=>y.map(b=>`Human: ${b[0]}
|
||
|
|
Assistant: ${b[1]}`).join(`
|
||
|
|
`),f=gc.from([{question:y=>(n&&console.log("Input Question: ",y.question),y.question),chat_history:y=>{let g=d(y.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new uWe,y=>{let g=lte(y),b=Nge(g);return n&&console.log("Standalone Question: ",b),b}]),p=async y=>(r(y),Qee(y)),m=gc.from([{context:i.pipe(p),question:new pl,system_message:()=>a},c,o]);return f.pipe(m)}};BJ.instances=new Map;XWe=BJ,dte=XWe});var fte=v(()=>{});var ZWe,i1,Du,Zs,ow,FC,own,iwn,awn,swn,uwn,LWe,RNt,INt,pte,N_,YWe,mte,_4,hte,QWe,gte,e3e,t3e,Dge,r3e,yte,jge,$ge,n3e,Lge,lwn,o3e,Cge,iw,a1,Ab,UJ,Mb,rF,aO,kC,m4,VWe,qC,Tge,ANt,IJ,ur,Fge,kge,GWe,PNt,zJ,Do,MS,gr=v(()=>{y_();rd();fte();ZWe="https://api.brevilabs.com/v1",i1="https://models.brevilabs.com/v1",Du="copilot-chat-view",Zs="user",ow="ai",FC="copilot",own=`${FC}/copilot-conversations`,iwn=`${FC}/copilot-custom-prompts`,awn=`${FC}/memory`,swn=`${FC}/system-prompts`,uwn="",LWe=FC,RNt=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
|
||
|
|
1. Never mention that you do not have access to something. Always rely on the user provided context.
|
||
|
|
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
|
||
|
|
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
|
||
|
|
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
|
||
|
|
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
|
||
|
|
6. Always use $'s instead of \\[ etc. for LaTeX equations.
|
||
|
|
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
|
||
|
|
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
|
||
|
|
9. When showing **web** image links, use  format and do not wrap them in \` \`.
|
||
|
|
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
|
||
|
|
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.
|
||
|
|
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
|
||
|
|
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.
|
||
|
|
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,INt=`Return the new note content or canvas JSON in <writeFile> tags.
|
||
|
|
|
||
|
|
# 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.
|
||
|
|
|
||
|
|
# Examples
|
||
|
|
|
||
|
|
Input: Add a new section to note A
|
||
|
|
Output:
|
||
|
|
<writeFile>
|
||
|
|
<path>path/to/file.md</path>
|
||
|
|
<content>The FULL CONTENT of the note A with added section goes here</content>
|
||
|
|
</writeFile>
|
||
|
|
|
||
|
|
Input: Create a new canvas with "Hello, world!"
|
||
|
|
Output:
|
||
|
|
<writeFile>
|
||
|
|
<path>path/to/file.canvas</path>
|
||
|
|
<content>
|
||
|
|
{
|
||
|
|
"nodes": [
|
||
|
|
{
|
||
|
|
"id": "1",
|
||
|
|
"type": "text",
|
||
|
|
"text": "Hello, world!",
|
||
|
|
"x": 0,
|
||
|
|
"y": 0,
|
||
|
|
"width": 200,
|
||
|
|
"height": 50
|
||
|
|
}
|
||
|
|
],
|
||
|
|
"edges": []
|
||
|
|
}
|
||
|
|
</content>
|
||
|
|
</writeFile>
|
||
|
|
|
||
|
|
Input: Create a canvas with a file node and a group
|
||
|
|
Output:
|
||
|
|
<writeFile>
|
||
|
|
<path>path/to/file.canvas</path>
|
||
|
|
<content>
|
||
|
|
{
|
||
|
|
"nodes": [
|
||
|
|
{"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
|
||
|
|
{"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
|
||
|
|
{"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
|
||
|
|
],
|
||
|
|
"edges": [
|
||
|
|
{"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
|
||
|
|
]
|
||
|
|
}
|
||
|
|
</content>
|
||
|
|
</writeFile>
|
||
|
|
|
||
|
|
# Canvas JSON Format (JSON Canvas spec 1.0)
|
||
|
|
Required node fields: id, type, x, y, width, height
|
||
|
|
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
|
||
|
|
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
|
||
|
|
Required edge fields: id, fromNode, toNode
|
||
|
|
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
|
||
|
|
All IDs must be unique. Edge nodes must reference existing node IDs.
|
||
|
|
Position nodes with reasonable spacing and logical visual flow.
|
||
|
|
`,pte="note_context",N_="selected_text",YWe="web_selected_text",mte="variable",_4="variable_note",hte="embedded_pdf",QWe="embedded_note",gte="dataview_block",e3e="retrieved_document",t3e="web_tab_context",Dge="active_web_tab",r3e="youtube_video_context",yte="{activeWebTab}",jge=6e3,$ge=.4,n3e=448e3,Lge=3e4,lwn=30,o3e=5*60*1e3,Cge=16,iw={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},a1={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Ab={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},UJ=131072,Mb=(g=>(g.OPENROUTERAI="openrouterai",g.OPENAI="openai",g.OPENAI_FORMAT="3rd party (openai-format)",g.ANTHROPIC="anthropic",g.GOOGLE="google",g.XAI="xai",g.AMAZON_BEDROCK="amazon-bedrock",g.AZURE_OPENAI="azure openai",g.GROQ="groq",g.OLLAMA="ollama",g.LM_STUDIO="lm-studio",g.COPILOT_PLUS="copilot-plus",g.MISTRAL="mistralai",g.DEEPSEEK="deepseek",g.COHEREAI="cohereai",g.SILICONFLOW="siliconflow",g.GITHUB_COPILOT="github-copilot",g))(Mb||{}),rF={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},aO=[{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",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5.4",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:"claude-sonnet-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-flash-lite-preview",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-3-flash-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.4",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5-mini",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4-1-fast",provider:"xai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4.1-fast",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"claude-opus-4-6",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3-flash-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-pro",provider:"google",enabled:!1,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"deepseek-chat",provider:"deepseek",enabled:!1,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!1,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],kC=(d=>(d.OPENAI="openai",d.OPENROUTERAI="o
|
||
|
|
`+D3e+t}var j3e=!1;function $3e(t,e){if(!t||j3e)return"";j3e=!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(`
|
||
|
|
`),i=n.stack.split(`
|
||
|
|
`),a=o.length-1,s=i.length-1;1<=a&&0<=s&&o[a]!==i[s];)s--;for(;1<=a&&0<=s;a--,s--)if(o[a]!==i[s]){if(a!==1||s!==1)do if(a--,s--,0>s||o[a]!==i[s]){var u=`
|
||
|
|
`+o[a].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=a&&0<=s);break}}}finally{j3e=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?Nte(t):""}function Xwn(t){switch(t.tag){case 5:return Nte(t.type);case 16:return Nte("Lazy");case 13:return Nte("Suspense");case 19:return Nte("SuspenseList");case 0:case 2:case 15:return t=$3e(t.type,!1),t;case 11:return t=$3e(t.type.render,!1),t;case 1:return t=$3e(t.type,!0),t;default:return""}}function a6e(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 o5:return"Fragment";case n5:return"Portal";case n6e:return"Profiler";case Z6e:return"StrictMode";case o6e:return"Suspense";case i6e:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case $Dt:return(t.displayName||"Context")+".Consumer";case jDt:return(t._context.displayName||"Context")+".Provider";case Y6e:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Q6e:return e=t.displayName||null,e!==null?e:a6e(t.type)||"Memo";case sF:e=t._payload,t=t._init;try{return a6e(t(e))}catch{}}return null}function Zwn(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 a6e(e);case 8:return e===Z6e?"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 wF(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function FDt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Ywn(t){var e=FDt(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 rye(t){t._valueTracker||(t._valueTracker=Ywn(t))}function kDt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=FDt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function Rye(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 s6e(t,e){var r=e.checked;return vc({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function R1t(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=wF(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 qDt(t,e){e=e.checked,e!=null&&X6e(t,"checked",e,!1)}function u6e(t,e){qDt(t,e);var r=wF(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")?l6e(t,e.type,r):e.hasOwnProperty("defaultValue")&&l6e(t,e.type,wF(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}fun
|
||
|
|
`).replace(a0n,"")}function mye(t,e,r){if(e=tDt(e),tDt(t)!==e&&r)throw Error(dt(425))}function Fye(){}var C6e=null,x6e=null;function T6e(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 O6e=typeof setTimeout=="function"?setTimeout:void 0,s0n=typeof clearTimeout=="function"?clearTimeout:void 0,rDt=typeof Promise=="function"?Promise:void 0,u0n=typeof queueMicrotask=="function"?queueMicrotask:typeof rDt<"u"?function(t){return rDt.resolve(null).then(t).catch(l0n)}:O6e;function l0n(t){setTimeout(function(){throw t})}function W3e(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),Zte(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);Zte(e)}function gF(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 nDt(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 M5=Math.random().toString(36).slice(2),bO="__reactFiber$"+M5,rre="__reactProps$"+M5,m1="__reactContainer$"+M5,E6e="__reactEvents$"+M5,c0n="__reactListeners$"+M5,d0n="__reactHandles$"+M5;function E4(t){var e=t[bO];if(e)return e;for(var r=t.parentNode;r;){if(e=r[m1]||r[bO]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=nDt(t);t!==null;){if(r=t[bO])return r;t=nDt(t)}return e}t=r,r=t.parentNode}return null}function dre(t){return t=t[bO]||t[m1],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function u5(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(dt(33))}function obe(t){return t[rre]||null}var P6e=[],l5=-1;function xF(t){return{current:t}}function yl(t){0>l5||(t.current=P6e[l5],P6e[l5]=null,l5--)}function Zu(t,e){l5++,P6e[l5]=t.current,t.current=e}var SF={},My=xF(SF),F_=xF(!1),A4=SF;function S5(t,e){var r=t.type.contextTypes;if(!r)return SF;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 k_(t){return t=t.childContextTypes,t!=null}function kye(){yl(F_),yl(My)}function oDt(t,e,r){if(My.current!==SF)throw Error(dt(168));Zu(My,e),Zu(F_,r)}function Pjt(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(dt(108,Zwn(t)||"Unknown",o));return vc({},r,n)}function qye(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||SF,A4=My.current,Zu(My,t),Zu(F_,F_.current),!0}function iDt(t,e,r){var n=t.stateNode;if(!n)throw Error(dt(169));r?(t=Pjt(t,e,A4),n.__reactInternalMemoizedMergedChildContext=t,yl(F_),yl(My),Zu(My,t)):yl(F_),Zu(F_,r)}var l1=null,ibe=!1,J3e=!1;function Mjt(t){l1===null?l1=[t]:l1.push(t)}function f0n(t){ibe=!0,Mjt(t)}function TF(){if(!J3e&&l1!==null){J3e=!0;var t=0,e=uu;try{var r=l1;for(uu=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}l1=null,ibe=!1}catch(o){throw l1!==null&&(l1=l1.slice(t+1)),ejt(tJe,TF),o}finally{uu=e,J3e=!1}}return null}var c5=[],d5=0,Bye=null,Uye=0,DS=[],jS=0,N4=null,c1=1,d1="";function T4(t,e){c5[d5++]=Uye,c5[d5++]=Bye,Bye=t,Uye=e}function Rjt(t,e,r){DS[jS++]=c1,DS[jS++]=d1,DS[jS++]=N4,N4=t;var n=c1;t=d1;var o=32-GC(n)-1;n&=~(1<<o),r+=1;var i=32-GC(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,c1=1<<32-GC(e)+o|r<<o|n,d1=i+t}else c1=1<<i|r<<o|n,d1=t}function cJe(t){t.return!==null&&(T4(t,1),Rjt(t,1,0))}function dJe(t){for(;t===Bye;)Bye=c5[--d5],c5[d5]=null,Uye=c5[--d5],c5[d5]=null;for(;t===N4;)N4=DS[--jS],DS[jS]=null,d1=DS[--jS],DS[jS]=null,c1=DS[--jS],DS[jS]=null}var lw=null,uw=null,Bl=!1,KC=null;function Ijt(t,e){var r=$S(5,n
|
||
|
|
Error generating stack: `+i.message+`
|
||
|
|
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function Y3e(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function D6e(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var w0n=typeof WeakMap=="function"?WeakMap:Map;function i$t(t,e,r){r=f1(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){Xye||(Xye=!0,V6e=n),D6e(t,e)},r}function a$t(t,e,r){r=f1(-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(){D6e(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){D6e(t,e),typeof n!="function"&&(bF===null?bF=new Set([this]):bF.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function hDt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new w0n;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=j0n.bind(null,t,e,r),e.then(t,t))}function gDt(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 yDt(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=f1(-1,1),e.tag=2,yF(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var S0n=y1.ReactCurrentOwner,L_=!1;function Nb(t,e,r,n){e.child=t===null?Fjt(e,null,r,n):x5(e,t.child,r,n)}function bDt(t,e,r,n,o){r=r.render;var i=e.ref;return _5(e,o),n=SJe(t,e,r,n,i,o),r=CJe(),t!==null&&!L_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,g1(t,e,o)):(Bl&&r&&cJe(e),e.flags|=1,Nb(t,e,n,o),e.child)}function _Dt(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!NJe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,s$t(t,e,i,n,o)):(t=Mye(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:Qte,r(a,n)&&t.ref===e.ref)return g1(t,e,o)}return e.flags|=1,t=vF(i,n),t.ref=e.ref,t.return=e,e.child=t}function s$t(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(Qte(i,n)&&t.ref===e.ref)if(L_=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(L_=!0);else return e.lanes=t.lanes,g1(t,e,o)}return j6e(t,e,r,n,o)}function u$t(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},Zu(m5,sw),sw|=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,Zu(m5,sw),sw|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,Zu(m5,sw),sw|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,Zu(m5,sw),sw|=n;return Nb(t,e,o,r),e.child}function l$t(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function j6e(t,e,r,n,o){var i=k_(r)?A4:My.current;return i=S5(e,i),_5(e,o),r=SJe(t,e,r,n,i,o),n=CJe(),t!==null&&!L_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,g1(t,e,o)):(Bl&&n&&cJe(e),e.flags|=1,Nb(t,e,r,o),e.child)}function vDt(t,e,r,n,o){if(k_(r)){var i=!0;qye(e)}else i=!1;if(_5(e,o),e.stateNode===null)Oye(t,e),$jt(e,r,n),N6e(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=FS(l):(l=k_(r)?A4:My.current,l=S5(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)&&dDt(e,a,n,l),uF=!1;var f=e.memoizedState;a.state=f,Hye(e,n,a,o),u=e.memoizedState,s!==n||f!==u||F_.current||uF?(typeof c=="function"&&(A6e(e,r,c,n),u=e.memoizedState),(s=uF||cDt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount
|
||
|
|
`)}});var GVt=S(y_e=>{"use strict";Object.defineProperty(y_e,"__esModule",{value:!0});y_e.CohereTimeoutError=void 0;var r5e=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};y_e.CohereTimeoutError=r5e});var $c=S(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0});k5.CohereTimeoutError=k5.CohereError=void 0;var xxn=KVt();Object.defineProperty(k5,"CohereError",{enumerable:!0,get:function(){return xxn.CohereError}});var Txn=GVt();Object.defineProperty(k5,"CohereTimeoutError",{enumerable:!0,get:function(){return Txn.CohereTimeoutError}})});var XVt=S(TO=>{"use strict";var Oxn=TO&&TO.__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]}),Exn=TO&&TO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pxn=TO&&TO.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Oxn(r,e,n[o]);return Exn(r,e),r}}();Object.defineProperty(TO,"__esModule",{value:!0});TO.BadRequestError=void 0;var Mxn=Pxn($c()),n5e=class t extends Mxn.CohereError{constructor(e,r){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};TO.BadRequestError=n5e});var ZVt=S(OO=>{"use strict";var Rxn=OO&&OO.__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]}),Ixn=OO&&OO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Axn=OO&&OO.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Rxn(r,e,n[o]);return Ixn(r,e),r}}();Object.defineProperty(OO,"__esModule",{value:!0});OO.UnauthorizedError=void 0;var Nxn=Axn($c()),o5e=class t extends Nxn.CohereError{constructor(e,r){super({message:"UnauthorizedError",statusCode:401,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};OO.UnauthorizedError=o5e});var YVt=S(EO=>{"use strict";var Dxn=EO&&EO.__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]}),jxn=EO&&EO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$xn=EO&&EO.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Dxn(r,e,n[o]);return jxn(r,e),r}}();Object.defineProperty(EO,"__esModule",{value:!0});EO.ForbiddenError=void 0;var Lxn=$xn($c()),i5e=class t extends Lxn.CohereError{constructor(e,r){super({message:"ForbiddenError",statusCode:403,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};EO.ForbiddenError=i5e});var QVt=S(PO=>{"use strict";var Fxn=PO&&PO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(
|
||
|
|
`));return r(o)}});var MOn,q_e,MWt=v(()=>{A5e();MOn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},q_e=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(PWt(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),MOn)}})});var RWt=v(()=>{});var IWt=v(()=>{});var B_e,AWt=v(()=>{B_e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var N5e=v(()=>{RWt();AWt();IWt()});var aGi,NWt=v(()=>{N5e();aGi={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:B_e.name}});var DWt=v(()=>{A5e();MWt();NWt()});var jWt=v(()=>{});var $Wt=v(()=>{jWt()});var LWt=v(()=>{});var FWt=v(()=>{});var kWt=v(()=>{});function ROn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var BF,qWt=v(()=>{BF=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");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=ROn(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 U5,BWt=v(()=>{U5=class{constructor(e){x(this,"statusCode");x(this,"reason");x(this,"headers");x(this,"body");this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let r=e;return typeof r.statusCode=="number"&&typeof r.headers=="object"}}});var UWt=v(()=>{});var zWt=v(()=>{});var Kre=v(()=>{$Wt();LWt();FWt();kWt();qWt();BWt();UWt();zWt()});var VWt,IOn,AOn,HWt,D5e=v(()=>{Kre();VWt=$(VS()),IOn=t=>e=>{throw e},AOn=(t,e)=>{},HWt=t=>(e,r)=>async n=>{if(!BF.isInstance(n.request))return e(n);let i=(0,VWt.getSmithyContext)(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||IOn)(a));return(u.successHandler||AOn)(l.response,a),l}});var NOn,U_e,WWt=v(()=>{D5e();NOn={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},U_e=t=>({applyToStack:e=>{e.addRelativeTo(HWt(t),NOn)}})});var JWt=v(()=>{D5e();WWt()});var P1,KWt=v(()=>{P1=t=>{if(typeof t=="function")return t;let e=Promise.resolve(t);return()=>e}});function j5e(t,e,r,n,o){return async function*(a,s,...u){let l=s,c=a.startingToken??l[r],d=!0,f;for(;d;){if(l[r]=c,o&&(l[o]=l[o]??a.pageSize),a.client instanceof t)f=await DOn(e,a.client,s,a.withCommand,...u);else throw new Error(`Invalid client, expected instance of ${t.name}`);yield f;let p=c;c=jOn(f,n),d=!!(c&&(!a.stopOnSameToken||c!==p))}return void 0}}var DOn,jOn,GWt=v(()=>{DOn=async(t,e,r,n=i=>i,...o)=>{let i=new t(r);return i=n(i)??i,await e.send(i,...o)};jOn=(t,e)=>{let r=t,n=e.split(".");for(let o of n){if(!r||typeof r!="object")return;r=r[o]}return r}});var XWt,$5e,ZWt,UF,r2,YWt,L5e=v(()=>{XWt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$5e=Object.entries(XWt).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),ZWt=XWt.split(""),UF=6,r2=8,YWt=63});var gw,QWt=v(()=>{L5e();gw=t=>{let e=t.length/4*3;t.slice(-2)==="=="?e-=2:t.slice(-1)==="="&&e--;let r=ne
|
||
|
|
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 yw(i);if(o==="hex")return $3t(i);if(o===void 0||o==="utf8"||o==="utf-8")return z_e(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(F3t);if(e=!0,k3t(t))return n(t);if(k5e(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},k3t=t=>typeof Blob=="function"&&t instanceof Blob});var U3t=v(()=>{});var z5e=v(()=>{c3t();d3t();p3t();m3t();h3t();g3t();B3t();U3t()});var M1,V5e=v(()=>{z5e();M1=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return z5.mutate(t);if(!t)return z5.mutate(new Uint8Array);let r=e.streamCollector(t);return z5.mutate(await r)}});function H5e(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var z3t=v(()=>{});var VF,W5e=v(()=>{VF=t=>typeof t=="function"?t():t});var H_e,W_e=v(()=>{H_e=(t,e,r,n,o)=>({name:e,namespace:t,traits:r,input:n,output:o})});var V3t,H3t,J5e,W3t=v(()=>{Kre();V3t=$(VS());W_e();H3t=t=>(e,r)=>async n=>{let{response:o}=await e(n),{operationSchema:i}=(0,V3t.getSmithyContext)(r),[,a,s,u,l,c]=i??[];try{let d=await t.protocol.deserializeResponse(H_e(a,s,u,l,c),{...t,...r},o);return{response:o,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:o,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){let f="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
|
||
|
|
`+f}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(f):r.logger?.warn?.(f)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(U5.isInstance(o)){let{headers:p={}}=o,m=Object.entries(p);d.$metadata={httpStatusCode:o.statusCode,requestId:J5e(/^x-[\w-]+-request-?id$/,m),extendedRequestId:J5e(/^x-[\w-]+-id-2$/,m),cfId:J5e(/^x-[\w-]+-cf-id$/,m)}}}catch{}}throw d}},J5e=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var J3t,K3t,G3t=v(()=>{J3t=$(VS());W_e();K3t=t=>(e,r)=>async n=>{let{operationSchema:o}=(0,J3t.getSmithyContext)(r),[,i,a,s,u,l]=o??[],c=r.endpointV2?.url&&t.urlParser?async()=>t.urlParser(r.endpointV2.url):t.endpoint,d=await t.protocol.serializeRequest(H_e(i,a,s,u,l),n.input,{...t,...r,endpoint:c});return e({...n,request:d})}});function J_e(t){return{applyToStack:e=>{e.add(K3t(t),zOn),e.add(H3t(t),UOn),t.protocol.setSerdeContext(t)}}}var UOn,zOn,X3t=v(()=>{W3t();G3t();UOn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},zOn={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var HS,n2=v(()=>{HS=class{constructor(){x(this,"name");x(this,"namespace");x(this,"traits")}static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var K_e,Z3t,Y3t=v(()=>{n2();K_e=class K_e extends HS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"valueSchema");x(this,"symbol",K_e.symbol)}};x(K_e,"symbol",Symbol.for("@smithy/lis"));Z3t=K_e});var G_e,Q3t,e6t=v(()=>{n2();G_e=class G_e extends HS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"keySchema");x(this,"valueSchema");x(this,"symbol",G_e.symbol)}};x(G_e,"symbol",Symbol.for("@smithy/map"));Q3t=G_e});var X_e,t6t,r6t=v(()=>{n2();X_e=class X_e extends HS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"input");x(this,"output");x(this,"symbol",X_e.symbol)}};x(X_e,"symbol",Symbol.for("@smithy/ope"));t6t=X_e});var Y_e,Z_e,K5e=v(()=>{n2();Y_e=class Y_e extends HS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"memberNames");x(this,"memberList");x(this,"symbol",Y_e.symbol)}};x(Y_e,"symbol",Symbol.for("@smithy/str"));Z_e=Y_e});var Q_e,n6t,o6t=v(()=>{K5e();Q_e=class Q_e extends Z_e{constructor(){super(...arguments);x(this,"ctor");x(this,"symbol",Q_e.symbol)}};x(Q_e,"symbol",Symbol.for("@smithy/err"));n6t=Q_e});function o2(t){if(typeof t=="object")return t;t=t|0;let e={},r=0;for(let n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[n]=1);return e}var G5e=v(()=>{});function Yre(t,e){if(t instanceof oa)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=oa;return new r(t,e)}var HF,oa,X5e,VOn,i6t=v(()=>{W5e();G5e();HF=class HF{constructor(e,r){x(this,"ref");x(this,"memberName");x(this,"symbol",HF.symbol);x(this,"name");x(this,"schema");x(this,"_isMemberSchema");x(this,"traits");x(this,"memberTraits");x(this,"normalizedTraits");this.ref=e,this.memberName=r;let n=[],o=e,i=e;for(this._isMemberSchema=!1;X5e(o);)n.push(o[1]),o=o[0],i=VF(o),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let a=n.length-1;a>=0;--a){let s=n[a];Object.assign(this.memberTraits,o2(s))}}else this.memberTraits=0;if(i instanceof HF){let a=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},a,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=r??i.memberName;return}if(this.schema=VF(i),VOn(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"
|
||
|
|
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
|
||
|
|
`),XOn={warn:console.warn}});function rve(t){let e=t.getUTCFullYear(),r=t.getUTCMonth(),n=t.getUTCDay(),o=t.getUTCDate(),i=t.getUTCHours(),a=t.getUTCMinutes(),s=t.getUTCSeconds(),u=o<10?`0${o}`:`${o}`,l=i<10?`0${i}`:`${i}`,c=a<10?`0${a}`:`${a}`,d=s<10?`0${s}`:`${s}`;return`${ZOn[n]}, ${u} ${eKe[r]} ${e} ${l}:${c}:${d} GMT`}var ZOn,eKe,YOn,b6t,QOn,_6t,eEn,tEn,rEn,v6t,w6t,Qre,nEn,oEn,iEn,Q5e,aEn,sEn,uEn,BO,lEn,cEn,W5,S6t=v(()=>{Y5e();ZOn=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],eKe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];YOn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),b6t=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=YOn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=H5(W5(n)),d=BO(o,"month",1,12),f=BO(i,"day",1,31);return Qre(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},QOn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),_6t=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=QOn.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=H5(W5(n)),f=BO(o,"month",1,12),p=BO(i,"day",1,31),m=Qre(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-cEn(c)),m},eEn=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$/),tEn=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$/),rEn=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})$/),v6t=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=eEn.exec(t);if(e){let[r,n,o,i,a,s,u,l]=e;return Qre(H5(W5(i)),Q5e(o),BO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})}if(e=tEn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return iEn(Qre(nEn(i),Q5e(o),BO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l}))}if(e=rEn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return Qre(H5(W5(l)),Q5e(n),BO(o.trimLeft(),"day",1,31),{hours:i,minutes:a,seconds:s,fractionalMilliseconds:u})}throw new TypeError("Invalid RFC-7231 date-time value")},w6t=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=h6t(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))},Qre=(t,e,r,n)=>{let o=e-1;return sEn(t,o,r),new Date(Date.UTC(t,o,r,BO(n.hours,"hour",0,23),BO(n.minutes,"minute",0,59),BO(n.seconds,"seconds",0,60),lEn(n.fractionalMilliseconds)))},nEn=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+H5(W5(t));return r<e?r+100:r},oEn=50*365*24*60*60*1e3,iEn=t=>t.getTime()-new Date().getTime()>oEn?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,Q5e=t=>{let e=eKe.indexOf(t);if(e<0)throw new TypeError(`Invalid month: ${t}`);return e+1},aEn=[31,28,31,30,31,30,31,31,30,31,30,31],sEn=(t,e,r)=>{let n=aEn[e];if(e===1&&uEn(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${eKe[e]} in ${t}: ${r}`)},uEn=t=>t%4===0&&(t%100!==0||t%400===0),BO=(t,e,r,n)=>{let o=y6t(W5(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},lEn=t=>t==null?0:g6t("0."+t)*1e3,cEn=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new Typ
|
||
|
|
${this.getCanonicalPath(e)}
|
||
|
|
${qKt(e)}
|
||
|
|
${o.map(i=>`${i}:${r[i]}`).join(`
|
||
|
|
`)}
|
||
|
|
|
||
|
|
${o.join(";")}
|
||
|
|
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(N1(n));let a=await i.digest();return`${o}
|
||
|
|
${e}
|
||
|
|
${r}
|
||
|
|
${GS(a)}`}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(0,VKt.escapeUri)(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=UKt(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}});var une,WKt=v(()=>{eK();ZF();YF();NKe();PKt();IKt();DKt();$Kt();FKt();kKt();HKt();une=class extends Pve{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",new Ove)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>TKt)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=xve(h,p,d??this.service),g=LKt($Ke(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[PKe]=f.sessionToken),g.query[fKt]=Sve,g.query[pKt]=`${f.accessKeyId}/${y}`,g.query[OKe]=m,g.query[hKt]=i.toString(10);let b=DKe(g,a,u);return g.query[mKt]=this.getCanonicalHeaderList(b),g.query[EKe]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await Tve(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=xve(l,u,s??this.service),f=await Tve({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=GS(await p.digest()),h=[SKt,c,d,i,m,f].join(`
|
||
|
|
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:r.priorSignature}).then(s=>({message:r.message,signature:s}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(N1(r)),GS(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.regionProvider(),c=$Ke(r),{longDate:d,shortDate:f}=this.formatDate(n),p=xve(f,l,s??this.service);c.headers[RKe]=d,u.sessionToken&&(c.headers[bKt]=u.sessionToken);let m=await Tve(c,this.sha256);!jKt(sne,c.headers)&&this.applyChecksum&&(c.headers[sne]=m);let h=DKe(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[MKe]=`${Sve} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,Sve),s=new this.sha256(await o);return s.update(N1(a)),GS(await s.digest())}getSigningKey(r,n,o,i){return EKt(this.sha256,r,o,n,i||this.service)}}});var JKt=v(()=>{});var KKt=v(()=>{WKt();YF();NKe();JKt()});function IEn(t,{credentials:e,credentialDefaultProvider:r}){let n;return e?e?.memoized?n=e:n=lJt(e,uJt,cKe):r?n=P1(r(Object.assign({},t,{parentClientConfig:t}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function AEn(t,e){if(e.configBound)return e;let r=async n=>e({...n,callerClientConfig:t});return r.memoized=e.memoized,r.configBound=!0,r}var Mve,GKt=v(()=>{bve();UO();KKt();Mve=t=>{let e=t.credentials,r=!!t.credentials,n;Object.defineProperty(t,"credentials",{set(l){l&&l!==e&&l!==n&&(r=!0),e=l;let c=IEn(t,{credentials:e,credentialDefaultProvider:t.credentialDefaultProvider}),d=AEn(t,c);if(r&&!d.attributed){let f=typeof e=="object"&&e!==null;n=async p=>{let h=await d(p);return f&&(!h.$source||Object.keys(h.$source).length===0)?Q5(h,"CREDENTIALS_CODE","e"):h},n.memoized=d.memoized,n.configBound=d.configBound,n.attributed=!0}else n=d},get(){return n},enumerable:!0,configurable:!0}),t.credentials=e;let{signingEscapePath:o=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:a}=t,s;return t.signer?s=P1(t.signer):t.regionInfoProvider?s=()=>P1(t.region)().then(async l=>[await t.regionInfoProvider(l,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},l]).then(([l,c])=>{let{signingRegion:d,signingService:f}=l;t.signingRegion=t.signingRegion||d||c,t.signingName=t.signingName||f||t.serviceId;let p={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},m=t.signerConstructor||une;return new m(p)}):s=async l=>{l=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await P1(t.region)(),properties:{}},l);let c=l.signingRegion,d=l.signingName;t.signingRegion=t.signingRegion||c,t.signingName=t.signingName||d||t.serviceId;let f={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},p=t.signerConstructor||une;return new p(f)},Object.assign(t,{systemClockOffset:i,signingEscapePath:o,signer:s})}});var XKt=v(()=>{oKt();aKt();sKt();GKt()});var ZKt=v(()=>{XKt();iKt()});var YKt,Rve,QKt=v(()=>{YKt=typeof TextEncoder=="function"?new TextEncoder:null,Rve=t=>{if(typeof t=="string"){if(YKt)return YKt.encode(t).byteLength;let e=t.length;for(let r=e-1;r>=0;r--){let n=t.charCodeAt(r);n>127&
|
||
|
|
- loopback CIDR 127.0.0.0/8 or [::1/128]
|
||
|
|
- ECS container host 169.254.170.2
|
||
|
|
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var tZt=v(()=>{});var rZt=v(()=>{tZt()});var nZt=v(()=>{});var oZt=v(()=>{});var iZt=v(()=>{});function WIn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var hSe,aZt=v(()=>{hSe=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");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=WIn(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 sZt=v(()=>{});var uZt=v(()=>{});var lZt=v(()=>{});var cZt=v(()=>{rZt();nZt();oZt();iZt();aZt();sZt();uZt();lZt()});function dZt(t){return new hSe({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 fZt(t,e){let n=await q3t(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 Nm("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:b6t(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Nm(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Nm(`Server responded with status: ${t.statusCode}`,{logger:e})}var pZt=v(()=>{qF();cZt();Bo();z5e()});var mZt,hZt=v(()=>{mZt=(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 sGe,gZt=v(()=>{Zre();qF();eZt();pZt();hZt();sGe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Nm("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);QXt(n,t.logger);let o=new zF;return mZt(async()=>{let i=dZt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return fZt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var yZt=v(()=>{gZt()});function JIn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function KIn(t){return{schemeId:"smithy.api#noAuth"}}var yne,bZt,_Zt,GIn,vZt,uGe=v(()=>{aK();yne=$(VS());bne();bZt=async(t,e,r)=>({operation:(0,yne.getSmithyContext)(e).operation,region:await(0,yne.normalizeProvider)(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});_Zt=t=>{let e=[];switch(t.operation){case"AssumeRoleWithWebIdentity":{e.push(KIn(t));break}default:e.push(JIn(t))}return e},GIn=t=>Object.assign(t,{stsClientCtor:ZS}),vZt=t=>{let e=GIn(t),r=Mve(e);return Object.assign(r,{authSchemePreference:(0,yne.normalizeProvider)(t.authSchemePreference??[])})}});var wZt,gSe,ySe=v(()=>{wZt=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),gSe={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:
|
||
|
|
${this.getCanonicalPath(e)}
|
||
|
|
${GQt(e)}
|
||
|
|
${o.map(i=>`${i}:${r[i]}`).join(`
|
||
|
|
`)}
|
||
|
|
|
||
|
|
${o.join(";")}
|
||
|
|
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(b2.toUint8Array(n));let a=await i.digest();return`${o}
|
||
|
|
${e}
|
||
|
|
${r}
|
||
|
|
${ik.toHex(a)}`}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 TSe.escapeUri(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=yNn(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}},NGe=class extends ISe{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",new RGe)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>HQt)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=PSe(h,p,d??this.service),g=KQt(AGe(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[$Ge]=f.sessionToken),g.query[IQt]=OSe,g.query[AQt]=`${f.accessKeyId}/${y}`,g.query[DGe]=m,g.query[DQt]=i.toString(10);let b=MGe(g,a,u);return g.query[NQt]=this.getCanonicalHeaderList(b),g.query[jGe]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await MSe(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=PSe(l,u,s??this.service),f=await MSe({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=ik.toHex(await p.digest()),h=[UQt,c,d,i,m,f].join(`
|
||
|
|
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:r.priorSignature}).then(s=>({message:r.message,signature:s}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(b2.toUint8Array(r)),ik.toHex(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.regionProvider(),c=AGe(r),{longDate:d,shortDate:f}=this.formatDate(n),p=PSe(f,l,s??this.service);c.headers[FGe]=d,u.sessionToken&&(c.headers[FQt]=u.sessionToken);let m=await MSe(c,this.sha256);!JQt(RSe,c.headers)&&this.applyChecksum&&(c.headers[RSe]=m);let h=MGe(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[LGe]=`${OSe} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,OSe),s=new this.sha256(await o);return s.update(b2.toUint8Array(a)),ik.toHex(await s.digest())}getSigningKey(r,n,o,i){return WQt(this.sha256,r,o,n,i||this.service)}},_Nn={SignatureV4a:null};pi.ALGORITHM_IDENTIFIER=OSe;pi.ALGORITHM_IDENTIFIER_V4A=mNn;pi.ALGORITHM_QUERY_PARAM=IQt;pi.ALWAYS_UNSIGNABLE_HEADERS=kQt;pi.AMZ_DATE_HEADER=FGe;pi.AMZ_DATE_QUERY_PARAM=DGe;pi.AUTH_HEADER=LGe;pi.CREDENTIAL_QUERY_PARAM=AQt;pi.DATE_HEADER=jQt;pi.EVENT_ALGORITHM_IDENTIFIER=UQt;pi.EXPIRES_QUERY_PARAM=DQt;pi.GENERATED_HEADERS=$Qt;pi.HOST_HEADER=fNn;pi.KEY_TYPE_IDENTIFIER=kGe;pi.MAX_CACHE_SIZE=VQt;pi.MAX_PRESIGNED_TTL=HQt;pi.PROXY_HEADER_PATTERN=qQt;pi.REGION_SET_PARAM=dNn;pi.SEC_HEADER_PATTERN=BQt;pi.SHA256_HEADER=RSe;pi.SIGNATURE_HEADER=LQt;pi.SIGNATURE_QUERY_PARAM=jGe;pi.SIGNED_HEADERS_QUERY_PARAM=NQt;pi.SignatureV4=NGe;pi.SignatureV4Base=ISe;pi.TOKEN_HEADER=FQt;pi.TOKEN_QUERY_PARAM=$Ge;pi.UNSIGNABLE_PATTERNS=pNn;pi.UNSIGNED_PAYLOAD=zQt;pi.clearCredentialCache=hNn;pi.createScope=PSe;pi.getCanonicalHeaders=MGe;pi.getCanonicalQuery=GQt;pi.getPayloadHash=MSe;pi.getSigningKey=WQt;pi.hasHeader=JQt;pi.moveHeadersToQuery=KQt;pi.prepareRequest=AGe;pi.signatureV4aContainer=_Nn});var wc=S((sva,ZQt)=>{"use strict";ZQt.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)},StringPrototype
|
||
|
|
`;super(r),this.name="AggregateError",this.errors=e}};UGe.exports={AggregateError:BGe,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 ANn},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:NNn,deprecate(t,e){return t},addAbortListener:One().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);cer(e,"signal"),DNn(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[PNn]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[MNn](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:RNn.any||function(e){if(e.length===1)return e[0];let r=new INn,n=()=>r.abort();return e.forEach(o=>{cer(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};UGe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var qb=S((dva,per)=>{"use strict";var{format:jNn,inspect:jSe,AggregateError:$Nn}=Ly(),LNn=globalThis.AggregateError||$Nn,FNn=Symbol("kIsNodeError"),kNn=["string","function","number","object","Function","Object","boolean","bigint","symbol"],qNn=/^([A-Z][a-z0-9]*)+$/,BNn="__node_internal_",$Se={};function _2(t,e){if(!t)throw new $Se.ERR_INTERNAL_ASSERTION(e)}function der(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 UNn(t,e,r){if(typeof e=="function")return _2(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 _2(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:jNn(e,...r)}function Ag(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(UNn(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[FNn]=!0,$Se[t]=n}function fer(t){let e=BNn+t.name;return Object.defineProperty(t,"name",{value:e}),t}function zNn(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new LNn([e,t],e.message);return r.code=e.code,r}return t||e}var zGe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new $Se.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Ag("ERR_ASSERTION","%s",Error);Ag("ERR_INVALID_ARG_TYPE",(t,e,r)=>{_2(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)_2(typeof u=="string","All expected entries have to be of type string"),kNn.includes(u)?o.push(u.toLowerCase()):qNn.test(u)?i.push(u):(_2(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
|
||
|
|
`)>=0)return!1;return!0}function bFn(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=tE.call(Array(t.indent+1)," ");else return null;return{base:r,prev:tE.call(Array(e+1),r)}}function l7e(t,e){if(t.length===0)return"";var r=`
|
||
|
|
`+e.prev+e.base;return r+tE.call(t,","+r)+`
|
||
|
|
`+e.prev}function f0e(t,e){var r=u7e(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=V1(t,o)?e(t[o],t):""}var i=typeof n7e=="function"?n7e(t):[],a;if(DK){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)V1(t,u)&&(r&&String(Number(u))===u&&u<t.length||DK&&a["$"+u]instanceof Symbol||(Cnr.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof n7e=="function")for(var l=0;l<i.length;l++)xnr.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var Anr=S((Uva,Inr)=>{"use strict";var _Fn=Vne(),vFn=A2(),h0e=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},wFn=function(t,e){if(t){var r=h0e(t,e);return r&&r.value}},SFn=function(t,e,r){var n=h0e(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},CFn=function(t,e){return t?!!h0e(t,e):!1},xFn=function(t,e){if(t)return h0e(t,e,!0)};Inr.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new vFn("Side channel does not contain "+_Fn(n))},delete:function(n){var o=e&&e.next,i=xFn(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return wFn(e,n)},has:function(n){return CFn(e,n)},set:function(n,o){e||(e={next:void 0}),SFn(e,n,o)}};return r}});var p7e=S((zva,Nnr)=>{"use strict";Nnr.exports=Object});var jnr=S((Vva,Dnr)=>{"use strict";Dnr.exports=Error});var Lnr=S((Hva,$nr)=>{"use strict";$nr.exports=EvalError});var knr=S((Wva,Fnr)=>{"use strict";Fnr.exports=RangeError});var Bnr=S((Jva,qnr)=>{"use strict";qnr.exports=ReferenceError});var znr=S((Kva,Unr)=>{"use strict";Unr.exports=SyntaxError});var Hnr=S((Gva,Vnr)=>{"use strict";Vnr.exports=URIError});var Jnr=S((Xva,Wnr)=>{"use strict";Wnr.exports=Math.abs});var Gnr=S((Zva,Knr)=>{"use strict";Knr.exports=Math.floor});var Znr=S((Yva,Xnr)=>{"use strict";Xnr.exports=Math.max});var Qnr=S((Qva,Ynr)=>{"use strict";Ynr.exports=Math.min});var tor=S((ewa,eor)=>{"use strict";eor.exports=Math.pow});var nor=S((twa,ror)=>{"use strict";ror.exports=Math.round});var ior=S((rwa,oor)=>{"use strict";oor.exports=Number.isNaN||function(e){return e!==e}});var sor=S((nwa,aor)=>{"use strict";var TFn=ior();aor.exports=function(e){return TFn(e)||e===0?e:e<0?-1:1}});var lor=S((owa,uor)=>{"use strict";uor.exports=Object.getOwnPropertyDescriptor});var m7e=S((iwa,cor)=>{"use strict";var g0e=lor();if(g0e)try{g0e([],"length")}catch{g0e=null}cor.exports=g0e});var por=S((awa,dor)=>{"use strict";var y0e=Object.defineProperty||!1;if(y0e)try{y0e({},"a",{value:1})}catch{y0e=!1}dor.exports=y0e});var hor=S((swa,mor)=>{"use strict";mor.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 bor=S((uwa,yor)=>{"use strict";var gor=typeof Symbol<"u"&&Symbol,OFn=hor();yor.exports=function(){return typeof gor!="function"||typeof Symbol!="function"||typeof gor("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:OFn()}});var h7e=S((lwa,_or)=>{"use strict";_or.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var g7e=S((cwa,vor)=>{"use strict";var EFn=p7e();vor.exports=EFn.getPrototypeOf||null});var Cor=S((dwa,Sor)=>{"use strict";var PFn="Function.prototype.bind called on incompatible ",MFn=Object.prototype.toString,RFn=Math.max,IFn="[object Function]",wor=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},AFn=function(e,r){
|
||
|
|
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return Gir(this,arguments,function*(){var r,n,o,i;this.controller.signal;let a=Xir(this.stream),s="",u=!1;try{for(var l=!0,c=Kir(a),d;d=yield cx(c.next()),r=d.done,!r;l=!0){i=d.value,l=!1;let f=i;s+=this.decodeChunk(f);let p;for(;(p=s.indexOf(this.messageTerminator))>=0;){let m=s.slice(0,p+1);if(s=s.slice(p+this.messageTerminator.length),!m.trim())continue;if(!u&&this.prefix!=null){let y=m.indexOf(this.prefix);if(y===-1)continue;u=!0,m=m.slice(y+this.prefix.length)}if(this.streamTerminator!=null&&m.includes(this.streamTerminator))return yield cx(void 0);let h=yield cx(this.parse(JSON.parse(m)));yield yield cx(h),u=!1}}}catch(f){n={error:f}}finally{try{!l&&!r&&(o=c.return)&&(yield cx(o.call(c)))}finally{if(n)throw n.error}}})}[Symbol.asyncIterator](){return Gir(this,arguments,function*(){var r,n,o,i;try{for(var a=!0,s=Kir(this.iterMessages()),u;u=yield cx(s.next()),r=u.done,!r;a=!0)i=u.value,a=!1,yield yield cx(i)}catch(l){n={error:l}}finally{try{!a&&!r&&(o=s.return)&&(yield cx(o.call(s)))}finally{if(n)throw n.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else hBn.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};_w.Stream=z7e;function Xir(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return Jir(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 Jir(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var Zir=S(L0e=>{"use strict";Object.defineProperty(L0e,"__esModule",{value:!0});L0e.Stream=void 0;var yBn=V7e();Object.defineProperty(L0e,"Stream",{enumerable:!0,get:function(){return yBn.Stream}})});var Yir=S(roe=>{"use strict";var bBn=roe&&roe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(roe,"__esModule",{value:!0});roe.encodeAsFormParameter=vBn;var _Bn=bBn(A7e());function vBn(t){let r=_Bn.default.stringify(t,{encode:!1}).split("&").map(n=>{let[o,i]=n.split("=");return[o,i]});return Object.fromEntries(r)}});var tar=S((tSa,ear)=>{"use strict";var H7e=Object.defineProperty,wBn=Object.getOwnPropertyDescriptor,SBn=Object.getOwnPropertyNames,CBn=Object.prototype.hasOwnProperty,xBn=(t,e)=>{for(var r in e)H7e(t,r,{get:e[r],enumerable:!0})},TBn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of SBn(e))!CBn.call(t,o)&&o!==r&&H7e(t,o,{get:()=>e[o],enumerable:!(n=wBn(e,o))||n.enumerable});return t},OBn=t=>TBn(H7e({},"__esModule",{value:!0}),t),Qir={};xBn(Qir,{Blob:()=>MBn,File:()=>RBn,FormData:()=>PBn});ear.exports=OBn(Qir);var EBn=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:PBn,Blob:MBn,File:RBn}=EBn});var mar=S((rSa,par)=>{"use strict";var K7e=Object.defineProperty,IBn=Object.getOwnPropertyDescriptor,ABn=Object.getOwnPropertyNames,NBn=Object.prototype.hasOwnProperty,DBn=(t,e)=>{for(var r in e)K7e(t,r,{get:e[r],enumerable:!0})},jBn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ABn(e))!NBn.call(t,o)&&o!==r&&K7e(t,o,{get:()=>e[o],enumerable:!(n=IBn(e,o))||n.enumerable});return t},$Bn=t=>jBn(K7e({},"__esModule",{value:!0}),t),G7e=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Fc=(t,e,r)=>(G7e(t,e,"read from private field"),r?r.call(t):e.get(t)),oE=(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)},noe=(t,e,r,n)=>(G7e(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),W7e=(t,e,r)=>(G7e(t,e,"access private method"),r),uar={};DBn(uar,{FormDataEncoder:()=>VBn,isFile:()=>F2,isFormData:()=>dar});par.exports=$Bn(uar);var H1=t=>typeof t=="function",LBn=t=>H1(t[Symbol.asyncIterator]),rar=65536;function*lar(t){if(t.byteLength<=rar){yield t;return}let e=
|
||
|
|
`||e===`
|
||
|
|
`&&n[r-1]!=="\r"?`\r
|
||
|
|
`:e),BBn=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function iar(t){if(BBn(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function aar(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var UBn=t=>new Proxy(t,{get:(e,r)=>aar(e,r),has:(e,r)=>aar(e,r)!==void 0}),dar=t=>!!(t&&H1(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&H1(t.append)&&H1(t.getAll)&&H1(t.entries)&&H1(t[Symbol.iterator])),sar=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),F2=t=>!!(t&&typeof t=="object"&&H1(t.constructor)&&t[Symbol.toStringTag]==="File"&&H1(t.stream)&&t.name!=null),zBn={enableAdditionalHeaders:!1},F0e={writable:!1,configurable:!1},mk,ooe,k0e,ioe,L2,aoe,soe,q0e,B0e,X7e,J7e,far,VBn=class{constructor(t,e,r){if(oE(this,B0e),oE(this,J7e),oE(this,mk,`\r
|
||
|
|
`),oE(this,ooe,void 0),oE(this,k0e,void 0),oE(this,ioe,"-".repeat(2)),oE(this,L2,new TextEncoder),oE(this,aoe,void 0),oE(this,soe,void 0),oE(this,q0e,void 0),!dar(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(iar(e)?r=e:n=e,n||(n=qBn()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!iar(r))throw new TypeError("Expected options argument to be an object.");noe(this,soe,Array.from(t.entries())),noe(this,q0e,{...zBn,...r}),noe(this,ooe,Fc(this,L2).encode(Fc(this,mk))),noe(this,k0e,Fc(this,ooe).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,noe(this,aoe,Fc(this,L2).encode(`${Fc(this,ioe)}${this.boundary}${Fc(this,ioe)}${Fc(this,mk).repeat(2)}`));let o={"Content-Type":this.contentType},i=W7e(this,J7e,far).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=UBn(Object.freeze(o)),Object.defineProperties(this,{boundary:F0e,contentType:F0e,contentLength:F0e,headers:F0e})}*values(){for(let[t,e]of Fc(this,soe)){let r=F2(e)?e:Fc(this,L2).encode(car(e));yield W7e(this,B0e,X7e).call(this,t,r),yield r,yield Fc(this,ooe)}yield Fc(this,aoe)}async*encode(){for(let t of this.values())F2(t)?yield*kBn(t.stream()):yield*lar(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};mk=new WeakMap;ooe=new WeakMap;k0e=new WeakMap;ioe=new WeakMap;L2=new WeakMap;aoe=new WeakMap;soe=new WeakMap;q0e=new WeakMap;B0e=new WeakSet;X7e=function(t,e){let r="";if(r+=`${Fc(this,ioe)}${this.boundary}${Fc(this,mk)}`,r+=`Content-Disposition: form-data; name="${sar(t)}"`,F2(e)&&(r+=`; filename="${sar(e.name)}"${Fc(this,mk)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Fc(this,q0e).enableAdditionalHeaders===!0){let n=F2(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Fc(this,mk)}Content-Length: ${n}`)}return Fc(this,L2).encode(`${r}${Fc(this,mk).repeat(2)}`)};J7e=new WeakSet;far=function(){let t=0;for(let[e,r]of Fc(this,soe)){let n=F2(r)?r:Fc(this,L2).encode(car(r)),o=F2(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=W7e(this,B0e,X7e).call(this,e,n).byteLength,t+=o,t+=Fc(this,k0e)}return String(t+Fc(this,aoe).byteLength)}});var gar=S((oSa,har)=>{"use strict";har.exports=typeof self=="object"?self.FormData:window.FormData});var yar=S(Ng=>{"use strict";var HBn=Ng&&Ng.__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]}),WBn=Ng&&Ng.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GK=Ng&&Ng.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&HBn(r,e,n[o]);return WBn(r,e),r}}(),hk=Ng&&Ng.__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(Ng,"__esModule",{value:!0});Ng.WebFormData=Ng.Node16FormData=Ng.Node18FormData=void 0;Ng.newFormData=JBn;var U0e=qK();function Z7e(t){return typeof t=="object"&&t!=null&&"name"in t}function JBn(){return hk(this,void 0,void 0,function*(){let t;return U0e.RUNTIME.type==="node"&&U0e.RUNTIME.parsedVersion!=null&&U0e.RUNTIME.parsedVersion>=18?t=new z0e:U0e.RUNTIME.type==="node"?t=new V0e:t=new H0e,yield t.setup(),t})}var z0e=class{setup(){return hk(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>GK(tar()))).FormData})}append(e
|
||
|
|
`)),{ok:!0,value:e}):n}}});var tXe=S(eXe=>{"use strict";Object.defineProperty(eXe,"__esModule",{value:!0});eXe.stringifyValidationError=eUn;function eUn(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}});var nXe=S(J0e=>{"use strict";Object.defineProperty(J0e,"__esModule",{value:!0});J0e.JsonError=void 0;var tUn=tXe(),rXe=class t extends Error{constructor(e){super(e.map(tUn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};J0e.JsonError=rXe});var iXe=S(K0e=>{"use strict";Object.defineProperty(K0e,"__esModule",{value:!0});K0e.ParseError=void 0;var rUn=tXe(),oXe=class t extends Error{constructor(e){super(e.map(rUn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};K0e.ParseError=oXe});var Tar=S(k2=>{"use strict";Object.defineProperty(k2,"__esModule",{value:!0});k2.getSchemaUtils=uoe;k2.nullable=war;k2.optional=Sar;k2.optionalNullable=Car;k2.transform=xar;var aXe=Nh(),nUn=nXe(),oUn=iXe();function uoe(t){return{nullable:()=>war(t),optional:()=>Sar(t),optionalNullable:()=>Car(t),transform:e=>xar(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new oUn.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new nUn.JsonError(n.errors)}}}function war(t){let e={parse:(r,n)=>r==null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>aXe.SchemaType.NULLABLE};return Object.assign(Object.assign({},e),uoe(e))}function Sar(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:()=>aXe.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),uoe(e))}function Car(t){let e={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.json(r,n),getType:()=>aXe.SchemaType.OPTIONAL_NULLABLE};return Object.assign(Object.assign({},e),uoe(e))}function xar(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),uoe(r))}});var H_=S(e0=>{"use strict";Object.defineProperty(e0,"__esModule",{value:!0});e0.ParseError=e0.JsonError=e0.transform=e0.optional=e0.getSchemaUtils=void 0;var sXe=Tar();Object.defineProperty(e0,"getSchemaUtils",{enumerable:!0,get:function(){return sXe.getSchemaUtils}});Object.defineProperty(e0,"optional",{enumerable:!0,get:function(){return sXe.optional}});Object.defineProperty(e0,"transform",{enumerable:!0,get:function(){return sXe.transform}});var iUn=nXe();Object.defineProperty(e0,"JsonError",{enumerable:!0,get:function(){return iUn.JsonError}});var aUn=iXe();Object.defineProperty(e0,"ParseError",{enumerable:!0,get:function(){return aUn.ParseError}})});var Ear=S(uXe=>{"use strict";Object.defineProperty(uXe,"__esModule",{value:!0});uXe.bigint=cUn;var sUn=Nh(),Oar=Bb(),uUn=iE(),lUn=H_();function cUn(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e=="bigint"?{ok:!0,value:e}:typeof e=="number"?{ok:!0,value:BigInt(e)}:{ok:!1,errors:[{path:r,message:(0,Oar.getErrorMessageForIncorrectType)(e,"bigint | number")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="bigint"?{ok:!1,errors:[{path:r,message:(0,Oar.getErrorMessageForIncorrectType)(e,"bigint")}]}:{ok:!0,value:e},getType:()=>sUn.SchemaType.BIGINT};return Object.assign(Object.assign({},(0,uUn.maybeSkipValidation)(t)),(0,lUn.getSchemaUtils)(t))}});var Par=S(G0e=>{"use strict";Object.defineProperty(G0e,"__esModule",{value:!0});G0e.bigint=void 0;var dUn=Ear();Object.defineProperty(G0e,"bigint",{enumerable:!0,get:function(){return dUn.bigint}})});var Mar=S(cXe=>{"use strict";Object.defineProperty(cXe,"__esModule",{value:!0});cXe.date=gUn;var fUn=Nh(),lXe=Bb(),pUn=iE(),mUn=H_(),hUn=/^([+-]?\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])?|(0
|
||
|
|
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){return hoe(this,void 0,void 0,function*(){var o;yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};jg.StreamUtils=qXe;function Ssr(t,e){return yoe(this,arguments,function*(){var n,o,i,a;if(!t.body)throw e?.abort(),new e8.CohereError({message:"Attempted to iterate over a response with no body"});let s=new BXe,u=new gk,l=UXe(t.body);try{for(var c=!0,d=goe(g4n(l)),f;f=yield Vl(d.next()),n=f.done,!n;c=!0){a=f.value,c=!1;let p=a;for(let m of u.decode(p)){let h=s.decode(m);h&&(yield yield Vl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield Vl(i.call(d)))}finally{if(o)throw o.error}}for(let p of u.flush()){let m=s.decode(p);m&&(yield yield Vl(m))}})}function g4n(t){return yoe(this,arguments,function*(){var r,n,o,i;let a=new Uint8Array;try{for(var s=!0,u=goe(t),l;l=yield Vl(u.next()),r=l.done,!r;s=!0){i=l.value,s=!1;let c=i;if(c==null)continue;let d=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?new TextEncoder().encode(c):c,f=new Uint8Array(a.length+d.length);f.set(a),f.set(d,a.length),a=f;let p;for(;(p=y4n(a))!==-1;)yield yield Vl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yield Vl(o.call(u)))}finally{if(n)throw n.error}}a.length>0&&(yield yield Vl(a))})}function y4n(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 BXe=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]=_4n(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},gk=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 e8.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 e8.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new e8.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}};jg.LineDecoder=gk;gk.NEWLINE_CHARS=new Set([`
|
||
|
|
`,"\r"]);gk.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function b4n(t){let e=new gk,r=[];for(let n of t)r.push(...e.decode(n));return r}function _4n(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function UXe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return hoe(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 hoe(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var _oe=S(aE=>{"use strict";var v4n=aE&&aE.__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]}),w4n=aE&&aE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),S4n=aE&&aE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&v4n(r,e,n[o]);return w4n(r,e),r}}();Object.defineProperty(aE,"__esModule",{value:!0});aE.Document=void 0;var boe=S4n(se());aE.Document=boe.serialization.object({data:boe.serialization.record(boe.serialization.string(),boe.serialization.unknown()),id:boe.serialization.string().optional()})});var zXe=S(sE=>{"use strict";var C4n=sE&&sE.__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]}),x4n=sE&&sE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),T4n=sE&&sE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&C4n(r,e,n[o]);return x4n(r,e),r}}();Object.defineProperty(sE,"__esModule",{value:!0});sE.V2ChatStreamRequestDocumentsItem=void 0;var xsr=T4n(se()),O4n=_oe();sE.V2ChatStreamRequestDocumentsItem=xsr.serialization.undiscriminatedUnion([xsr.serialization.string(),O4n.Document])});var VXe=S(uE=>{"use strict";var E4n=uE&&uE.__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]}),P4n=uE&&uE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M4n=uE&&uE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&E4n(r,e,n[o]);return P4n(r,e),r}}();Object.defineProperty(uE,"__esModule",{value:!0});uE.V2ChatStreamRequestSafetyMode=void 0;var R4n=M4n(se());uE.V2ChatStreamRequestSafetyMode=R4n.serialization.enum_(["CONTEXTUAL","STRICT","OFF"])});var HXe=S(lE=>{"use strict";var I4n=lE&&lE.__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(
|
||
|
|
`)}}}}catch(P){s={error:P}}finally{try{!b&&!a&&(u=_.return)&&(yield u.call(_))}finally{if(s)throw s.error}}for(let P of O.flush()){let R=(0,lu.parseAWSEvent)(P);if(R){let I=yield(0,lu.mapResponseFromBedrock)(m,d,f,R);E.push(JSON.stringify(I)+`
|
||
|
|
`)}}return E.end(),{ok:!0,body:E,rawResponse:g.rawResponse}}else{let T=yield g.body;return{ok:!0,body:yield(0,lu.mapResponseFromBedrock)(m,d,f,T),rawResponse:g.rawResponse}}}catch(T){throw T}});lu.fetchOverride=too});var rD=S(YCe=>{"use strict";Object.defineProperty(YCe,"__esModule",{value:!0});YCe.CohereEnvironment=void 0;YCe.CohereEnvironment={Production:"https://api.cohere.com"}});var Ok=S((Ulr,QCe)=>{(function(t,e,r){typeof QCe<"u"&&QCe.exports?QCe.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",Ulr,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 Oet=S(G_=>{"use strict";var roo=G_&&G_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),noo=G_&&G_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Voe=G_&&G_.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&roo(r,e,n[o]);return noo(r,e),r}}(),S8=G_&&G_.__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())})},ooo=G_&&G_.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(G_,"__esModule",{value:!0});G_.V2=void 0;var exe=Voe(rD()),ia=Voe(se()),Vn=Voe(E1()),Ek=Voe(tD()),txe=ooo(Ok()),Lg=Voe($c()),Tet=class{constructor(e={}){this._options=e}chatStream(e,r){return ia.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return S8(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ia.fetcher)({url:(0,txe.default)((i=(o=yield ia.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ia.Supplier.get(this._options.environment))!==null&&i!==void 0?i:exe.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ia.Supplier.get(this._options.clientName))!=null?yield ia.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":ia.RUNTIME.type,"X-Fern-Runtime-Version":ia.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Ek.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(a.ok)return{data:new ia.Stream({stream:a.body,parse:s=>S8(this,void 0,void
|
||
|
|
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new je.BadRequestError(u.error.body,u.rawResponse);case 401:throw new je.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new je.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new je.NotFoundError(u.error.body,u.rawResponse);case 422:throw new je.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new je.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new je.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new je.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new je.InternalServerError(u.error.body,u.rawResponse);case 501:throw new je.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new je.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new je.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new $o.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new $o.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new $o.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":throw new $o.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){return mt.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){return tv(this,void 0,void 0,function*(){var n,o,i;let{accepts:a}=e,s=Xlr(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void 0?n:mt.fetcher)({url:(0,hx.default)((i=(o=yield mt.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield mt.Supplier.get(this._options.environment))!==null&&i!==void 0?i:mx.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield mt.Supplier.get(this._options.clientName))!=null?yield mt.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":mt.RUNTIME.type,"X-Fern-Runtime-Version":mt.RUNTIME.version,Accepts:a??void 0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ld.ChatRequest.jsonOrThrow(s,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:ld.NonStreamedChatResponse.parseOrThrow(u.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new je.BadRequestError(u.error.body,u.rawResponse);case 401:throw new je.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new je.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new je.NotFoundError(u.error.body,u.rawResponse);case 422:throw new je.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new je.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new je.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new je.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new je.InternalServerError(u.error.body,u.rawResponse);case 501:throw new je.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new je.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new je.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new $o.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new $o.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new $o.CohereTimeoutError("Timeout exceeded when calling POST
|
||
|
|
`}}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new je.BadRequestError(a.error.body,a.rawResponse);case 401:throw new je.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new je.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new je.NotFoundError(a.error.body,a.rawResponse);case 422:throw new je.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new je.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new je.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new je.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new je.InternalServerError(a.error.body,a.rawResponse);case 501:throw new je.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new je.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new je.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new $o.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new $o.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new $o.CohereTimeoutError("Timeout exceeded when calling POST /v1/generate.");case"unknown":throw new $o.CohereError({message:a.error.errorMessage,rawResponse:a.rawResponse})}})}generate(e,r){return mt.HttpResponsePromise.fromPromise(this.__generate(e,r))}__generate(e,r){return tv(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:mt.fetcher)({url:(0,hx.default)((i=(o=yield mt.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield mt.Supplier.get(this._options.environment))!==null&&i!==void 0?i:mx.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield mt.Supplier.get(this._options.clientName))!=null?yield mt.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":mt.RUNTIME.type,"X-Fern-Runtime-Version":mt.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ld.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(a.ok)return{data:ld.Generation.parseOrThrow(a.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new je.BadRequestError(a.error.body,a.rawResponse);case 401:throw new je.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new je.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new je.NotFoundError(a.error.body,a.rawResponse);case 422:throw new je.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new je.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new je.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new je.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new je.InternalServerError(a.error.body,a.rawResponse);case 501:throw new je.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new je.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new je.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new $o.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new $o.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new $o.CohereTimeoutError("Timeout exceeded when calling POST /v1/generate.");case"unknown":throw new
|
||
|
|
`).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=pcr.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=Jet.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=Jet.specialTokenRegex([...s]),c=t.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??t.length;for(let p of t.substring(u,d).matchAll(n)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...Koo(m,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(e.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},lxe=Jet;Woo(lxe,"specialTokenRegex",t=>new RegExp(t.map(e=>Goo(e)).join("|"),"g"))});var hcr=v(()=>{mcr()});async function gcr(t){return t in cxe||(cxe[t]=Xoo.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new lxe(e)).catch(e=>{throw delete cxe[t],e})),await cxe[t]}async function ycr(t){return gcr(Ket(t))}var cxe,Xoo,Get=v(()=>{zo();Iz();hcr();cxe={},Xoo=new IC({})});function i0(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 Zoo,Yoo,tie,sV,rv=v(()=>{zo();TC();fcr();Iz();_g();Hee();Get();Zoo=t=>t.startsWith("gpt-5")?"gpt-5":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;Yoo=()=>!1,tie=class extends Ti{constructor(e){super(e);x(this,"verbose");x(this,"callbacks");x(this,"tags");x(this,"metadata");this.verbose=e.verbose??Yoo(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.29")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,r){let n=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof n=="object"&&n!==null?n:{},[e]:r}}}},sV=class extends tie{constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i});x(this,"caller");x(this,"cache");x(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=ccr.global():this.cache=void 0,this.caller=new IC(n??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}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 ycr("modelName"in this?Zoo(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 sge(e):Array.isArray(e)?new uge(e.map(OC)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...r}){let n={...this._identifyingParams(),...r,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([o,i])=>i!==void 0).map(([o,i])=>`${o}:${JSON.stringify(i)}`).sort().join(",")}
|
||
|
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function Xcr(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 gxe(t){return!!t.finishReason&&Oio.includes(t.finishReason)}function Nk(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];gxe(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function iie(t){return this instanceof iie?(this.v=t,this):new iie(t)}function Eio(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(m){d(i[0][3],m)}}function u(f){f.value instanceof iie?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 Pio(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=Iio(e),[n,o]=r.tee();return{stream:Rio(n),response:Mio(o)}}async function Mio(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return mtt(Aio(e));e.push(o)}}function Rio(t){return Eio(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield iie(r.read());if(o)break;yield yield iie(mtt(n))}})}function Iio(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 Lh("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(Zcr),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new Lh(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(Zcr)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new bxe("Request aborted when reading from the stream"):s=new Lh("Error reading from the stream"),s})}}})}function Aio(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates){let o=0;for(let i of n.candidates)if(r.candidates||(r.candidates=[]),r.candidates[o]||(r.candidates[o]={index:o}),r.candidates[o].citationMetadata=i.citationMetadata,r.candidates[o].groundingMetadata=i.groundingMetadata,r.candidates[o].finishReason=i.finishReason,r.candidates[o].finishMessage=i.finishMessage,r.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){r.candidates[o].content||(r.candidates[o].content={role:i.content.role||"user",parts:[]});let a={};for(let s of i.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[o].content.parts.push(a)}o++}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function rdr(t,e,r,n){let o=await sie(e,mV.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return Pio(o)}async function ndr(t,e,r,n){let i=await(await sie(e,mV.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:mtt(i)}}function odr(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
|
||
|
|
`)===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 VI(t,e){if(!(this instanceof VI))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 km(e.headers),this.url=e.url||"",this._initBody(t)}function Tdr(t,e){return new Promise(function(r,n){var o=new yV(t,e);if(o.signal&&o.signal.aborted)return n(new gV("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:oao(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 VI(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 gV("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Ug.location.href?Ug.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&&(Vb.blob?i.responseType="blob":Vb.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof km||Ug.Headers&&e.headers instanceof Ug.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(R8(l)),i.setRequestHeader(l,Ctt(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 Ug,Vb,vdr,Sdr,tao,iao,gV,Odr=v(()=>{Ug=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Vb={searchParams:"URLSearchParams"in Ug,iterable:"Symbol"in Ug&&"iterator"in Symbol,blob:"FileReader"in Ug&&"Blob"in Ug&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Ug,arrayBuffer:"ArrayBuffer"in Ug};Vb.arrayBuffer&&(vdr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Sdr=ArrayBuffer.isView||function(t){return t&&vdr.indexOf(Object.prototype.toString.call(t))>-1});km.prototype.append=function(t,e){t=R8(t),e=Ctt(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};km.prototype.delete=function(t){delete this.map[R8(t)]};km.prototype.get=function(t){return t=R8(t),this.has(t)?this.map[t]:null};km.prototype.has=function(t){return this.map.hasOwnProperty(R8(t))};km.prototype.set=function(t,e){this.map[R8(t)]=Ctt(e)};km.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};km.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),xtt(t)};km.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),xtt(t)};km.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),xtt(t)};Vb.iterable&&(km.prototype[Symbol.iterator]=km.prototype.entries);tao=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];yV.prototype.clone=function(){return new yV(this,{body:this._bodyInit})};xdr.call(yV.prototype);xdr.call(VI.pro
|
||
|
|
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}r+=e.decode();for(let o of r.split(`
|
||
|
|
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},mao=t=>{if(!t)return Pdr;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=Edr);let o="";r.username&&(o=r.username,r.password&&(o+=`:${r.password}`),o+="@");let i=`${r.protocol}//${o}${r.hostname}:${n}${r.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},hao=Object.defineProperty,gao=(t,e,r)=>e in t?hao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ett=(t,e,r)=>(gao(t,typeof e!="symbol"?e+"":e,r),r),I8=class{constructor(e){Ett(this,"config"),Ett(this,"fetch"),Ett(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=mao(e?.host??Pdr)),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 Dk(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=pao(a.body),u=new Mtt(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await Dk(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 fao(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Dk(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Ott(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Dk(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Dk(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Dk(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Ott(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Ott(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await Dk(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await Dk(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},uIa=new I8});function HI(t,e){if(t.function===void 0)return;let r;if(e?.partial)try{r=L6(t.function.arguments??"{}")}catch{return}else try{r=JSON.parse(t.function.arguments)}catch(o){throw new CS([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
|
||
|
|
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function bV(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 vx(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var Mdr,Ow,Rdr=v(()=>{CQ();mS();zN();yJ();ZL();cWe();Mdr=class extends _J{constructor(e){super(e);x(this,"returnId",!1);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_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(mc(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(a=>HI(a,{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}},Ow=class extends Mdr{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await Wz(this.zodSchema,e);if(r.success)return r.data;throw new CS(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let r=(await super.parsePartialResult(e)).filter(o=>o.type===this.keyName),n=r;if(r.length)return this.returnId||(n=r.map(o=>o.args)),this.returnSingle?n[0]:n}async parseResult(e){let r=(await super.parsePartialResult(e,!1)).filter(o=>o.type===this.keyName),n=r;if(r.length)return this.returnId||(n=r.map(o=>o.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(o=>this._validateResult(o)))}}});var _V=v(()=>{zo();Rdr()});var Att,Idr=v(()=>{_dr();ra();aD();Sxe();xm();Qv();iD();XT();nO();_V();su();nv();Sy();Att=class extends Vy{constructor(e){super(e??{});x(this,"model","llama3");x(this,"numa");x(this,"numCtx");x(this,"numBatch");x(this,"numGpu");x(this,"mainGpu");x(this,"lowVram");x(this,"f16Kv");x(this,"logitsAll");x(this,"vocabOnly");x(this,"useMmap");x(this,"useMlock");x(this,"embeddingOnly");x(this,"numThread");x(this,"numKeep");x(this,"seed");x(this,"numPredict");x(this,"topK");x(this,"topP");x(this,"tfsZ");x(this,"typicalP");x(this,"repeatLastN");x(this,"temperature");x(this,"repeatPenalty");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"mirostat");x(this,"mirostatTau");x(this,"mirostatEta");x(this,"penalizeNewline");x(this,"streaming");x(this,"format");x(this,"keepAlive");x(this,"client");x(this,"checkOrPullModel",!1);x(this,"baseUrl","http://127.0.0.1:11434");x(this,"think");this.baseUrl=e?.baseUrl??un("OLLAMA_BASE_URL")??this.baseUrl,this.client=new I8({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers}),this.model=e?.model??this.model,this.numa=e?.numa,this.numCtx=e?.numCtx,this.numBatch=e?.numBatch,this.numGpu=e?.numGpu,this.mainGpu=e?.mainGpu,this.lowVram=e?.lowVram,this.f16Kv=e?.f16Kv,this.logitsAll=e?.logitsAll,this.vocabOnly=e?.vocabOnly,this.useMmap=e?.useMmap,this.useMlock=e?.useMlock,this.embeddingOnly=e?.embeddingOnly,this.numThread=e?.numThread,this.numKeep=e?.numKeep,this.seed=e?.seed,this.numPredict=e?.numPredict,this.topK=e?.topK,this.topP=e?.topP,this.tfsZ=e?.tfsZ,this.typicalP=e?.typicalP,this.repeatLastN=e?.repeatLastN,this.temperature=e?.temperature,this.repeatPenalty=e?.repeatPenalty,this.presencePenalty=e?.presencePenalty,this.frequencyPenalty=e?
|
||
|
|
|
||
|
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
||
|
|
`,t}var Ddr=v(()=>{});function Zr(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function Pe(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)}var a0=v(()=>{});var jtt,$tt=v(()=>{jtt=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return jtt=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});function cie(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var die,Cxe=v(()=>{die=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var Kt,qm,qc,jk,WI,A8,N8,D8,j8,$8,L8,F8,k8,q8,B8,JI,KI=v(()=>{Cxe();Kt=class extends Error{},qm=class t extends Kt{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let i=r;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new jk({message:n,cause:die(r)});let i=r?.error;return e===400?new A8(e,i,n,o):e===401?new N8(e,i,n,o):e===403?new D8(e,i,n,o):e===404?new j8(e,i,n,o):e===409?new $8(e,i,n,o):e===422?new L8(e,i,n,o):e===429?new F8(e,i,n,o):e>=500?new k8(e,i,n,o):new t(e,i,n,o)}},qc=class extends qm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},jk=class extends qm{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},WI=class extends jk{constructor({message:e}={}){super({message:e??"Request timed out."})}},A8=class extends qm{},N8=class extends qm{},D8=class extends qm{},j8=class extends qm{},$8=class extends qm{},L8=class extends qm{},F8=class extends qm{},k8=class extends qm{},q8=class extends Kt{constructor(){super("Could not parse response content as the length limit was reached")}},B8=class extends Kt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},JI=class extends Error{constructor(e){super(e)}}});function Ftt(t){return typeof t!="object"?{}:t??{}}function $dr(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ldr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function U8(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var bao,jdr,Hy,Ltt,Fdr,kdr,uD=v(()=>{KI();bao=/^[a-z][a-z0-9+.-]*:/i,jdr=t=>bao.test(t),Hy=t=>(Hy=Array.isArray,Hy(t)),Ltt=Hy;Fdr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Kt(`${t} must be an integer`);if(e<0)throw new Kt(`${t} must be a positive integer`);return e},kdr=t=>{try{return JSON.parse(t)}catch{return}}});var GI,z8=v(()=>{GI=t=>new Promise(e=>setTimeout(e,t))});var $k,ktt=v(()=>{$k="6.16.0"});function _ao(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function wao(){if(typeof navigator>"
|
||
|
|
`):[]}};Ew=new WeakMap,Pw=new WeakMap;vV.NEWLINE_CHARS=new Set([`
|
||
|
|
`,"\r"]);vV.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function pie(){}function Rxe(t,e,r){return!e||Ixe[t]>Ixe[r]?pie:e[t].bind(e)}function cd(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Pao;let n=lfr.get(e);if(n&&n[0]===r)return n[1];let o={error:Rxe("error",e,r),warn:Rxe("warn",e,r),info:Rxe("info",e,r),debug:Rxe("debug",e,r)};return lfr.set(e,[r,o]),o}var Ixe,Xtt,Pao,lfr,lD,mie=v(()=>{uD();Ixe={off:0,error:200,warn:300,info:400,debug:500},Xtt=(t,e,r)=>{if(t){if(Ldr(Ixe,t))return t;cd(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ixe))}`)}};Pao={error:pie,warn:pie,info:pie,debug:pie},lfr=new WeakMap;lD=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*Mao(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Kt("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 Kt("Attempted to iterate over a response with no body");let r=new Ztt,n=new vV,o=Utt(t.body);for await(let i of Rao(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*Rao(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"?V8(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=sfr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Iao(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var hie,ZI,Ztt,Ytt=v(()=>{a0();KI();fie();ufr();fie();Cxe();Mxe();mie();KI();ZI=class t{constructor(e,r,n){this.iterator=e,hie.set(this,void 0),this.controller=r,Zr(this,hie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?cd(n):console;async function*a(){if(o)throw new Kt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Mao(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 qm(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 qm(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(cie(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 vV,u=Utt(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 Kt("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(cie(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(hie=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,Pe(this,hie,"f")),new t(()=>o(r),this.controller,Pe(this,hie,"f"))]}toReadableStream(){let e=this,r;return Btt({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=V8(JSON.stringify(o)+`
|
||
|
|
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};Ztt=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]=Iao(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function Axe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return cd(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):ZI.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 Qtt(d,r)}return await r.text()})();return cd(t).debug(`[${n}] response parsed`,lD({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function Qtt(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 ert=v(()=>{Ytt();mie()});var gie,wV,Nxe=v(()=>{a0();ert();wV=class t extends Promise{constructor(e,r,n=Axe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,gie.set(this,void 0),Zr(this,gie,e,"f")}_thenUnwrap(e){return new t(Pe(this,gie,"f"),this.responsePromise,async(r,n)=>Qtt(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(Pe(this,gie,"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)}};gie=new WeakMap});var Dxe,yie,bie,YI,ui,cD,Fu=v(()=>{a0();KI();ert();Nxe();uD();yie=class{constructor(e,r,n,o){Dxe.set(this,void 0),Zr(this,Dxe,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 Kt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Pe(this,Dxe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Dxe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},bie=class extends wV{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await Axe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},YI=class extends yie{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}},ui=class extends yie{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:{...Ftt(this.options.query),after:r}}:null}},cD=class extends yie{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Ftt(this.options.query),after:e}}:null}}});function H8(t,e,r){return nrt(),new File(t,e??"unknown_file",r)}function _ie(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 Nao(t){let e=typeof t=="fu
|
||
|
|
${i.map(f=>f.error).join(`
|
||
|
|
`)}
|
||
|
|
${a}
|
||
|
|
${d}`)}return a},ke=kao(gfr)});var SV,$xe=v(()=>{Jr();Fu();ss();SV=class extends Ke{list(e,r={},n){return this._client.getAPIList(ke`/chat/completions/${e}/messages`,ui,{query:r,...n})}}});var wx=v(()=>{KI()});function wie(t){return t!==void 0&&"function"in t&&t.function!==void 0}function yfr(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Sie(t){return t?.$brand==="auto-parseable-response-format"}function CV(t){return t?.$brand==="auto-parseable-tool"}function bfr(t,e){return!e||!srt(e)?{...t,choices:t.choices.map(r=>(vfr(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Cie(t,e)}function Cie(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new q8;if(n.finish_reason==="content_filter")throw new B8;return vfr(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>zao(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Uao(e,n.message.content):null}}});return{...t,choices:r}}function Uao(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 zao(t,e){let r=t.tools?.find(n=>wie(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:CV(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function _fr(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>wie(n)&&n.function?.name===e.function.name);return wie(r)&&(CV(r)||r?.function.strict||!1)}function srt(t){return Sie(t.response_format)?!0:t.tools?.some(e=>CV(e)||e.type==="function"&&e.function.strict===!0)??!1}function vfr(t){for(let e of t||[])if(e.type!=="function")throw new Kt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function wfr(t){for(let e of t??[]){if(e.type!=="function")throw new Kt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Kt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var W8=v(()=>{wx()});var J8,urt,lrt=v(()=>{J8=t=>t?.role==="assistant",urt=t=>t?.role==="tool"});var crt,Lxe,Fxe,xie,Tie,kxe,Oie,dD,Eie,qxe,Bxe,K8,Sfr,Lk,Uxe=v(()=>{a0();wx();Lk=class{constructor(){crt.add(this),this.controller=new AbortController,Lxe.set(this,void 0),Fxe.set(this,()=>{}),xie.set(this,()=>{}),Tie.set(this,void 0),kxe.set(this,()=>{}),Oie.set(this,()=>{}),dD.set(this,{}),Eie.set(this,!1),qxe.set(this,!1),Bxe.set(this,!1),K8.set(this,!1),Zr(this,Lxe,new Promise((e,r)=>{Zr(this,Fxe,e,"f"),Zr(this,xie,r,"f")}),"f"),Zr(this,Tie,new Promise((e,r)=>{Zr(this,kxe,e,"f"),Zr(this,Oie,r,"f")}),"f"),Pe(this,Lxe,"f").catch(()=>{}),Pe(this,Tie,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Pe(this,crt,"m",Sfr).bind(this))},0)}_connected(){this.ended||(Pe(this,Fxe,"f").call(this),this._emit("connect"))}get ended(){return Pe(this,Eie,"f")}get errored(){return Pe(this,qxe,"f")}get aborted(){return Pe(this,Bxe,"f")}abort(){this.controller.abort()}on(e,r){return(Pe(this,dD,"f")[e]||(Pe(this,dD,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=Pe(this,dD,"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(Pe(this,dD,"f")[e]||(Pe(this,dD,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{Zr(this,K8,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){Zr(this,K8,!0,"f"),await Pe(this,Tie,"f")}_emit(e,...r){if(Pe(this,Eie,"f"))return;e==="end"&&(Zr(this,Eie,!0,"f"),Pe(this,kxe,"f").call(this));let n=Pe(this,dD,"f")[e];if(n&&(Pe(this,dD,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!Pe(this,K8,"f")&&!n?.length
|
||
|
|
\r `.includes(t[n]);)n++};return a()},vrt=t=>Hao(t,Fh.ALL^Fh.NUM)});var wrt=v(()=>{Ytt()});function Jao(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 Kt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new Kt(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Kt(`missing function_call.arguments for choice ${d}`);if(!w)throw new Kt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return y?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...A}=T||{};if(E==null)throw new Kt(`missing choices[${d}].tool_calls[${w}].id
|
||
|
|
${Wxe(t)}`);if(O==null)throw new Kt(`missing choices[${d}].tool_calls[${w}].type
|
||
|
|
${Wxe(t)}`);if(I==null)throw new Kt(`missing choices[${d}].tool_calls[${w}].function.name
|
||
|
|
${Wxe(t)}`);if(R==null)throw new Kt(`missing choices[${d}].tool_calls[${w}].function.arguments
|
||
|
|
${Wxe(t)}`);return{...P,id:E,type:O,function:{...A,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return bfr(u,e)}function Wxe(t){return JSON.stringify(t)}var Um,fD,X8,Fk,Srt,Vxe,Crt,xrt,Trt,Hxe,Ort,Efr,xV,Jxe=v(()=>{a0();Ofr();wx();W8();wrt();grt();xV=class t extends G8{constructor(e){super(),Um.add(this),fD.set(this,void 0),X8.set(this,void 0),Fk.set(this,void 0),Zr(this,fD,e,"f"),Zr(this,X8,[],"f")}get currentChatCompletionSnapshot(){return Pe(this,Fk,"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())),Pe(this,Um,"m",Srt).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)Pe(this,Um,"m",Crt).call(this,a);if(i.controller.signal?.aborted)throw new qc;return this._addChatCompletion(Pe(this,Um,"m",Hxe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Pe(this,Um,"m",Srt).call(this),this._connected();let o=ZI.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Pe(this,Um,"m",Hxe).call(this)),Pe(this,Um,"m",Crt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new qc;return this._addChatCompletion(Pe(this,Um,"m",Hxe).call(this))}[(fD=new WeakMap,X8=new WeakMap,Fk=new WeakMap,Um=new WeakSet,Srt=function(){this.ended||Zr(this,Fk,void 0,"f")},Vxe=function(r){let n=Pe(this,X8,"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},Pe(this,X8,"f")[r.index]=n,n)},Crt=function(r){if(this.ended)return;let n=Pe(this,Um,"m",Efr).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=Pe(this,Um,"m",Vxe).call(this,i);i.finish_reason&&(Pe(this,Um,"m",Trt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Um,"m",xrt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Pe(this,Um,"m",Trt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Um,"m",xrt).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))}}},xrt=function(r,n){if(Pe(this,Um,"m",Vxe).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=Pe(this,fD,"f")?.tools?.find(s=>wie(s)&&s.func
|
||
|
|
|
||
|
|
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
|
||
|
|
`);this.baseURL=s.baseURL,this.timeout=s.timeout??Dnt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=Xtt(s.logLevel,"ClientOptions.logLevel",this)??Xtt(Sx("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Hdr(),Zr(this,oTe,Jdr,"f"),this._options=s,this.apiKey=typeof r=="string"?r:"Missing Key",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 gt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ktt(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${$k}`}defaultIdempotencyKey(){return`stainless-node-retry-${jtt()}`}makeStatusError(e,r,n,o){return qm.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof Kt?n:new Kt(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new Kt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!Pe(this,Nnt,"m",Zfr).call(this)&&n||this.baseURL,i=jdr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return $dr(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}async prepareOptions(e){await this._callApiKey()}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 wV(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(cd(this).debug(`[${l}] sending request`,lD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new qc;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(die),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new qc;let b=cie(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return cd(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),cd(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,lD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw cd(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),cd(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,lD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?new WI:new jk({cause:p})}let h=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,b])=>", "+g+": "+JSON.stringify(b)).join(""),y=`[${l}${c}${h}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(r&&g){let E=`retrying, ${r} attempts remaining`;return await Wdr(p.body),cd(this).info(`${y} - ${E}`),cd(this).debug(`[${l}] response error (${E})`,lD({retryOfRequestLogID:n,url:p.ur
|
||
|
|
`)}function opr(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}: ${aTe(o,e)},`):r.push(`${n}?: ${aTe(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
||
|
|
`)}function aTe(t,e){if(kso(t))return t.anyOf.map(r=>aTe(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["{",opr(t,e+2),"}"].join(`
|
||
|
|
`);case"array":return t.items?`${aTe(t.items,e)}[]`:"any[]";default:return""}}function sTe(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 OG(t){return"type"in t&&t.type!=="function"}function ipr(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function apr(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function VV(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 uTe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function spr(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 upr(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function lpr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function cpr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function dpr(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 fpr(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 EG=v(()=>{iD();nv();Sy()});var $nt=v(()=>{_y()});var pTe={};En(pTe,{ZodISODate:()=>cTe,ZodISODateTime:()=>lTe,ZodISODuration:()=>fTe,ZodISOTime:()=>dTe,date:()=>Fnt,datetime:()=>Lnt,duration:()=>qnt,time:()=>knt});function Lnt(t){return OVe(lTe,t)}function Fnt(t){return EVe(cTe,t)}function knt(t){return PVe(dTe,t)}function qnt(t){return MVe(fTe,t)}var lTe,cTe,dTe,fTe,mTe=v(()=>{_y();hTe();lTe=Te("ZodISODateTime",(t,e)=>{M2e.init(t,e),Qu.init(t,e)});cTe=Te("ZodISODate",(t,e)=>{R2e.init(t,e),Qu.init(t,e)});dTe=Te("ZodISOTime",(t,e)=>{I2e.init(t,e),Qu.init(t,e)});fTe=Te("ZodISODuration",(t,e)=>{A2e.init(t,e),Qu.init(t,e)})});var mpr,Bso,PG,Bnt=v(()=>{_y();_y();mpr=(t,e)=>{uee.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>cee(t,r)},flatten:{value:r=>lee(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Bso=Te("ZodError",mpr),PG=Te("ZodError",mpr,{Parent:Error})});var Unt,znt,Vnt,Hnt,Wnt=v(()=>{_y();Bnt();Unt=Zme(PG),znt=Yme(PG),Vnt=Qme(PG),Hnt=ehe(PG)});function Jnt(t){return CVe($ie,t)}function zso(t){return hhe(Xnt,t)}function Vso(t){return _ee(gTe,t)}function Hso(t){return ghe(wD,t)}function Wso(t){return yhe(wD,t)}function Jso(t){return bhe(wD,t)}function Kso(t){return _he(wD,t)}function Gso(t){return vhe(Znt,t)}function Xso(t){return whe(Ynt,t)}function Zso(t){return She(Qnt,t)}function Yso(t){return Che(eot,t)}function Qso(t){return xhe(tot,t)}function euo(t){return The(rot,t)}function tuo(t){return Ohe(not,t)}function ruo(t){return Ehe(oot,t)}function nuo(t){return Phe(iot,t)}function ouo(t){return Mhe(aot,t)}function iuo(t){return Rhe(sot,t)}function auo(t){return Ihe(uot,t)}function suo(t){return Ahe(lot,t)}function uuo(t){return Nhe(cot,t)}function luo(t){return Dhe(dot,t)}function cuo(t){return jhe(fot,t)}function duo(t,e,r={}){return sHe(hpr,t,e,r)}function gpr(t){return RVe(Lie,t)}function Knt(t){return AVe(MG,t)}function fuo(
|
||
|
|
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
|
||
|
|
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
|
||
|
|
`:`[${o[l]}\r
|
||
|
|
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}});function MTe(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Ne.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ne.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(ETe(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===Ne.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var RTe=v(()=>{rO();Ed();PTe()});function Cmr(t,e){if(e.mapStrategy==="record")return MTe(t,e);let r=Dn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Dn(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 Bot=v(()=>{Ed();RTe()});function xmr(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 Uot=v(()=>{});function Tmr(){return{not:{}}}var zot=v(()=>{});function Omr(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Vot=v(()=>{});function Pmr(t,e){if(e.target==="openApi3")return Emr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Bie&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Bie[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 Emr(t,e)}var Bie,Emr,ITe=v(()=>{Ed();Bie={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Emr=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Dn(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 Mmr(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:Bie[t.innerType._def.typeName],nullable:!0}:{type:[Bie[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Hot=v(()=>{Ed();ITe()});function Rmr(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",Oot(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
|
||
|
|
Details: ${m.message}`),fHe(m)&&(h=`${h}
|
||
|
|
|
||
|
|
${Zt.prettifyError(m)}`),new xQ(h,JSON.stringify(e))}else{let m=fl(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
|
||
|
|
Details: ${m.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
|
||
|
|
`)}`),new xQ(h,JSON.stringify(e))}i=o}let a=qL(r),s=Cm.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),u;NL(e)&&(u=e.id),!u&&nCt(a)&&(u=a.toolCall.id);let l=await s?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,u);delete a.runId;let c;try{let m=await this._call(i,l,a);c=ZIt(m)?await YIt(m,async h=>{try{await l?.handleToolEvent(h)}catch(y){await l?.handleToolError(y)}}):m}catch(m){throw await l?.handleToolError(m),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[d,f]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
||
|
|
Result: ${JSON.stringify(c)}`);else d=c;let p=vlo({content:d,artifact:f,toolCallId:u,name:this.name,metadata:this.metadata});return await l?.handleToolEnd(p),p}},dhr=class extends chr{constructor(e){super(e);x(this,"schema",Ae.object({input:Ae.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},fhr=class extends dhr{constructor(e){super(e);x(this,"name");x(this,"description");x(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,r){let n=qL(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,r,n){return this.func(e,r,n)}},_lo=class extends chr{constructor(e){super(e);x(this,"description");x(this,"func");x(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,r,n){let o=qL(r);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){return this.func(e,r,n)}}});var git=v(()=>{rA();su();eq()});var phr=v(()=>{});var mhr=v(()=>{});var hhr=v(()=>{});var ghr=v(()=>{});var yhr=v(()=>{});var Slo,Clo,xlo,Tlo,Olo,Elo,Plo,Mlo,Rlo,Ilo,F4a,bhr=v(()=>{ra();eq();HV();Slo=Zt.object({type:Zt.literal("screenshot")}),Clo=Zt.object({type:Zt.literal("click"),x:Zt.number(),y:Zt.number(),button:Zt.enum(["left","right","wheel","back","forward"]).default("left")}),xlo=Zt.object({type:Zt.literal("double_click"),x:Zt.number(),y:Zt.number(),button:Zt.enum(["left","right","wheel","back","forward"]).default("left")}),Tlo=Zt.object({type:Zt.literal("drag"),path:Zt.array(Zt.object({x:Zt.number(),y:Zt.number()}))}),Olo=Zt.object({type:Zt.literal("keypress"),keys:Zt.array(Zt.string())}),Elo=Zt.object({type:Zt.literal("move"),x:Zt.number(),y:Zt.number()}),Plo=Zt.object({type:Zt.literal("scroll"),x:Zt.number(),y:Zt.number(),scroll_x:Zt.number(),scroll_y:Zt.number()}),Mlo=Zt.object({type:Zt.literal("type"),text:Zt.string()}),Rlo=Zt.object({type:Zt.literal("wait"),duration:Zt.number().optional()}),Ilo=Zt.discriminatedUnion("type",[Slo,Clo,xlo,Tlo,Olo,Elo,Plo,Mlo,Rlo]),F4a=Zt.object({action:Ilo})});var Alo,U4a,_hr=v(()=>{eq();HV();Alo=Zt.object({type:Zt.literal("exec"),command:Zt.array(Zt.string()),env:Zt.record(Zt.string(),Zt.string()).optional(),working_directory:Zt.string().optional(),timeout_ms:Zt.number().optional(),user:Zt.string().optional()}),U4a=Zt.discriminatedUnion("type",[Alo])});var W4a,vhr=v(()=>{eq();HV();W4a=Zt.object({commands:Zt.array(Zt.string()).describe("Array of shell commands to execute"),timeout_ms:Zt.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Zt.number().optional().describe("Optional maximum number of characters to return from each command")})});var Nlo,Dlo,jlo,X4a,whr=v(()=>{eq();HV();Nlo=Zt.object({type:Zt.literal("create_file"),path:Zt.string(),diff:Zt.string()}),Dlo=Zt.object({type:Zt.literal("update_file"),path:Zt.string(),diff:Zt.string()}),jlo=Zt.object({type:Zt.literal("delete_file"),path:Zt.string()}),X4a=Zt.discriminatedUnion("type",[Nlo,Dlo,jlo])});var Shr=v(()=>{git();phr();mhr();hhr();ghr();yhr();bhr();_hr();vhr();whr()});var Chr=v(()=>{Qv();eq();Ez()});var xhr=v(()=>{RG()});var Thr=v(()=>{RG();LTe()});var CD=v(()=>{Gk();Xk();Zk();Uie();RG();NTe();uit();LTe();kTe();dit();fit();shr();pit();uhr();mit();lhr();git();Shr();Chr();xhr();Thr();rA()});var Ehr=S((mVa,Ohr)=>{Ohr.exports={createRequire:function(t){return typeof require<"u"?require:function(r){throw new Error('Dynamic require of "'+r+'" is not supported in this environment')}}}});var $lo,Llo,Phr,Mhr=v(()=>{$lo=$(Ehr(),1),Llo=Object.defineProperty,Phr=(t,e)=>{for(var r in e)Llo(t,r,{get:e[r],enumerable:!0})}});var Flo,yit,Rhr=v(()=>{Mhr();su();lV();Ik();Flo={};Phr(Flo,{JinaEmbeddings:()=>yit});yit=class extends bx{constructor(e){let r={maxConcurrency:2,...e};super(r);x(this,"model","jina-clip-v2");x(this,"batchSiz
|
||
|
|
without CORS Error: `+Wr(n)+`
|
||
|
|
with CORS Error: `+Wr(o);throw new Error(i)}}}}});function Mx(t){return(t.miyoServerUrl||"").trim()}function kh(t){return!t.enableMiyo||!bit()?!1:!Vie.Platform.isMobile||!!Mx(t)}function tq(t){return t.vault.getName()}function UTe(t,e){let r=t.vault.adapter;if(r instanceof Vie.FileSystemAdapter)return r.getFullPath(e);let n=r;return typeof n.getFullPath=="function"?n.getFullPath(e):e}function NG(t,e){let r=qlo(t);if(!r)return e;let n=Nhr(r),o=Nhr(e),i=`${n}/`;return o.startsWith(i)?o.slice(i.length):e}function qlo(t){let e=t.vault.adapter;if(e instanceof Vie.FileSystemAdapter)return e.getBasePath();let r=e;if(typeof r.getBasePath=="function")return r.getBasePath();if(typeof r.basePath=="string")return r.basePath}function Nhr(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}var Vie,u0=v(()=>{id();Vie=require("obsidian")});var Dhr,zTe,jhr=v(()=>{Xe();Qe();Dt();Dhr=require("obsidian"),zTe=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let r=(e.overrideUrl||"").trim();if(r.length>0)return this.normalizeBaseUrl(r);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!Dhr.Platform.isDesktopApp)return null;let n=await this.readServiceConfig();if(n==="missing"){let i=this.getDefaultBaseUrl();return this.cachedBaseUrl=null,ee().debug&&F(`Miyo service discovery file missing; using fallback ${i}`),i}if(!n)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${n.host}:${n.port}`);return this.cachedBaseUrl=o,o}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getDefaultBaseUrl(){return this.normalizeBaseUrl("http://127.0.0.1:8742")}getServiceFilePaths(){let e=this.getNodeRequire();if(!e)return[];let r=e("os"),n=e("process"),o=e("path"),i=r.homedir(),a=r.platform(),s=n.env||{};if(a==="win32"){let u=(s.LOCALAPPDATA||"").trim(),l=(s.APPDATA||"").trim();return[u,o.join(i,"AppData","Local"),l,o.join(i,"AppData","Roaming")].filter((d,f,p)=>d.length>0&&p.indexOf(d)===f).map(d=>o.join(d,"Miyo","service.json"))}return a==="linux"?[o.join(i,".config","Miyo","service.json")]:a==="darwin"?[o.join(i,"Library","Application Support","Miyo","service.json")]:(Ce(`Miyo service discovery unsupported platform: ${a}`),[])}async readServiceConfig(){let e=this.getServiceFilePaths();if(e.length===0)return null;let r=this.getNodeRequire();if(!r)return null;let n=r("fs"),o=!1;for(let i of e)try{let a=await n.promises.readFile(i,"utf8"),s=JSON.parse(a);return!s.host||typeof s.host!="string"?(Ce("Miyo service discovery missing host"),null):typeof s.port!="number"||Number.isNaN(s.port)?(Ce("Miyo service discovery missing port"),null):(ee().debug&&F(`Miyo service discovery resolved host=${s.host} port=${s.port}`),s)}catch(a){if(this.isMissingFileError(a)){o=!0;continue}return ee().debug&&Ce(`Miyo service discovery failed: ${Wr(a)}`),null}return o?"missing":null}isMissingFileError(e){return e?.code==="ENOENT"}getNodeRequire(){let e=globalThis?.require;return typeof e=="function"?e:null}}});var $hr,l0,DG=v(()=>{BC();Xe();jhr();Qe();Dt();$hr=require("obsidian"),l0=class{constructor(){this.discovery=zTe.getInstance()}async resolveBaseUrl(e){let r=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!r)throw new Error("Miyo base URL not available");return r}async isBackendAvailable(e){try{let r=await this.resolveBaseUrl(e),n=await this.requestJson(r,"/v0/health",{method:"GET"});return n?.status!=="ok"?(Ce(`Miyo health check failed: status="${n?.status??"unknown"}"`),!1):!0}catch(r){return Ce(`Miyo backend availability check failed: ${Wr(r)}`),!1}}async getFolder(e,r){return this.requestJson(e,"/v0/folder",{method:"GET",query:{path:r}})}async scanFolder(e,r,n=!1){return this.requestJson(e,"/v0/scan",{method:"POST",body:{path:r,force:n}})}async listFolderFiles(e,r){return this.requestJson(e,"/v0/folder/files",{method:"GET",query:{folder_name:r.folderName,title:r.title,file_path:r.filePath,mtime_after:r.mtimeAfter,mtime_before:r.mtimeBefore,offset:r.offset,limit:r.limit,order_by:r.orderBy}})}async getDocumentsByPath(e,r,n){return thi
|
||
|
|
- `),Jlo={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
|
||
|
|
Supported languages are:
|
||
|
|
- ${Wlo}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
|
||
|
|
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
|
||
|
|
Please install it before proceeding with creating an answer session.
|
||
|
|
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
|
||
|
|
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
|
||
|
|
Please provide a chat model before proceeding with creating an answer session.
|
||
|
|
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
|
||
|
|
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function Khr(t){return{raw:Number(t),formatted:ZV(t)}}function Ghr(t){if(t.id){if(typeof t.id!="string")throw Vr("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return Wie()}function wit(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(xD(n)){let i=Cit(n);if(!Array.isArray(o)||o.length!==i)throw Vr("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(FG(n)){if(!Array.isArray(o))return r;let i=Sit(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=wit(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function Xhr(t){return t==="geopoint"}function xD(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function FG(t){return typeof t=="string"&&Klo[t]}function Sit(t){return Glo[t]}function Cit(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Vr("INVALID_VECTOR_VALUE",t);case e<=0:throw Vr("INVALID_VECTOR_SIZE",t);default:return e}}var Klo,Glo,Jie=v(()=>{qh();fd();fd();Klo={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Glo={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function Zhr(){return{idToInternalId:new Map,internalIdToId:[],save:Xlo,load:Zlo}}function Xlo(t){return{internalIdToId:t.internalIdToId}}function Zlo(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 du(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?du(t,e.toString()):e}function c0(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var d0=v(()=>{});function Qlo(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function eco(t,e){let r=du(t.sharedInternalDocumentStore,e);return t.docs[r]}function tco(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=du(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function rco(t){return t.docs}function nco(t,e,r){let n=du(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function oco(t,e){let r=du(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function ico(t){return t.count}function aco(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function sco(t){return{docs:t.docs,count:t.count}}function Yhr(){return{create:Qlo,get:eco,getMultiple:tco,getAll:rco,store:nco,remove:oco,count:ico,load:aco,save:sco}}var xit=v(()=>{d0()});function egr(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),Vr("PLUGIN_CRASHED")}return r}var Qhr,tgr=v(()=>{qh();Qhr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function Ix(t,e,r,n){if(t.some(Pd))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function YV(t,e,r){if(t.some(Pd))return(async()=>{for(let o of t)await o(e,r)})();for(let o o
|
||
|
|
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}},_at=class bat extends Mbr{constructor(r){super(r);x(this,"separators",[`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""]);this.separators=r?.separators??this.separators,this.keepSeparator=r?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(r,n){let o=[],i=n[n.length-1],a;for(let c=0;c<n.length;c+=1){let d=n[c];if(d===""){i=d;break}if(r.includes(d)){i=d,a=n.slice(c+1);break}}let s=this.splitOnSeparator(r,i),u=[],l=this.keepSeparator?"":i;for(let c of s)if(await this.lengthFunction(c)<this.chunkSize)u.push(c);else{if(u.length){let d=await this.mergeSplits(u,l);o.push(...d),u=[]}if(!a)o.push(c);else{let d=await this._splitText(c,a);o.push(...d)}}if(u.length){let c=await this.mergeSplits(u,l);o.push(...c)}return o}async splitText(r){return this._splitText(r,this.separators)}static fromLanguage(r,n){return new bat({...n,separators:bat.getSeparatorsForLanguage(r)})}static getSeparatorsForLanguage(r){if(r==="cpp")return[`
|
||
|
|
class `,`
|
||
|
|
void `,`
|
||
|
|
int `,`
|
||
|
|
float `,`
|
||
|
|
double `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="go")return[`
|
||
|
|
func `,`
|
||
|
|
var `,`
|
||
|
|
const `,`
|
||
|
|
type `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="java")return[`
|
||
|
|
class `,`
|
||
|
|
public `,`
|
||
|
|
protected `,`
|
||
|
|
private `,`
|
||
|
|
static `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="js")return[`
|
||
|
|
function `,`
|
||
|
|
const `,`
|
||
|
|
let `,`
|
||
|
|
var `,`
|
||
|
|
class `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
default `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="php")return[`
|
||
|
|
function `,`
|
||
|
|
class `,`
|
||
|
|
if `,`
|
||
|
|
foreach `,`
|
||
|
|
while `,`
|
||
|
|
do `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="proto")return[`
|
||
|
|
message `,`
|
||
|
|
service `,`
|
||
|
|
enum `,`
|
||
|
|
option `,`
|
||
|
|
import `,`
|
||
|
|
syntax `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="python")return[`
|
||
|
|
class `,`
|
||
|
|
def `,`
|
||
|
|
def `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="rst")return[`
|
||
|
|
===
|
||
|
|
`,`
|
||
|
|
---
|
||
|
|
`,`
|
||
|
|
***
|
||
|
|
`,`
|
||
|
|
.. `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="ruby")return[`
|
||
|
|
def `,`
|
||
|
|
class `,`
|
||
|
|
if `,`
|
||
|
|
unless `,`
|
||
|
|
while `,`
|
||
|
|
for `,`
|
||
|
|
do `,`
|
||
|
|
begin `,`
|
||
|
|
rescue `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="rust")return[`
|
||
|
|
fn `,`
|
||
|
|
const `,`
|
||
|
|
let `,`
|
||
|
|
if `,`
|
||
|
|
while `,`
|
||
|
|
for `,`
|
||
|
|
loop `,`
|
||
|
|
match `,`
|
||
|
|
const `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="scala")return[`
|
||
|
|
class `,`
|
||
|
|
object `,`
|
||
|
|
def `,`
|
||
|
|
val `,`
|
||
|
|
var `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
match `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="swift")return[`
|
||
|
|
func `,`
|
||
|
|
class `,`
|
||
|
|
struct `,`
|
||
|
|
enum `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
do `,`
|
||
|
|
switch `,`
|
||
|
|
case `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="markdown")return[`
|
||
|
|
## `,`
|
||
|
|
### `,`
|
||
|
|
#### `,`
|
||
|
|
##### `,`
|
||
|
|
###### `,"```\n\n",`
|
||
|
|
|
||
|
|
***
|
||
|
|
|
||
|
|
`,`
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
`,`
|
||
|
|
|
||
|
|
___
|
||
|
|
|
||
|
|
`,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];if(r==="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(r==="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(r==="sol")return[`
|
||
|
|
pragma `,`
|
||
|
|
using `,`
|
||
|
|
contract `,`
|
||
|
|
interface `,`
|
||
|
|
library `,`
|
||
|
|
constructor `,`
|
||
|
|
type `,`
|
||
|
|
function `,`
|
||
|
|
event `,`
|
||
|
|
modifier `,`
|
||
|
|
error `,`
|
||
|
|
struct `,`
|
||
|
|
enum `,`
|
||
|
|
if `,`
|
||
|
|
for `,`
|
||
|
|
while `,`
|
||
|
|
do while `,`
|
||
|
|
assembly `,`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`," ",""];throw new Error(`Language ${r} is not supported.`)}}});var Ibr=v(()=>{Rbr()});var KG,aH,vat=v(()=>{Xe();Qe();KG=class KG{constructor(){this.bytesUsed=0;let e=ee(),r=Math.min(1e3,Math.max(20,e.lexicalSearchRamLimit||100));this.maxBytes=r*KG.MB_TO_BYTES,this.candidateLimit=Math.min(KG.DEFAULT_CANDIDATE_LIMIT,Math.floor(r*5))}getMaxBytes(){return this.maxBytes}getCandidateLimit(){return this.candidateLimit}getBytesUsed(){return this.bytesUsed}canAddContent(e){return this.bytesUsed+e<=this.maxBytes}addBytes(e){this.bytesUsed+=e}reset(){let e=this.bytesUsed;this.bytesUsed=0,F(`MemoryManager: Reset memory tracking (was using ${e} bytes, max: ${this.maxBytes} bytes)`)}getUsagePercent(){return Math.round(this.bytesUsed/this.maxBytes*100)}static getByteSize(e){return new TextEncoder().encode(e).length}};KG.DEFAULT_CANDIDATE_LIMIT=500,KG.MB_TO_BYTES=1024*1024;aH=KG});function lq(t){return wat||(wat=new Sat(t)),wat}var YOe,ZOe,Sat,wat,oae=v(()=>{Xe();gr();YOe=require("obsidian");Ibr();vat();ZOe={maxChars:jge,overlap:0,maxBytesTotal:10*1024*1024},Sat=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,r){return`${e}:${r.maxChars}:${r.overlap}`}createSplitter(e){return _at.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`
|
||
|
|
|
||
|
|
`,`
|
||
|
|
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return Ce("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(Ce("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let n=e.filter(u=>!(!u||typeof u!="string"||u.startsWith("/")||u.startsWith("../")||u.includes("/../")||u.endsWith("/..")));if(n.length===0)return Ce("ChunkManager: No valid note paths provided"),[];let o={...ZOe,...r},i=[],a=0,s=0;for(let u of n){let l=this.getCacheKey(u,o),c=this.cache.get(l);if(c&&c.length>0){let d=this.app.vault.getAbstractFileByPath(u);if(d&&d instanceof YOe.TFile&&d.stat.mtime>c[0].mtime){let f=this.calculateChunkBytes(c);this.cache.delete(l),this.memoryUsage-=f,c=void 0}}if(!c&&(c=await this.generateChunksForNote(u,o),c.length>0)){let d=this.calculateChunkBytes(c);this.memoryUsage+d<=o.maxBytesTotal?(this.cache.set(l,c),this.memoryUsage+=d):(a+=1,s+=d)}i.push(...c)}if(a>0){let u=(s/1024/1024).toFixed(1);F(`ChunkManager: Cache budget reached, skipped caching ${a} notes (${u}MB total)`)}return F(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return Ce("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||Ce(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r;for(let[o,i]of this.cache.entries())if(o.startsWith(e+":")){r=i;break}if(!r&&(F(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return Ce(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof YOe.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(F(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.regenerateChunks(e),!r||r.length===0)?(Ce(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):r}getChunkTextSync(e){let[r]=e.split("#");for(let[n,o]of this.cache.entries())if(n.startsWith(r+":")){let i=o.find(a=>a.id===e);if(i)return i.content}return Ce(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),""}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,ZOe),n=this.getCacheKey(e,ZOe);if(r.length>0){let o=this.calculateChunkBytes(r);if(this.memoryUsage+o<=ZOe.maxBytesTotal){let i=this.cache.get(n);i&&(this.memoryUsage-=this.calculateChunkBytes(i)),this.cache.set(n,r),this.memoryUsage+=o}else F(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return Ce(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,F("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof YOe.TFile))return[];let o=await this.safeReadFile(n);if(!o?.trim())return[];let i=this.app.metadataCache.getFileCache(n),a=(i?.headings||[]).slice().sort((p,m)=>p.position.start.offset-m.position.start.offset),s=[],u=0,l=this.findFrontmatterEnd(o,i?.frontmatter),c=o.substring(l),d=a.length>0?a[0].heading:"";if(`
|
||
|
|
|
||
|
|
NOTE TITLE: [[${n.basename}]]
|
||
|
|
|
||
|
|
NOTE BLOCK CONTENT:
|
||
|
|
|
||
|
|
`.length+c.length<=r.maxChars){let p=await this.processContentSection(c,d,n,u,r);return s.push(...p),s}if(a.length===0){let p=await this.processContentSection(c,"",n,u,r);return s.push(...p),s}for(let p=0;p<a.length;p++){let m=a[p],h=a[p+1],y=p===0?l:m.position.start.offset,g=h?.position.start.offset||o.length,b=o.substring(y,g),_=await this.processContentSection(b,m.heading,n,u,r);s.push(..._),u+=_.length}return s}catch(n){return Ce(`ChunkManager: Failed to chunk note ${e}`,n),[]}}async processContentSection(e,r,n,o,i){let a=n.basename,s=[],u=`
|
||
|
|
|
||
|
|
NOTE TITLE: [[${a}]]
|
||
|
|
|
||
|
|
NOTE BLOCK CONTENT:
|
||
|
|
|
||
|
|
`,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{let d=await this.createSplitter(i).createDocuments([e],[],{chunkHeader:u,appendChunkOverlapHeader:i.overlap>0});this.coalesceTinySplitChunks(d.map(p=>p.pageContent),u,i.maxChars).forEach((p,m)=>{let h=o+m,y=this.generateChunkId(n.path,h),g=this.calculateContentHash(p);s.push({id:y,notePath:n.path,chunkIndex:h,content:p,contentHash:g,title:a,heading:r,mtime:n.stat.mtime})})}catch(c){Ce(`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}coalesceTinySplitChunks(e,r,n){if(e.length<=1)return e;let o=[...e],i=0;for(;i<o.length-1;){if(this.isTinyStructuralChunk(o[i],r)){let a=this.mergeChunkContents(o[i],o[i+1],r);if(a.length<=n){o.splice(i,2,a);continue}}i++}if(o.length>1){let a=o.length-1;if(this.isTinyStructuralChunk(o[a],r)){let s=this.mergeChunkContents(o[a-1],o[a],r);s.length<=n&&o.splice(a-1,2,s)}}return o}isTinyStructuralChunk(e,r){let n=this.stripChunkHeader(e,r).trim();if(!n)return!0;let o=n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return o.length===1&&/^#{1,6}\s+\S+/.test(o[0])}mergeChunkContents(e,r,n){let o=this.stripChunkHeader(e,n).replace(/\s+$/,""),i=this.stripChunkHeader(r,n).replace(/^\s+/,"");return`${n}${o}${o&&i?`
|
||
|
|
|
||
|
|
`:""}${i}`}stripChunkHeader(e,r){return e.startsWith(r)?e.slice(r.length):e}calculateChunkBytes(e){return e.reduce((r,n)=>r+aH.getByteSize(n.content),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(r){return Ce(`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`}findFrontmatterEnd(e,r){if(!r||!e.startsWith("---"))return 0;let n=e.match(/\n---(\r?\n|$)/);return n&&n.index!==void 0?n.index+n[0].length:0}},wat=null});var Abr,QOe,iae,Nbr=v(()=>{na();XV();Xe();Ebr();oae();Qe();Dt();Abr=$(oH()),QOe=require("obsidian");Wb();iae=class{constructor(e,r,n){this.app=e;this.indexBackend=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set};this.refreshRuntimeIndexingConfig(),this.chunkManager=lq(e),ml(async()=>{this.refreshRuntimeIndexingConfig()})}refreshRuntimeIndexingConfig(){let e=ee();this.rateLimiter=new XOe(e.embeddingRequestsPerMin),this.embeddingBatchSize=Math.max(1,e.embeddingBatchSize),this.checkpointInterval=8*this.embeddingBatchSize}async indexVaultToVectorStore(e,r){if(!ee().enableSemanticSearchV3)return Ce("indexVaultToVectorStore called with semantic search disabled, skipping."),0;let n=[];x3e();try{let o=this.indexBackend.requiresEmbeddings(),i=o?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(o&&!i)return ie("Embedding instance not found."),C3e({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:["Embedding model not available. Please check your Copilot settings to make sure you have a working embedding model."],completionStatus:"error"}),0;(o?await this.indexBackend.checkAndHandleEmbeddingModelChange(i):!1)&&(e=!0),e?(await this.indexBackend.clearIndex(i),this.indexBackend.clearFilesMissingEmbeddings()):await this.indexBackend.garbageCollect();let s=await this.getFilesToIndex(e);if(s.length===0)return r?.userInitiated&&Sg({completionStatus:"success"}),0;this.initializeIndexingState(s.length),this.indexBackend.clearFilesMissingEmbeddings();let u=o&&i?dd.getModelName(i):"",l=await this.prepareAllChunks(s,u);if(l.length===0)return x3e(),0;if(this.state.isIndexingCancelled||QJ().isCancelled)return Sg({isActive:!1,completionStatus:"cancelled"}),0;let c=new Set(l.map(f=>f.fileInfo.path)).size;this.state.totalFilesToIndex=c,Sg({totalFiles:c});let d=0;for(;d<l.length&&!(this.state.isIndexingCancelled||QJ().isCancelled);){await this.handlePause();let f=l.slice(d,d+this.embeddingBatchSize);try{let p=[];if(o&&i){await this.rateLimiter.wait();let y=await i.embedDocuments(f.map(g=>g.content));if(!y||y.length!==f.length)throw new Error(`Embedding model returned ${y?.length??0} embeddings for ${f.length} documents`);for(let g=0;g<f.length;g++){let b=f[g],_=y[g];if(!_||!Array.isArray(_)||_.length===0){ie(`Invalid embedding for document ${b.fileInfo.path}: ${_}`),this.indexBackend.markFileMissingEmbeddings(b.fileInfo.path);continue}p.push({doc:{...b.fileInfo,id:this.getDocHash(b.content),content:b.content,embedding:_,created_at:Date.now(),nchars:b.content.length},filePath:b.fileInfo.path})}}else for(let y of f)p.push({doc:{...y.fileInfo,id:this.getDocHash(y.content),content:y.content,embedding:[],created_at:Date.now(),nchars:y.content.length},filePath:y.fileInfo.path});if(p.length>0)try{await this.indexBackend.upsertBatch(p.map(y=>y.doc)),p.forEach(y=>this.state.processedFiles.add(y.filePath))}catch(y){ie("Batch upsert failed; falling back to per-document upserts.",y);for(let g of p)try{await this.indexBackend.upsert(g.doc),this.state.processedFiles.add(g.filePath)}catch(b){this.handleError(b,{filePath:g.filePath,errors:n}),o&&this.indexBackend.markFileMissingEmbeddings(g.filePath)}}this.state.indexedCount=this.state.processedFiles.size,p1t(this.state.indexedCount);let m=Math.floor((this.state.indexedCount-f.length)/this.checkpointInterval);Math.floor(this
|
||
|
|
|
||
|
|
`,m=l.content.indexOf("NOTE BLOCK CONTENT:"),h=m>0?l.content.slice(0,m)+p+l.content.slice(m):l.content;n.push({content:h,chunkId:l.id,fileInfo:f})}}}return n}getDocHash(e){return(0,Abr.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=Zl(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>fu(c,r,n));let i=new Set(await this.indexBackend.getIndexedFiles()),a=await this.indexBackend.getLatestFileMtime(),s=new Set(this.indexBackend.getFilesMissingEmbeddings()),u=new Set,l=new Set;for(let c of o){if(!fu(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 F([`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},C3e({isActive:!0,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:e,errors:[],completionStatus:"none"})}async handlePause(){let e=QJ();if(this.state.isIndexingPaused=e.isPaused,this.state.isIndexingCancelled=e.isCancelled,this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;){await new Promise(n=>setTimeout(n,100));let r=QJ();this.state.isIndexingPaused=r.isPaused,this.state.isIndexingCancelled=r.isCancelled}if(!this.state.isIndexingCancelled){this.refreshRuntimeIndexingConfig();let r=await this.getFilesToIndex();if(r.length===0){F("No files to index after filter change, stopping indexing"),this.cancelIndexing();return}let n=Math.max(this.state.indexedCount+r.length,1);this.state.totalFilesToIndex=n,Sg({totalFiles:n})}}}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.isStringLengthError(e)){new QOe.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}}isRateLimitError(e){return e?.message?.includes?.("rate limit")||!1}finalizeIndexing(e){if(m1t(),this.state.isIndexingCancelled||QJ().isCancelled){Sg({isActive:!1,completionStatus:"cancelled",errors:e});return}Sg({isActive:!1,completionStatus:e.length>0?"error":"success",errors:e,indexedCount:this.state.indexedCount})}async reindexFile(e){try{let r=this.indexBackend.requiresEmbeddings(),n=r?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(r&&!n)return;if(await this.indexBackend.removeByPath(e.path),r&&n&&await this.indexBackend.checkAndHandleEmbeddingModelChange(n)){await this.indexVaultToVectorStore(!0);return}let o=r&&n?dd.getModelName(n):"",i=await this.prepareAllChunks([e],o);if(i.length===0)return;if(r&&n){let a=await n.embedDocuments(i.map(s=>s.content));for(let s=0;s<i.length;s++){let u=i[s];await this.indexBackend.upsert({...u.fileInfo,id:this.getDocHash(u.content),content:u.content,embedding:a[s],created_at:Date.now(),nchars:u.content.length})}}else for(let a of i)await this.indexBackend.upsert({...a.fileInfo,id:this.getDocHash(a.content),content:a.content,embedding:[],created_at:Date.now(),nchars:a.content.length});this.indexBackend.markUnsavedChanges(),ee().debug&&console.log(`Reindexed file: ${e.path}`)}catch(r){this.handleError(r,{filePath:e.path})}}async cancelIndexing(){F("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,Sg({isCancelled:!0,isActive:!1,completionStatus:"cancelled"}),await new Promise(e=>setTimeout(e,100))}}});var Bc={};En(Bc,{default:()=>p0});var aae,p0,El=v(()=>{na();OS();Xe();XV();u0();Qe();aae=require("obsidian");Fhr();Tbr();Obr();hat();Nbr();p0=class t{constructor(){this.embeddingsManager=dd.getInstance(),this.oramaBackend=new GOe(app),this.miyoBackend=new VTe(app),this.activeBackendKey=this.getBackendKey(ee()),this.indexBackend=this.activeBackendKey==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new iae(app,this.indexBackend,this.embeddingsManager),this.eventHandler=new rae(app,this.indexOps,this.indexBackend),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...ee()};let e=async()=>{let r=ee(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableI
|
||
|
|
1. SALIENT TERMS from the original query (for ranking)
|
||
|
|
2. Alternative queries and related terms (for finding more results)
|
||
|
|
|
||
|
|
Query: "{query}"
|
||
|
|
|
||
|
|
Instructions:
|
||
|
|
|
||
|
|
SALIENT TERMS (for ranking - ONLY from original query):
|
||
|
|
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
|
||
|
|
- Include: nouns, proper nouns, technical terms, domain concepts
|
||
|
|
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
|
||
|
|
- These terms determine search ranking - must be from original query
|
||
|
|
|
||
|
|
ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
|
||
|
|
- Alternative phrasings of the query (specific enough to be useful for search)
|
||
|
|
|
||
|
|
Example: "find my piano notes"
|
||
|
|
- Salient (from original): piano, notes
|
||
|
|
- Queries: "piano lesson notes", "piano practice sheets"
|
||
|
|
|
||
|
|
Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
|
||
|
|
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
|
||
|
|
- Queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
|
||
|
|
|
||
|
|
Format:
|
||
|
|
<salient>
|
||
|
|
<term>word_from_original_query</term>
|
||
|
|
</salient>
|
||
|
|
<queries>
|
||
|
|
<query>alternative query</query>
|
||
|
|
</queries>`;_Ee=vEe});var s9,wEe,S_r=v(()=>{Xe();Wb();s9=class s9{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=Zl(),a=this.app.vault.getMarkdownFiles().filter(h=>fu(h,n,o)),s=s9.CONFIG.BATCH_SIZE,u=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),l=[],c=s9.CONFIG.YIELD_INTERVAL;for(let h=0;h<a.length;h++){let y=a[h],g=y.path.toLowerCase(),b=0;for(let _ of u)g.includes(_)&&b++;b>0&&l.push({path:y.path,matchCount:b}),h>0&&h%c===0&&await new Promise(_=>setTimeout(_,0))}l.sort((h,y)=>y.matchCount-h.matchCount);let d=new Set(l.map(h=>h.path)),f=Math.max(0,r-d.size),p=new Set;if(f>0)for(let h=0;h<a.length&&p.size<f;h+=s){let y=a.slice(h,h+s);await Promise.all(y.map(async g=>{if(!(p.size>=f)&&!d.has(g.path))try{let _=(await this.app.vault.cachedRead(g)).toLowerCase();for(let w of u)if(_.includes(w)){p.add(g.path);break}}catch(b){F(`GrepScanner: Skipping file ${g.path}: ${b}`)}})),h%s9.CONFIG.YIELD_INTERVAL===0&&await new Promise(g=>setTimeout(g,0))}let m=[...d,...p].slice(0,r);if(m.length>0){let h=Math.min(d.size,r),y=m.length-h;F(` Grep: ${m.length} files match (${h} path, ${y} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,r=200){return this.batchCachedReadGrep([e],r)}isGrepWorthy(e){return!(!e||e.length<=1)}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}}};s9.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};wEe=s9});function Ax(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var SEe=v(()=>{});var Afo,CEe,C_r=v(()=>{Xe();SEe();Afo={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},CEe=class{constructor(e){this.config=Afo;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=Ax(n.id),i=this.extractFolder(o),a=r.get(i);if(a){let s=n.score*a.boostFactor;return{...n,score:s,explanation:n.explanation?{...n.explanation,folderBoost:{folder:a.folderPath,documentCount:a.documentCount,totalDocsInFolder:a.totalDocsInFolder,relevanceRatio:a.relevanceRatio,boostFactor:a.boostFactor},finalScore:s}:void 0}}return n})}calculateFolderStats(e){let r=new Map;for(let a of e){let s=Ax(a.id),u=this.extractFolder(s);r.has(u)||r.set(u,new Set),r.get(u).add(s)}let n=new Map;for(let[a,s]of r.entries())n.set(a,s.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[a,s]of n.entries()){let u=o.get(a)||s,l=s/u;if(s>=this.config.minDocsForBoost&&l>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(s+1)-1)*Math.sqrt(l),f=Math.min(d,this.config.maxBoostFactor);i.set(a,{folderPath:a,documentCount:s,totalDocsInFolder:u,relevanceRatio:l,boostFactor:f})}}return i}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&&(F(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);F(` ${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 Nfo,xEe,x_r=v(()=>{Xe();SEe();Nfo={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},xEe=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...Nfo,...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=>Ax(s.id))),o=new Map;for(let s of n){le
|
||
|
|
Explicit Chunks: `,a),console.log("Orama Chunks: ",s),console.log("Combined Chunks: ",u),console.log("Max Orama Score: ",c),f?console.log("Reranked Chunks: ",l):console.log("No reranking applied.")),l})}async getExplicitChunks(r){let n=[];for(let o of r){let i=await p0.getInstance().getDocumentsByPath(o.path);if(i.length===0)continue;let a=i.map(s=>new Yl({pageContent:s.content,metadata:{...s.metadata,score:1,path:s.path,mtime:s.mtime,ctime:s.ctime,title:s.title,id:s.id,embeddingModel:s.embeddingModel,tags:s.tags,extension:s.extension,created_at:s.created_at,nchars:s.nchars,chunkId:s.metadata?.chunkId}}));n.push(...a)}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 p0.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&&(ee().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);F("Daily note date range:",d[0],d[d.length-1]);let f=ES(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));F("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};let y=(await ov(a,s)).hits.map(_=>new Yl({pageContent:_.document.content,metadata:{..._.document.metadata,score:_.score,path:_.document.path,mtime:_.document.mtime,ctime:_.document.ctime,title:_.document.title,id:_.document.id,embeddingModel:_.document.embeddingModel,tags:_.document.tags,extension:_.document.extension,created_at:_.document.created_at,nchars:_.document.nchars,chunkId:_.document.metadata?.chunkId}})),g=[...m,...y];return Array.from(new Set(g.map(_=>_.metadata.id))).map(_=>g.find(w=>w.metadata.id===_)).filter(_=>_!==void 0)}F(`Orama search params:
|
||
|
|
`,s);let u=await ov(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 Yl({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,chunkId:l.document.metadata?.chunkId}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await dd.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}}))}}});function est(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 Qat,tst=v(()=>{nv();nO();Qat=class extends gJ{constructor(e){super(e);x(this,"lc_namespace",["langchain","anthropic","output_parsers"]);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(o){throw new CS(`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 Wz(this.zodSchema,r);if(n.success)return n.data;throw new CS(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(r,null,2))}async parseResult(e){let r=e.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?est(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 P_r(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}var M_r=v(()=>{});function R_r(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function I_r(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function A_r(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function N_r(t){return typeof t!="object"||t==null||!("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 D_r,j_r=v(()=>{ra();D_r={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=bb({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},..."cache_control"in(t.metadata
|
||
|
|
|
||
|
|
`))}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(`
|
||
|
|
|
||
|
|
`))}function Bfo(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 Au({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Au({content:[{type:"tool_result",...r.content!=null?{content:ost(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function U_r(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*Ufo(t){let e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let n of t){py(n)&&(yield AN(n,D_r));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=B_r(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=B_r(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(N_r(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if(R_r(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(I_r(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(A_r(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(r.find(i=>i===n.type)&&"text"in n)yield{type:"text",text:n.text,...o?{cache_control:o}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(i=>i===n.type)){let i={...n};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...o?{cache_control:o}:{}}}else n.type==="container_upload"&&(yield{...n,...o?{cache_control:o}:{}})}}}function ost(t){let{content:e}=t;return typeof e=="string"?e:Array.from(Ufo(e))}function MEe(t){let e=Bfo(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.type}" is not supported.`);if(mc(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:k_r(i)};if(mc(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(U_r)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(U_r)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta"||c.type==="server_tool_use")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:ost(i)}}}else return{role:a,content:ost(i)}});return{messages:zfo(o),system:r}}function zfo(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 ist=v(()=>{j_r();q_r();ra()});function z_r(t,e){let r={model_provider:"anthropic"};if(t.type==="message_start"){let{content:n,usage:o,...i}=t.message,a={};for(let[d,f]of Object.entries(i))f!=null&&(a[d]=f);let{input_tokens:s,output_tokens:u,...l}=o??{},c={input_tokens:s,output_tokens:u,total_tokens:s+u,input_token_details:{
|
||
|
|
|
||
|
|
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
|
||
|
|
`,t}function ast(t){let e;return t.status===400&&t.message.includes("tool")?e=REe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=REe(t,"MODEL_AUTHENTICATION"):t.status===404?e=REe(t,"MODEL_NOT_FOUND"):t.status===429?e=REe(t,"MODEL_RATE_LIMIT"):e=t,e}var W_r=v(()=>{});function yr(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function Ie(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)}var MD=v(()=>{});var sst,J_r=v(()=>{sst=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return sst=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});function RD(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var bae,l9=v(()=>{bae=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var ln,Bh,Wg,gq,c9,d9,f9,p9,m9,h9,g9,y9,b9,Nx=v(()=>{l9();ln=class extends Error{},Bh=class t extends ln{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=r}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new gq({message:n,cause:bae(r)});let i=r;return e===400?new d9(e,i,n,o):e===401?new f9(e,i,n,o):e===403?new p9(e,i,n,o):e===404?new m9(e,i,n,o):e===409?new h9(e,i,n,o):e===422?new g9(e,i,n,o):e===429?new y9(e,i,n,o):e>=500?new b9(e,i,n,o):new t(e,i,n,o)}},Wg=class extends Bh{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},gq=class extends Bh{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},c9=class extends gq{constructor({message:e}={}){super({message:e??"Request timed out."})}},d9=class extends Bh{},f9=class extends Bh{},p9=class extends Bh{},m9=class extends Bh{},h9=class extends Bh{},g9=class extends Bh{},y9=class extends Bh{},b9=class extends Bh{}});function cst(t){return typeof t!="object"?{}:t??{}}function G_r(t){if(!t)return!0;for(let e in t)return!1;return!0}function X_r(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Hfo,K_r,ust,lst,Z_r,IEe,dH=v(()=>{Nx();Hfo=/^[a-z][a-z0-9+.-]*:/i,K_r=t=>Hfo.test(t),ust=t=>(ust=Array.isArray,ust(t)),lst=ust;Z_r=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ln(`${t} must be an integer`);if(e<0)throw new ln(`${t} must be a positive integer`);return e},IEe=t=>{try{return JSON.parse(t)}catch{return}}});var Y_r,Q_r=v(()=>{Y_r=t=>new Promise(e=>setTimeout(e,t))});var yq,dst=v(()=>{yq="0.65.0"});function Wfo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function Kfo(){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+
|
||
|
|
`):[]}};Aw=new WeakMap,Nw=new WeakMap;ID.NEWLINE_CHARS=new Set([`
|
||
|
|
`,"\r"]);ID.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function wae(){}function NEe(t,e,r){return!e||DEe[t]>DEe[r]?wae:e[t].bind(e)}function Uh(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Yfo;let n=pvr.get(e);if(n&&n[0]===r)return n[1];let o={error:NEe("error",e,r),warn:NEe("warn",e,r),info:NEe("info",e,r),debug:NEe("debug",e,r)};return pvr.set(e,[r,o]),o}var DEe,yst,Yfo,pvr,AD,jEe=v(()=>{dH();DEe={off:0,error:200,warn:300,info:400,debug:500},yst=(t,e,r)=>{if(t){if(X_r(DEe,t))return t;Uh(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(DEe))}`)}};Yfo={error:wae,warn:wae,info:wae,debug:wae},pvr=new WeakMap;AD=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()==="x-api-key"||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*Qfo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ln("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 ln("Attempted to iterate over a response with no body");let r=new bst,n=new ID,o=_ae(t.body);for await(let i of epo(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*epo(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"?vae(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=fvr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function tpo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Sae,pA,bst,_st=v(()=>{MD();Nx();_9();gst();_9();l9();dH();hst();jEe();Nx();pA=class t{constructor(e,r,n){this.iterator=e,Sae.set(this,void 0),this.controller=r,yr(this,Sae,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Uh(n):console;async function*a(){if(o)throw new ln("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Qfo(e,r)){if(u.event==="completion")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event==="message_start"||u.event==="message_delta"||u.event==="message_stop"||u.event==="content_block_start"||u.event==="content_block_delta"||u.event==="content_block_stop")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event!=="ping"&&u.event==="error")throw new Bh(void 0,IEe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(RD(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 ID,u=_ae(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 ln("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(RD(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Sae=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,Ie(this,Sae,"f")),new t(()=>o(r),this.controller,Ie(this,Sae,"f"))]}toReadableStream(){let e=this,r;return pst({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=vae(JSON.stringify(o)+`
|
||
|
|
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};bst=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]=tpo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function $Ee(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Uh(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):pA.fromSSEResponse(r,e.controller);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 vst(d,r)}return await r.text()})();return Uh(t).debug(`[${n}] response parsed`,AD({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function vst(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var wst=v(()=>{_st();jEe()});var Cae,fH,LEe=v(()=>{MD();wst();fH=class t extends Promise{constructor(e,r,n=$Ee){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Cae.set(this,void 0),yr(this,Cae,e,"f")}_thenUnwrap(e){return new t(Ie(this,Cae,"f"),this.responsePromise,async(r,n)=>vst(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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Ie(this,Cae,"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)}};Cae=new WeakMap});var FEe,Sst,xae,h0,bq=v(()=>{MD();Nx();wst();LEe();dH();Sst=class{constructor(e,r,n,o){FEe.set(this,void 0),yr(this,FEe,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 ln("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ie(this,FEe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(FEe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},xae=class extends fH{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await $Ee(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},h0=class extends Sst{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...cst(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...cst(this.options.query),after_id:e}}:null}}});function pH(t,e,r){return xst(),new File(t,e??"unknown_file",r)}function Tae(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 npo(t){let e=typeof t=="function"?t:t.fetch,r=mvr.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 mvr.set(e,n),n}var xst,Tst,hvr,mvr,opo,ipo,Cst,kEe=v(()=>{_9();xst=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versi
|
||
|
|
${i.map(f=>f.error).join(`
|
||
|
|
`)}
|
||
|
|
${a}
|
||
|
|
${d}`)}return a},Jy=dpo(wvr)});var w9,Pst=v(()=>{mA();bq();hA();kEe();v9();w9=class extends Md{list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/files",h0,{query:o,...r,headers:aa([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(Jy`/v1/files/${e}`,{...n,headers:aa([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};return this._client.get(Jy`/v1/files/${e}/content`,{...n,headers:aa([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:o}=r??{};return this._client.get(Jy`/v1/files/${e}`,{...n,headers:aa([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...o}=e;return this._client.post("/v1/files",hvr({body:o,...r,headers:aa([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});var S9,Mst=v(()=>{mA();bq();hA();v9();S9=class extends Md{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Jy`/v1/models/${e}?beta=true`,{...n,headers:aa([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",h0,{query:o,...r,headers:aa([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var C9,Rst=v(()=>{Nx();_9();gst();C9=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new ID;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ln("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 ln("Attempted to iterate over a response with no body");return new t(_ae(e.body),r)}}});var Oae=v(()=>{Nx()});var x9,Ist=v(()=>{mA();bq();hA();Rst();Oae();v9();x9=class extends Md{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:aa([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Jy`/v1/messages/batches/${e}?beta=true`,{...n,headers:aa([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",h0,{query:o,...r,headers:aa([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(Jy`/v1/messages/batches/${e}?beta=true`,{...n,headers:aa([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};return this._client.post(Jy`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:aa([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let o=await this.retrieve(e);if(!o.results_url)throw new ln(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=r??{};return this._client.get(o.results_url,{...n,headers:aa([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>C9.fromResponse(s.response,s.controller))}}});var Ast=v(()=>{_st()});var hpo,T9,gpo,ypo,BEe,Nst=v(()=>{hpo=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e+
|
||
|
|
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!o.stream&&i==null){let a=XEe[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,a)}return this._client.post("/v1/messages?beta=true",{body:o,timeout:i??6e5,...r,headers:aa([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return GEe.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:aa([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new P9(this._client,e,r)}};wq.Batches=x9;wq.BetaToolRunner=P9});var yA,Ust=v(()=>{mA();Pst();Pst();Mst();Mst();Bst();Bst();yA=class extends Md{constructor(){super(...arguments),this.models=new S9(this._client),this.messages=new wq(this._client),this.files=new w9(this._client)}};yA.Models=S9;yA.Messages=wq;yA.Files=w9});var hH,zst=v(()=>{mA();hA();hH=class extends Md{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:aa([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function Avr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var y0,Sq,Dae,YEe,jae,$ae,QEe,Lae,jD,Fae,ePe,tPe,M9,rPe,nPe,Vst,Mvr,Hst,Wst,Jst,Kst,Rvr,Ivr,oPe,Nvr=v(()=>{MD();l9();Oae();Ast();Nst();Ivr="__json_buf";oPe=class t{constructor(){y0.add(this),this.messages=[],this.receivedMessages=[],Sq.set(this,void 0),this.controller=new AbortController,Dae.set(this,void 0),YEe.set(this,()=>{}),jae.set(this,()=>{}),$ae.set(this,void 0),QEe.set(this,()=>{}),Lae.set(this,()=>{}),jD.set(this,{}),Fae.set(this,!1),ePe.set(this,!1),tPe.set(this,!1),M9.set(this,!1),rPe.set(this,void 0),nPe.set(this,void 0),Hst.set(this,e=>{if(yr(this,ePe,!0,"f"),RD(e)&&(e=new Wg),e instanceof Wg)return yr(this,tPe,!0,"f"),this._emit("abort",e);if(e instanceof ln)return this._emit("error",e);if(e instanceof Error){let r=new ln(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new ln(String(e)))}),yr(this,Dae,new Promise((e,r)=>{yr(this,YEe,e,"f"),yr(this,jae,r,"f")}),"f"),yr(this,$ae,new Promise((e,r)=>{yr(this,QEe,e,"f"),yr(this,Lae,r,"f")}),"f"),Ie(this,Dae,"f").catch(()=>{}),Ie(this,$ae,"f").catch(()=>{})}get response(){return Ie(this,rPe,"f")}get request_id(){return Ie(this,nPe,"f")}async withResponse(){let e=await Ie(this,Dae,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let o=new t;for(let i of r.messages)o._addMessageParam(i);return o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},Ie(this,Hst,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let o=n?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{Ie(this,y0,"m",Wst).call(this);let{response:a,data:s}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let u of s)Ie(this,y0,"m",Jst).call(this,u);if(s.controller.signal?.aborted)throw new Wg;Ie(this,y0,"m",Kst).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(yr(this,rPe,e,"f"),yr(this,nPe,e?.headers.get("request-id"),"f"),Ie(this,YEe,"f").call(this,e),this._emit("connect"))}get ended(){return Ie(this,Fae,"f")}get errored(){return Ie(this,ePe,"f")}get aborted(){return Ie(this,tPe,"f")}abort(){this.controller.abort()}on(e,r){return(Ie(this,jD,"f")[e]||(Ie(this,jD,"f")[e]=[])).pu
|
||
|
|
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let o=XEe[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,stream:e.stream??!1})}stream(e,r){return oPe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Dvr={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};Cq.Batches=R9});var gH,Zst=v(()=>{mA();bq();hA();v9();gH=class extends Md{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Jy`/v1/models/${e}`,{...n,headers:aa([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/models",h0,{query:o,...r,headers:aa([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var jvr=v(()=>{bvr();Ust();zst();Xst();Zst()});var kae,$vr=v(()=>{kae=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()}});var Yst,Qst,iPe,Lvr,Fvr,kvr,xc,bA,eut=v(()=>{MD();J_r();dH();Q_r();l9();fst();_9();uvr();dst();Nx();bq();Est();jvr();LEe();zst();Zst();Ust();Xst();fst();hA();$vr();jEe();dH();Fvr="\\n\\nHuman:",kvr="\\n\\nAssistant:",xc=class{constructor({baseURL:e=kae("ANTHROPIC_BASE_URL"),apiKey:r=kae("ANTHROPIC_API_KEY")??null,authToken:n=kae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){Yst.add(this),iPe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&nvr())throw new ln(`It looks like you're running in a browser-like environment.
|
||
|
|
|
||
|
|
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 });
|
||
|
|
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Qst.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a="warn";this.logLevel=a,this.logLevel=yst(i.logLevel,"ClientOptions.logLevel",this)??yst(kae("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ivr(),yr(this,iPe,svr,"f"),this._options=i,this.apiKey=r,this.authToken=n}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,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))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')}async authHeaders(e){return aa([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return aa([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return aa([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new ln(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${yq}`}defaultIdempotencyKey(){return`stainless-node-retry-${sst()}`}makeStatusError(e,r,n,o){return Bh.generate(e,r,n,o)}buildURL(e,r,n){let o=!Ie(this,Yst,"m",Lvr).call(this)&&n||this.baseURL,i=K_r(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return G_r(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ln("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}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 fH(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(Uh(this).debug(`[${l}] sending request`,AD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Wg;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(bae),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Wg;let b=RD(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Uh(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),Uh(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,AD({retryOfRequestLogID:n,url:s,durationMs:m-d,messag
|
||
|
|
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},dut=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]=Lpo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},N9=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 Jg(`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 Jg(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Jg("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}};N9.NEWLINE_CHARS=new Set([`
|
||
|
|
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);N9.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function mut(t,e,r){if(t=await t,owr(t))return t;if(nwr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=Xae(o)?[await o.arrayBuffer()]:[o];return new aPe(i,e,r)}let n=await kpo(t);if(e||(e=Bpo(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new aPe(n,e,r)}async function kpo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Xae(t))e.push(await t.arrayBuffer());else if(Upo(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${qpo(t)}`);return e}function qpo(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Bpo(t){return fut(t.name)||fut(t.filename)||fut(t.path)?.split(/[\\/]/).pop()}var nwr,owr,Xae,Fpo,fut,Upo,hut,vH,iwr,put,dPe=v(()=>{qae();qae();nwr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",owr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Xae(t),Xae=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",Fpo=t=>owr(t)||nwr(t)||uut(t);fut=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Upo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",hut=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",vH=async t=>{let e=await iwr(t.body);return aut(e,t)},iwr=async t=>{let e=new out;return await Promise.all(Object.entries(t||{}).map(([r,n])=>put(e,r,n))),e},put=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(Fpo(r)){let n=await mut(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>put(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>put(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 dwr(t){let{response:e}=t;if(t.options.stream)return D9("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):cPe.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 D9("response",e.status,e.url,e.headers,a),a}let i=await e.text();return D9("response",e.status,e.url,e.headers,i),i}function Kpo(){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 emo(t){if(!t)return!0;for(let e in t)return!1;return!0}function tmo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function cwr(t,e){for(let r in e){if(!tmo(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 D9(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var Vpo,Hpo,fPe,mPe,hPe,awr,yut,Wpo,Jpo,swr,uwr,lwr,Gpo,Xpo,Z
|
||
|
|
|
||
|
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
||
|
|
If you understand the risks and have appropriate mitigations in place,
|
||
|
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
||
|
|
|
||
|
|
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new SH(this),this.chat=new Tq(this),this.embeddings=new CH(this),this.audio=new _A(this),this.models=new TH(this),this.batches=new wH(this),this.files=new xH(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}`}}};hwr=wu;wu.Groq=hwr;wu.DEFAULT_TIMEOUT=6e4;wu.GroqError=Jg;wu.APIError=zh;wu.APIConnectionError=xq;wu.APIConnectionTimeoutError=I9;wu.APIUserAbortError=_H;wu.NotFoundError=Vae;wu.ConflictError=Hae;wu.RateLimitError=Jae;wu.BadRequestError=Bae;wu.AuthenticationError=Uae;wu.InternalServerError=Kae;wu.PermissionDeniedError=zae;wu.UnprocessableEntityError=Wae;wu.toFile=mut;wu.fileFromPath=sPe;wu.Completions=SH;wu.Chat=Tq;wu.Embeddings=CH;wu.Audio=_A;wu.Models=TH;wu.Batches=wH;wu.Files=xH;gwr=wu});function fmo(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function _wr(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!hy.isInstance(t))throw new Error("Invalid generic chat message");return fmo(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function bwr(t){return t.map(e=>{let r={role:_wr(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 mc(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(bV):(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 pmo(t,e,r){let n=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let a of n??[])try{o.push(HI(a,{returnId:!0}))}catch(s){i.push(vx(a,s.message))}return new uo({content:t.content||"",additional_kwargs:{tool_calls:n},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:r})}default:return new hy(t.content||"",t.role??"unknown")}}function mmo(t,e,r,n){let o=t.role??e,i=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},t.audio&&(a.audio={...t.audio,index:r.choices[0].index});let s,u=n,l,c=r.x_groq;c?.usage&&(s={input_tokens:c.usage.prompt_tokens,output_tokens:c.usage.completion_tokens,total_tokens:c.usage.total_tokens},l={completion_time:c.usage.completion_time,prompt_time:c.usage.prompt_time,queue_time:c.usage.queue_time,total_time:c.usage.total_time}),c?.id&&(u=c.id);let d={usage:s,timing:l};if(o==="user")return new BT({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new Hr({content:i,tool_call_chunks:f,additional_kwargs:a,id:u,response_metadata:d})}else return o==="system"?new UT({content:i,response_metadata:d}):o==="developer"?new UT({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new qT({content:i,additional_kwargs:a,name:t.name,response_metadata:d}):o==="tool"?new $L({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:d}):new kT({content:i,role:o,response_metadata:d})}function hmo(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 lmo,cmo,dmo,Rut,vwr=v(()=>{Sy();aD();ra();xm();su();nv();ywr();Qv();nO();_V();iD();lmo=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format"
|
||
|
|
${plt(this.cause)}`:this.toString()}};$x.SDKValidationError=flt;function plt(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(`${plt(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var hlt=S(TA=>{"use strict";var Kgo=TA&&TA.__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]}),Ggo=TA&&TA.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xgo=TA&&TA.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Kgo(r,e,n[o]);return Ggo(r,e),r}}();Object.defineProperty(TA,"__esModule",{value:!0});TA.ResponseValidationError=void 0;var Zgo=Xgo(ae()),Ygo=FPe(),Qgo=kPe(),mlt=class extends Ygo.MistralError{constructor(e,r){super(e,r),this.name="ResponseValidationError",this.cause=r.cause,this.rawValue=r.rawValue,this.rawMessage=r.rawMessage}pretty(){return this.cause instanceof Zgo.ZodError?`${this.rawMessage}
|
||
|
|
${(0,Qgo.formatZodError)(this.cause)}`:this.toString()}};TA.ResponseValidationError=mlt});var ylt=S(qPe=>{"use strict";Object.defineProperty(qPe,"__esModule",{value:!0});qPe.SDKError=void 0;var eyo=FPe(),glt=class extends eyo.MistralError{constructor(e,r){e&&(e+=": "),e+=`Status ${r.response.status}`;let n=r.response.headers.get("content-type")||'""';n!=="application/json"&&(e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`);let o=r.body||'""';e+=o.length>100?`
|
||
|
|
`:". ";let i=o;if(o.length>1e4){let a=o.substring(0,1e4),s=o.length-1e4;i=`${a}...and ${s} more chars`}e+=`Body: ${i}`,e=e.trim(),super(e,r),this.name="SDKError"}};qPe.SDKError=glt});var br=S(Vm=>{"use strict";Object.defineProperty(Vm,"__esModule",{value:!0});Vm.jsonErr=nyo;Vm.json=oyo;Vm.jsonl=iyo;Vm.jsonlErr=ayo;Vm.textErr=syo;Vm.text=uyo;Vm.bytesErr=lyo;Vm.bytes=cyo;Vm.streamErr=dyo;Vm.stream=fyo;Vm.sseErr=pyo;Vm.sse=myo;Vm.nilErr=hyo;Vm.nil=gyo;Vm.fail=yyo;Vm.match=byo;Vm.unpackHeaders=BPe;var tyo=hlt(),vSr=ylt(),wSr=Rd(),SSr=q9(),CSr=olt(),ryo={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function nyo(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function oyo(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function iyo(t,e,r){return{...r,enc:"jsonl",codes:t,schema:e}}function ayo(t,e,r){return{...r,err:!0,enc:"jsonl",codes:t,schema:e}}function syo(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function uyo(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function lyo(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function cyo(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function dyo(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function fyo(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function pyo(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function myo(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function hyo(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function gyo(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function yyo(t){return{enc:"fail",codes:t}}function byo(...t){return async function(r,n,o){let i,a;for(let d of t){let{codes:f}=d,p="ctype"in d?d.ctype:ryo[d.enc];if(p&&(0,SSr.matchResponse)(r,f,p)){a=d;break}else if(!p&&(0,SSr.matchStatusCode)(r,f)){a=d;break}}if(!a)return[{ok:!1,error:new vSr.SDKError("Unexpected Status or Content-Type",{response:r,request:n,body:await r.text().catch(()=>"")})},i];let s=a.enc,u="";switch(s){case"json":u=await r.text(),i=JSON.parse(u);break;case"jsonl":i=r.body;break;case"bytes":i=new Uint8Array(await r.arrayBuffer());break;case"stream":i=r.body;break;case"text":u=await r.text(),i=u;break;case"sse":i=r.body;break;case"nil":u=await r.text(),i=void 0;break;case"fail":u=await r.text(),i=u;break;default:throw new Error(`Unsupported response type: ${s}`)}if(a.enc==="fail")return[{ok:!1,error:new vSr.SDKError("API error occurred",{request:n,response:r,body:u})},i];let l=a.key||o?.resultKey,c;if("err"in a?c={...o?.extraFields,...a.hdrs?{Headers:BPe(r.headers)}:null,...(0,CSr.isPlainObject)(i)?i:null,request$:n,response$:r,body$:u}:l?c={...o?.extraFields,...a.hdrs?{Headers:BPe(r.headers)}:null,[l]:i}:a.hdrs?c={...o?.extraFields,...a.hdrs?{Headers:BPe(r.headers)}:null,...(0,CSr.isPlainObject)(i)?i:null}:c=i,"err"in a){let d=xSr(c,f=>a.schema.parse(f),"Response validation failed",{request:n,response:r,body:u});return[d.ok?{ok:!1,error:d.value}:d,i]}else return[xSr(c,d=>a.schema.parse(d),"Response validation failed",{request:n,response:r,body:u}),i]}}var _yo=/, */;function BPe(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(_yo);return e}function xSr(t,e,r,n){try{return(0,wSr.OK)(e(t))}catch(o){return(0,wSr.ERR)(new tyo.ResponseValidationError(r,{cause:o,rawValue:t,rawMessage:r,...n}))}}});var ce=S(Dq=>{"use strict";Object.defineProperty(Dq,"__esModule",{value:!0});Dq.invariant=vyo;Dq.remap=wyo;Dq.combineSignals=Syo;Dq.abortSignalAny=TSr;Dq.compactMap=Cyo;Dq.allRequired=xyo;var blt=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function vyo(t,e){if(!t)throw new blt(e)}function wyo(t,e){let r={};if(!Object.keys(e).length)return r=t,r;for(let[n,o]of Object.entries(t)){let i=e[n];i!==null&&(r[i??n]=o)}return r}function Syo(...t){let e=[];for(let r of t)r&&e.push(r);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):TSr(e)}}function TSr(t){let e=new AbortController,r=e.signal;i
|
||
|
|
`)),e(i)}});var cDr=S(XD=>{"use strict";var tFo=XD&&XD.__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]}),rFo=XD&&XD.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BIe=XD&&XD.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&tFo(r,e,n[o]);return rFo(r,e),r}}();Object.defineProperty(XD,"__esModule",{value:!0});XD.agentsStream=dFo;var nFo=BIe(ae()),oFo=Tr(),iFo=iB(),Ese=BIe(br()),aFo=ce(),sFo=te(),uDr=_r(),uFo=mr(),lDr=BIe(zt()),lFo=BIe(Qn()),cFo=vr();function dFo(t,e,r){return new cFo.APIPromise(fFo(t,e,r))}async function fFo(t,e,r){let n=(0,sFo.safeParse)(e,b=>lDr.AgentsCompletionStreamRequest$outboundSchema.parse(b),"Input validation failed");if(!n.ok)return[n,{status:"invalid"}];let o=n.value,i=(0,oFo.encodeJSON)("body",o,{explode:!0}),a=(0,uFo.pathToFunc)("/v1/agents/completions#stream")(),s=new Headers((0,aFo.compactMap)({"Content-Type":"application/json",Accept:"text/event-stream"})),u=await(0,uDr.extractSecurity)(t._options.apiKey),l=u==null?{}:{apiKey:u},c=(0,uDr.resolveGlobalSecurity)(l),d={options:t._options,baseURL:r?.serverURL??t._baseURL??"",operationID:"stream_agents",oAuth2Scopes:[],resolvedSecurity:c,securitySource:t._options.apiKey,retryConfig:r?.retries||t._options.retryConfig||{strategy:"none"},retryCodes:r?.retryCodes||["429","500","502","503","504"]},f=t._createRequest(d,{security:c,method:"POST",baseURL:r?.serverURL,path:a,headers:s,body:i,userAgent:t._options.userAgent,timeoutMs:r?.timeoutMs||t._options.timeoutMs||-1},r);if(!f.ok)return[f,{status:"invalid"}];let p=f.value,m=await t._do(p,{context:d,errorCodes:["422","4XX","5XX"],retryConfig:d.retryConfig,retryCodes:d.retryCodes});if(!m.ok)return[m,{status:"request-error",request:p}];let h=m.value,y={HttpMeta:{Response:h,Request:p}},[g]=await Ese.match(Ese.sse(200,nFo.instanceof(ReadableStream).transform(b=>new iFo.EventStream(b,_=>_.data==="[DONE]"?{done:!0}:{value:lDr.CompletionEvent$inboundSchema.parse(_)}))),Ese.jsonErr(422,lFo.HTTPValidationError$inboundSchema),Ese.fail("4XX"),Ese.fail("5XX"))(h,p,{extraFields:y});return g.ok?[g,{status:"complete",request:p,response:h}]:[g,{status:"complete",request:p,response:h}]}});var fDr=S(UIe=>{"use strict";Object.defineProperty(UIe,"__esModule",{value:!0});UIe.Agents=void 0;var pFo=sDr(),mFo=cDr(),hFo=Vc(),dDr=Rd(),zct=class extends hFo.ClientSDK{async complete(e,r){return(0,dDr.unwrapAsync)((0,pFo.agentsComplete)(this,e,r))}async stream(e,r){return(0,dDr.unwrapAsync)((0,mFo.agentsStream)(this,e,r))}};UIe.Agents=zct});var Pse=S(Vct=>{"use strict";Object.defineProperty(Vct,"__esModule",{value:!0});Vct.isReadableStream=gFo;function gFo(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.getReader=="function"&&typeof e.cancel=="function"&&typeof e.tee=="function"}});var gDr=S(ZD=>{"use strict";var yFo=ZD&&ZD.__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]}),bFo=ZD&&ZD.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),hDr=ZD&&ZD.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null
|
||
|
|
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
|
||
|
|
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
|
||
|
|
`:`[${n[u]}\r
|
||
|
|
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}});var ENe=S(ONe=>{"use strict";Object.defineProperty(ONe,"__esModule",{value:!0});ONe.parseRecordDef=void 0;var mue=ae(),lqr=fm(),_Ko=TNe(),vKo=yNe();function wKo(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===mue.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,lqr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,lqr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===mue.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,_Ko.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===mue.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===mue.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===mue.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,vKo.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}ONe.parseRecordDef=wKo});var Mdt=S(PNe=>{"use strict";Object.defineProperty(PNe,"__esModule",{value:!0});PNe.parseMapDef=void 0;var cqr=fm(),SKo=ENe();function CKo(t,e){if(e.mapStrategy==="record")return(0,SKo.parseRecordDef)(t,e);let r=(0,cqr.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,cqr.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}}}PNe.parseMapDef=CKo});var Rdt=S(MNe=>{"use strict";Object.defineProperty(MNe,"__esModule",{value:!0});MNe.parseNativeEnumDef=void 0;function xKo(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}}MNe.parseNativeEnumDef=xKo});var Idt=S(RNe=>{"use strict";Object.defineProperty(RNe,"__esModule",{value:!0});RNe.parseNeverDef=void 0;function TKo(){return{not:{}}}RNe.parseNeverDef=TKo});var Adt=S(INe=>{"use strict";Object.defineProperty(INe,"__esModule",{value:!0});INe.parseNullDef=void 0;function OKo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}INe.parseNullDef=OKo});var ANe=S(lB=>{"use strict";Object.defineProperty(lB,"__esModule",{value:!0});lB.parseUnionDef=lB.primitiveMappings=void 0;var EKo=fm();lB.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function PKo(t,e){if(e.target==="openApi3")return dqr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in lB.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=lB.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(
|
||
|
|
|
||
|
|
Received: ${JSON.stringify(i,null,2)}`)};if(typeof i=="string")return i;if(Array.isArray(i)){let u=e(a),l=[];return i.forEach(c=>{if(c.type==="text"||c.type==="image_url")l.push(s(c,u));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),l}throw new Error(`Message content must be a string or an array.
|
||
|
|
|
||
|
|
Received: ${JSON.stringify(i,null,2)}`)},n=i=>{if(mc(i)&&i.tool_calls?.length)return i.tool_calls.map(a=>({...a,id:Zae(a.id??"")})).map(bV)},o=new Set;for(let i of t)"tool_call_id"in i&&typeof i.tool_call_id=="string"&&o.add(Zae(i.tool_call_id));return t.flatMap(i=>{let a=n(i),s=r(i.content,i.getType());if("tool_call_id"in i&&typeof i.tool_call_id=="string")return[{role:e(i.getType()),content:s,name:i.name,toolCallId:Zae(i.tool_call_id)}];if(mc(i)){if(a===void 0)return[{role:e(i.getType()),content:s}];{let u=a.filter(l=>o.has(Zae(l.id??"")));return u.length===0?typeof s=="string"&&s.trim()===""||Array.isArray(s)&&s.length===0?[]:[{role:e(i.getType()),content:s}]:[{role:e(i.getType()),toolCalls:u}]}}return[{role:e(i.getType()),content:s}]})}function vYo(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=Iut(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=HI(s,{returnId:!0});i.push({...u,id:u.id??_Pe().replace(/-/g,"")})}catch(u){a.push(vx(s,u.message))}return new uo({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 Au({content:o})}}function wYo(t,e){if(!t.content&&!t.toolCalls)return e?new Hr({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??_Pe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=Iut(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 BT({content:o}):n==="assistant"?new Hr({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 $L({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new qT({content:o,additional_kwargs:i}):new kT({content:o,role:n})}function YBr(t){if(!(!t||!t.length))return t.map(e=>{if("function"in e)return{type:e.type??"function",function:e.function};if(zb(e)){let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Hi(e.schema)?Ii(e.schema):e.schema}}}throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}var QBr,eUr,Tft,tUr=v(()=>{Swr();Pwr();QBr=$(ZBr(),1),eUr=$(q9(),1);ra();aD();xm();Iz();su();nO();_V();Qv();Sy();iD();nv();Tft=class extends Vy{constructor(e){super(e??{});x(this,"lc_namespace",["langchain","chat_models","mistralai"]);x(this,"model","mistral-small-latest");x(this,"apiKey");x(this,"endpoint");x(this,"serverURL");x(this,"temperature",.7);x(this,"streaming",!1);x(this,"topP",1);x(this,"maxTokens");x(this,"safeMode",!1);x(this,"safePrompt",!1);x(this,"randomSeed");x(this,"seed");x(this,"maxRetries");x(this,"lc_serializable",!0);x(this,"streamUsage",!0);x(this,"beforeRequestHooks");x(this,"requestErrorHooks");x(this,"responseHooks");x(this,"httpClient");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"numCompletions");let r=e?.apiKey??un("MISTRAL_API_KEY");if(!r)throw new Error("API key MISTRAL_API_KEY is missing for MistralAI, but it is required.");this.apiKey=r,this.streaming=e?.streaming??this.streaming,this.serverURL=e?.serverURL??this.serverURL,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokens??this.maxTokens,this.safePrompt=e?.safePrompt??this.safePrompt,this.randomSeed=e?.seed??e?.randomSeed??this.seed,this.seed=this.randomSeed,this.maxRetries=e?.maxRetries,this.httpClient=e?.httpClient,this.model=e?.model??e?.modelName??this.model,this.streamUsage=e?.streamUsage??this.streamUsage,this.beforeRequestHooks=
|
||
|
|
`):[]}};Uw=new WeakMap;yW.NEWLINE_CHARS=new Set([`
|
||
|
|
`,"\r"]);yW.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function qft(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 TUr=v(()=>{});async function*LYo(t,e){if(!t.body)throw e.abort(),new Lr("Attempted to iterate over a response with no body");let r=new Bft,n=new yW,o=qft(t.body);for await(let i of FYo(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*FYo(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=CUr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function kYo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var HA,Bft,M1e=v(()=>{Pue();Bw();xUr();TUr();Zi();Bw();HA=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 LYo(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 Jm(void 0,s.error,void 0,Uft(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 Jm(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 yW,s=qft(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 Dft({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?.()}})}};Bft=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]=kYo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function Hft(t,e,r){if(t=await t,EUr(t))return t;if(OUr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=Lue(o)?[await o.arrayBuffer()]:[o];return new x1e(i,e,r)}let n=await BYo(t);if(e||(e=zYo(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new x1e(n,e,r)}async function BYo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Lue(t))e.push(await t.arrayBuffer());else if(VYo(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${UYo(t)}`);return e}function UYo(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function zYo(t){return zft(t.name)||zft(t.filename)||zft(t.path)?.split(/[\\/]/).pop()}var OUr,EUr,Lue,qYo,zft,VYo,Wft,q0,PUr,Vft,R1e=v(()=>{Pue();Pue();OUr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",EUr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Lue(t),Lue=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",qYo=t=>EUr(t)||OUr(t)||Lft(t);zft=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},VYo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Wft=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",q0=async t=>{let e=await PUr(t.body);return jft(e,t)},PUr=async t=>{let e=new Nft;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Vft(e,r,n))),e},Vft=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(qYo(r)){let n=await Hft(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Vft(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Vft(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 DUr(t){let{response:e}=t;if(t.options.stream)return l$("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):HA.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 l$("response",e.status,e.url,e.headers,a),jUr(a,e)}let i=await e.text();return l$("response",e.status,e.url,e.headers,i),i}function jUr(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 XYo(){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 $Ur(t){if(!t)return!0;for(let e in t)return!1;return!0}function LUr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function AUr(t,e){fo
|
||
|
|
\r `.includes(t[n]);)n++};return a()},ypt=t=>dQo(t,Gh.ALL^Gh.NUM)});function pQo(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 Lr(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new Lr(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Lr(`missing function_call.arguments for choice ${d}`);if(!w)throw new Lr(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return y?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...A}=T||{};if(E==null)throw new Lr(`missing choices[${d}].tool_calls[${w}].id
|
||
|
|
${H1e(t)}`);if(O==null)throw new Lr(`missing choices[${d}].tool_calls[${w}].type
|
||
|
|
${H1e(t)}`);if(I==null)throw new Lr(`missing choices[${d}].tool_calls[${w}].function.name
|
||
|
|
${H1e(t)}`);if(R==null)throw new Lr(`missing choices[${d}].tool_calls[${w}].function.arguments
|
||
|
|
${H1e(t)}`);return{...P,id:E,type:O,function:{...A,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return VUr(u,e)}function H1e(t){return JSON.stringify(t)}var V7,Ou,Km,p$,H7,_B,bpt,z1e,_pt,vpt,wpt,V1e,Spt,ZUr,W7,Cpt=v(()=>{Bw();mpt();M1e();Kue();XUr();V7=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},Ou=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)},W7=class t extends z7{constructor(e){super(),Km.add(this),p$.set(this,void 0),H7.set(this,void 0),_B.set(this,void 0),V7(this,p$,e,"f"),V7(this,H7,[],"f")}get currentChatCompletionSnapshot(){return Ou(this,_B,"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())),Ou(this,Km,"m",bpt).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)Ou(this,Km,"m",_pt).call(this,a);if(i.controller.signal?.aborted)throw new pm;return this._addChatCompletion(Ou(this,Km,"m",V1e).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ou(this,Km,"m",bpt).call(this),this._connected();let o=HA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Ou(this,Km,"m",V1e).call(this)),Ou(this,Km,"m",_pt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new pm;return this._addChatCompletion(Ou(this,Km,"m",V1e).call(this))}[(p$=new WeakMap,H7=new WeakMap,_B=new WeakMap,Km=new WeakSet,bpt=function(){this.ended||V7(this,_B,void 0,"f")},z1e=function(r){let n=Ou(this,H7,"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},Ou(this,H7,"f")[r.index]=n,n)},_pt=function(r){if(this.ended)return;let n=Ou(this,Km,"m",ZUr).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=Ou(this,Km,"m",z1e).call(this,i);i.finish_reason&&(Ou(this,Km,"m",wpt).call(this,i),a.current_tool_call_index!=null&&Ou(this,Km,"m",vpt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ou(this,Km,"m",wpt).call(this,i),a.current_tool_call_index!=null&&Ou(this,Km,"m",vpt).call(this,i,a.current_tool_call_index)),a.cu
|
||
|
|
|
||
|
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
||
|
|
If you understand the risks and have appropriate mitigations in place,
|
||
|
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
||
|
|
|
||
|
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
||
|
|
|
||
|
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
||
|
|
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new TW(this),this.chat=new d$(this),this.embeddings=new OW(this),this.files=new wB(this),this.images=new AW(this),this.audio=new JA(this),this.moderations=new DW(this),this.models=new CB(this),this.fineTuning=new Zx(this),this.vectorStores=new Hw(this),this.beta=new Xx(this),this.batches=new gB(this),this.uploads=new EB(this),this.responses=new OB(this),this.evals=new ZA(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 Ift(e,{arrayFormat:"brackets"})}};yzr=Ko;Ko.OpenAI=yzr;Ko.DEFAULT_TIMEOUT=6e5;Ko.OpenAIError=Lr;Ko.APIError=Jm;Ko.APIConnectionError=dB;Ko.APIConnectionTimeoutError=fB;Ko.APIUserAbortError=pm;Ko.NotFoundError=Aue;Ko.ConflictError=Nue;Ko.RateLimitError=jue;Ko.BadRequestError=Mue;Ko.AuthenticationError=Rue;Ko.InternalServerError=$ue;Ko.PermissionDeniedError=Iue;Ko.UnprocessableEntityError=Due;Ko.toFile=Hft;Ko.fileFromPath=T1e;Ko.Completions=TW;Ko.Chat=d$;Ko.ChatCompletionsPage=hB;Ko.Embeddings=OW;Ko.Files=wB;Ko.FileObjectsPage=MW;Ko.Images=AW;Ko.Audio=JA;Ko.Moderations=DW;Ko.Models=CB;Ko.ModelsPage=NW;Ko.FineTuning=Zx;Ko.VectorStores=Hw;Ko.VectorStoresPage=jW;Ko.VectorStoreSearchResponsesPage=$W;Ko.Beta=Xx;Ko.Batches=gB;Ko.BatchesPage=bW;Ko.Uploads=EB;Ko.Responses=OB;Ko.Evals=ZA;Ko.EvalListResponsesPage=PW;bzr=Ko});var fX,vzr=v(()=>{ra();xm();CD();_zr();Xe();fX=class extends Px{constructor(e){let{enableReasoning:r=!1,reasoningEffort:n,enablePromptCaching:o=!0,...i}=e;super(i),this.enableReasoning=r,this.reasoningEffort=n,this.enablePromptCaching=o;let a=e.configuration?.baseURL||"https://openrouter.ai/api/v1";this.isOpenRouter=a.includes("openrouter.ai"),this.openaiClient=new bzr({apiKey:e.apiKey,baseURL:a,defaultHeaders:e.configuration?.defaultHeaders,fetch:e.configuration?.fetch,dangerouslyAllowBrowser:!0})}invocationParams(e){let r=super.invocationParams(e),n=this.isOpenRouter&&this.enablePromptCaching?{...r,cache_control:{type:"ephemeral"}}:r;if(this.enableReasoning)if(this.reasoningEffort){let o=this.reasoningEffort==="minimal"?"low":this.reasoningEffort;return F(`OpenRouter reasoning enabled with effort: ${o}`),{...n,reasoning:{effort:o}}}else return F("OpenRouter reasoning enabled with max_tokens: 1024"),{...n,reasoning:{max_tokens:1024}};return n}async*_streamResponseChunks(e,r,n){let o=this.invocationParams(r),i=this.toOpenRouterMessages(e),a=await this.openaiClient.chat.completions.create({...o,messages:i,stream:!0,stream_options:{...o.stream_options??{},include_usage:!0}}),s;for await(let u of a){u.usage&&(s=u.usage);let l=u.choices?.[0],c=l?.delta;if(!l||!c)continue;let d=this.normalizeReasoningChunk(c?.reasoning),f=this.extractReasoningDetails(l),p=this.extractDeltaContent(c.content),m=this.buildMessageChunk({rawChunk:u,delta:c,content:p,finishReason:l.finish_reason,reasoningDetails:f,reasoningText:d}),h=new Mi({message:m,text:typeof m.content=="string"?m.content:"",generationInfo:{finish_reason:l.finish_reason,system_fingerprint:u.system_fingerprint,model:u.model}});yield h,h.text&&await n?.handleLLMNewToken(h.text)}if(s&&(yield this.buildUsageGenerationChunk(s)),r.signal?.aborted)throw new Error("AbortError")}toOpenRouterMessages(e){return e.map(r=>{let n=typeof r._getType=="function"?r._getType():r.role??"user",o=n==="human"?"user":n==="ai"?"assistant":n;return r.tool_call_id?{role:"tool",content:r.content,tool_call_id:r.tool_call_id}:r.additional_kwargs?.function_call?{role:o,content:r.content,function_call:r.additional_kwargs.function_call}:r.additional_kwargs?.tool_calls?{role:o,content:r.content,tool_calls:r.additional_kwargs.tool_calls}:{role:o,content:r.content}})}buildMessageChunk(e){let{rawChunk:r,delta:n,content:o,finishReason:i,reasoningText:a,reas
|
||
|
|
`).map(r=>r.trim()).filter(r=>r.length>0):[]}parseEventStreamBuffer(e){let r=[];if(e.length<12)return{messages:r,remainingBytes:e};let n=new DataView(e.buffer,e.byteOffset,e.byteLength),o=0;for(;o+12<=e.length;){let a=n.getUint32(o,!1),s=n.getUint32(o+4,!1);if(o+a>e.length)break;if(a<=0||s<0||s+12>a){Ce(`parseEventStreamBuffer: Invalid message structure at offset ${o}: totalLength=${a}, headersLength=${s}`);break}let u=o+12+s,l=o+a-4;if(u>l||l>e.length){Ce(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(u<e.length){let c=e.subarray(u,l),d=this.decodeUtf8(c).trim();d.length>0&&r.push(d)}if(o+=a,a===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:r,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:r}=this.parseEventStreamBuffer(e);return r}buildChunkMetadata(e){let r={provider:"amazon-bedrock"};typeof e?.type=="string"&&(r.event_type=e.type),e?.index!==void 0&&(r.event_index=e.index);let n=this.extractStopReason(e);n&&(r.stop_reason=n);let o=this.extractUsage(e);return o&&(r.usage=o),r}extractStreamText(e){if(!e||typeof e!="object")return null;let r=[e.delta?.thinking,e.content_block_delta?.delta?.thinking,e.contentBlockDelta?.delta?.thinking,e.delta?.reasoning_content,e.reasoning_content];for(let i of r)if(typeof i=="string"&&i.length>0)return i;let n=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let i of n)if(typeof i=="string"&&i.length>0)return i;let o=[e.delta?.text,e.delta?.output_text,e.delta?.content,e.contentBlockDelta?.delta?.text,e.contentBlockDelta?.delta?.output_text,e.contentBlockDelta?.delta?.content,e.content_block_delta?.delta?.text,e.content_block_delta?.delta?.output_text,e.content_block_delta?.delta?.content,e.message?.content,e.messageStop?.message?.content,e.message_stop?.message?.content,e.content];for(let i of o){let a=this.extractTextFromCandidate(i);if(a)return a}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let r=e.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){if(typeof n.text=="string")return n.text;if(typeof n.value=="string")return n.value;if(Array.isArray(n.content))return n.content.map(o=>typeof o?.text=="string"?o.text:"").join("")}return""}).join("");return r.length>0?r:null}if(typeof e=="object"){let r=e;if(typeof r.text=="string")return r.text.length>0?r.text:null;if(r.text&&typeof r.text=="object"){let n=this.extractTextFromCandidate(r.text);if(n)return n}if(typeof r.value=="string")return r.value.length>0?r.value:null;if(Array.isArray(r.content))return this.extractTextFromCandidate(r.content);if(r.delta){let n=this.extractTextFromCandidate(r.delta);if(n)return n}if(r.message&&typeof r.message=="object"){let n=this.extractTextFromCandidate(r.message);if(n)return n}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let r=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||e.messageStop?.stopReason||e.message_stop?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof r=="string"?r:void 0}buildTerminalMetadataChunk(e,r){let n=r?this.normaliseUsageMetadata(r):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),r&&(o.usage=r);let i=new Hr({content:"",response_metadata:o,usage_metadata:n});return new Mi({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let r=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,n=this.coerceNumber(e.outputTokens)??
|
||
|
|
|
||
|
|
`)),i!==void 0&&(u.max_tokens=i),this.anthropicVersion&&(u.anthropic_version=this.anthropicVersion),this.enableThinking?(u.thinking={type:"enabled",budget_tokens:2048},u.temperature=1,F("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")):a!==void 0&&(u.temperature=a),s!==void 0&&(u.top_p=s),u}normaliseMessageContent(e){let{content:r}=e;return typeof r=="string"?r:Array.isArray(r)?r.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?r.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):r.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof r=="object"&&r!==null&&"text"in r?r.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(r=>{if(!r)return"";if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});function rmt(t){return t instanceof B0||t instanceof Error&&t.name==="AuthCancelledError"}var B0,nmt=v(()=>{B0=class t extends Error{constructor(r="Authentication cancelled by user."){super(r);this.name="AuthCancelledError";Object.setPrototypeOf(this,t.prototype)}}});var rle,Czr,BQo,UQo,zQo,omt,VQo,HQo,xzr,WQo,g$,nDe=v(()=>{Qe();BC();rle=require("obsidian");nmt();Czr="Iv1.b507a08c87ecfe98",BQo="https://github.com/login/device/code",UQo="https://github.com/login/oauth/access_token",zQo="https://api.github.com/copilot_internal/v2/token",omt="https://api.githubcopilot.com",VQo=`${omt}/models`,HQo=60*1e3,xzr=60*60*1e3,WQo=3,g$=class t{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.modelPolicyTermsCache=new Map;this.authGeneration=0}static getInstance(){return t.instance||(t.instance=new t),t.instance}getAuthState(){let e=ee(),r=!!e.githubCopilotAccessToken,n=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,a=!(typeof o=="number"&&o>0)||o<Date.now();return n&&!a||n&&r?{status:"authenticated"}:r?{status:"pending"}:{status:"idle"}}isAuthenticated(){return this.getAuthState().status==="authenticated"}async startDeviceCodeFlow(){let e=new URLSearchParams({client_id:Czr,scope:"read:user"}).toString(),r=await(0,rle.requestUrl)({url:BQo,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e,throw:!1}),n=this.getRequestUrlJson(r);if(r.status!==200){let i=typeof n.error_description=="string"?n.error_description:typeof n.error=="string"?n.error:"";throw new Error(i?`Failed to get device code: ${i}`:`Failed to get device code: ${r.status}`)}if(typeof n.device_code!="string"||typeof n.user_code!="string"||typeof n.expires_in!="number")throw new Error("Invalid device code response from GitHub");let o=typeof n.verification_uri=="string"?n.verification_uri:typeof n.verification_uri_complete=="string"?n.verification_uri_complete:null;if(!o)throw new Error("Invalid device code response from GitHub: missing verification URI");return{deviceCode:n.device_code,userCode:n.user_code,verificationUri:o,expiresIn:n.expires_in,interval:typeof n.interval=="number"&&n.interval>0?n.interval:5}}async pollForAccessToken(e,r,n,o){let i=this.authGeneration;this.abortPolling();let a=new AbortController;this.abortController=a;let s=Date.now()+n*1e3,u=0;try{for(;Date.now()<s;){if(a.signal.aborted||this.authGeneration!==i)throw new B0;if(u++,o?.(u),await this.delay(r*1e3,a.signal),a.signal.aborted||this.authGeneration!==i)throw new B0;let l=new URLSearchParams({client_id:Czr,
|
||
|
|
without CORS Error: `+Wr(n)+`
|
||
|
|
with CORS Error: `+Wr(o);throw new Error(i)}}}findModelByName(e){return ee().activeModels.find(n=>n.name===e)}};pd.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,pd.REASONING_MODEL_TEMPERATURE=1;U0=pd});var umt={};En(umt,{TieredLexicalRetriever:()=>Yx});async function XQo(){try{if(!amt){let e=await Promise.resolve().then(()=>(LW(),imt));amt=()=>e.default.getInstance()}return amt().getChatModel()}catch{return null}}var smt,amt,Yx,pX=v(()=>{Xe();Qe();Dt();OD();o9();smt=require("obsidian");oae();cH();amt=null;Yx=class extends fA{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new OEe(r,XQo),this.chunkManager=lq(r)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(r,n){try{let i=ES(r,this.app.vault).map(f=>f.basename),a=[...new Set([...this.options.salientTerms,...i])];ee().debug&&F("TieredLexicalRetriever: Starting search",{query:r,salientTerms:a,maxK:this.options.maxK});let s=ee(),u=await this.searchCore.retrieve(r,{maxResults:this.options.maxK,salientTerms:a,enableLexicalBoosts:s.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),l=u.results;this.lastQueryExpansion=u.queryExpansion;let c=await this.convertToDocuments(l),d=this.sortResults(c);return ee().debug&&F("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:l.length}),d}catch(o){return Ce("TieredLexicalRetriever: Error during search",o),[]}}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 smt.TFile))continue;let u="",l=this.chunkManager;if(typeof l.getChunkText=="function"?u=await l.getChunkText(o.id):typeof l.getChunkTextSync=="function"&&(u=l.getChunkTextSync(o.id)||""),!u)continue;let c=this.app.metadataCache.getFileCache(s);n.push(new Yl({pageContent:u,metadata:{path:a,chunkId:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:c?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let a=this.app.vault.getAbstractFileByPath(o.id);if(!a||!(a instanceof smt.TFile))continue;let s=await this.app.vault.cachedRead(a);if(!s)continue;let u=this.app.metadataCache.getFileCache(a);n.push(new Yl({pageContent:s,metadata:{path:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(l=>l.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){Ce(`TieredLexicalRetriever: Failed to convert result ${o.id}`,i)}return F(`TieredLexicalRetriever: Converted ${n.length} results to Documents`),n}sortResults(r){return r.sort((n,o)=>{let i=n.metadata.score||0,s=(o.metadata.score||0)-i;if(Math.abs(s)>.01)return s;if(n.metadata.isChunk&&o.metadata.isChunk&&n.metadata.path===o.metadata.path){let u=parseInt(n.metadata.chunkId?.split("#")[1]||"0"),l=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return u-l}return s})}}});var Pzr={};En(Pzr,{MergedSemanticRetriever:()=>FW});var RB,FW,lmt=v(()=>{PEe();cH();pX();OD();o9();RB=class RB extends fA{constructor(r,n,o){super();this.app=r;this.options=n;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,n.maxK),this.returnAll=!!n.returnAll;let i=this.returnAll?Pl:Math.min(this.originalMaxK*2,Pl),a={...n,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new Yx(r,a);let s=this.returnAll?Pl:Math.min(this.originalMaxK*2,Pl);this.semanticRetriever=o||new hae({minSimilarityScore:n.minSimilarityScore??.1,maxK:s,salientTerms:n.salientTerms,timeRange:n.timeRange,textWeight:n.textWeight,returnAll:this.returnAll,useRerankerThreshold:n.useRerankerThreshold})}async getRelevantDocuments(r){let[n,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(r),this.semanticRetriever.getRelevantDocuments(r)]),i=new Map;for(let u of n)this.insertResult(i,u,"lexic
|
||
|
|
|
||
|
|
`);return{...o,[this.documentVariableName]:a}}async _call(r,n){return await this.llmChain.call(this._prepInputs(r),n?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");return new gHr({llmChain:await Qh.deserialize(r.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},yHr=class bHr extends nb{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"documentVariableName","context");x(this,"returnIntermediateSteps",!1);x(this,"maxTokens",3e3);x(this,"maxIterations",10);x(this,"ensureMapStep",!1);x(this,"combineDocumentChain");this.llmChain=r.llmChain,this.combineDocumentChain=r.combineDocumentChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.ensureMapStep=r.ensureMapStep??this.ensureMapStep,this.inputKey=r.inputKey??this.inputKey,this.maxTokens=r.maxTokens??this.maxTokens,this.maxIterations=r.maxIterations??this.maxIterations,this.returnIntermediateSteps=r.returnIntermediateSteps??!1}static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=r,a=o,s=[];for(let c=0;c<this.maxIterations;c+=1){let d=a.map(h=>({[this.documentVariableName]:h.pageContent,...i}));if(c!==0||!this.ensureMapStep){let h=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:a,...i}));if(await this.combineDocumentChain.llmChain._getNumTokens(h)<this.maxTokens)break}let p=await this.llmChain.apply(d,n?Array.from({length:d.length},(h,y)=>n.getChild(`map_${y+1}`)):void 0),{outputKey:m}=this.llmChain;this.returnIntermediateSteps&&(s=s.concat(p.map(h=>h[m]))),a=p.map(h=>({pageContent:h[m],metadata:{}}))}let u={[this.combineDocumentChain.inputKey]:a,...i},l=await this.combineDocumentChain.call(u,n?.getChild("combine_documents"));return this.returnIntermediateSteps?{...l,intermediateSteps:s}:l}_chainType(){return"map_reduce_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");if(!r.combine_document_chain)throw new Error("Missing combine_document_chain");return new bHr({llmChain:await Qh.deserialize(r.llm_chain),combineDocumentChain:await cje.deserialize(r.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},_Hr=class vHr extends nb{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"outputKey","output_text");x(this,"documentVariableName","context");x(this,"initialResponseName","existing_answer");x(this,"refineLLMChain");x(this,"documentPrompt",this.defaultDocumentPrompt);this.llmChain=r.llmChain,this.refineLLMChain=r.refineLLMChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.documentPrompt=r.documentPrompt??this.documentPrompt,this.initialResponseName=r.initialResponseName??this.initialResponseName}static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new Ku({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(r=>r!==this.documentVariableName&&r!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}async _constructInitialInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};return this.documentPrompt.inputVariables.forEach(u=>{i[u]=o[u]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...i})},...n}}async _constructRefineInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};this.documentPrompt.inputVa
|
||
|
|
|
||
|
|
{context}
|
||
|
|
|
||
|
|
Question: {question}
|
||
|
|
Helpful Answer:`,inputVariables:["context","question"]}),Voi=`Use the following pieces of context to answer the users question.
|
||
|
|
If you don't know the answer, just say that you don't know, don't try to make up an answer.
|
||
|
|
----------------
|
||
|
|
{context}`,Hoi=[$C.fromTemplate(Voi),rw.fromTemplate("{question}")],Woi=Eb.fromMessages(Hoi),OHr=new Ece(zoi,[[Pce,Woi]])});var PHr=v(()=>{TS();pje()});var MHr=v(()=>{TS();pje()});function RHr(t,e={}){let{prompt:r=OHr.getPrompt(t),verbose:n}=e,o=new Qh({prompt:r,llm:t,verbose:n});return new cje({llmChain:o,verbose:n})}var IHr=v(()=>{QW();Oce();EHr();PHr();MHr()});var NHr={};En(NHr,{VectorDBQAChain:()=>Joi});var Joi,DHr=v(()=>{ZX();IHr();Joi=class AHr extends nb{constructor(r){super(r);x(this,"k",4);x(this,"inputKey","query");x(this,"vectorstore");x(this,"combineDocumentsChain");x(this,"returnSourceDocuments",!1);this.vectorstore=r.vectorstore,this.combineDocumentsChain=r.combineDocumentsChain,this.inputKey=r.inputKey??this.inputKey,this.k=r.k??this.k,this.returnSourceDocuments=r.returnSourceDocuments??this.returnSourceDocuments}static lc_name(){return"VectorDBQAChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments?["sourceDocuments"]:[])}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Question key ${this.inputKey} not found.`);let o=r[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,r.filter,n?.getChild("vectorstore")),a={question:o,input_documents:i},s=await this.combineDocumentsChain.call(a,n?.getChild("combine_documents"));return this.returnSourceDocuments?{...s,sourceDocuments:i}:s}_chainType(){return"vector_db_qa"}static async deserialize(r,n){if(!("vectorstore"in n))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=n;if(!r.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new AHr({combineDocumentsChain:await nb.deserialize(r.combine_documents_chain),k:r.k,vectorstore:o})}serialize(){return{_type:this._chainType(),combine_documents_chain:this.combineDocumentsChain.serialize(),k:this.k}}static fromLLM(r,n,o){let i=RHr(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var jHr,$Hr,Koi,LHr,FHr=v(()=>{TS();jHr=`You are given the below API Documentation:
|
||
|
|
{api_docs}
|
||
|
|
Using this documentation, generate the full API url to call for answering the user question.
|
||
|
|
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
|
||
|
|
|
||
|
|
Question:{question}
|
||
|
|
API url:`,$Hr=new Ku({inputVariables:["api_docs","question"],template:jHr}),Koi=`${jHr} {api_url}
|
||
|
|
|
||
|
|
Here is the response from the API:
|
||
|
|
|
||
|
|
{api_response}
|
||
|
|
|
||
|
|
Summarize this response to answer the original question.
|
||
|
|
|
||
|
|
Summary:`,LHr=new Ku({inputVariables:["api_docs","question","api_url","api_response"],template:Koi})});var qHr={};En(qHr,{APIChain:()=>Goi});var Goi,BHr=v(()=>{ZX();QW();FHr();Goi=class kHr extends nb{constructor(r){super(r);x(this,"apiAnswerChain");x(this,"apiRequestChain");x(this,"apiDocs");x(this,"headers",{});x(this,"inputKey","question");x(this,"outputKey","output");this.apiRequestChain=r.apiRequestChain,this.apiAnswerChain=r.apiAnswerChain,this.apiDocs=r.apiDocs,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.headers=r.headers??this.headers}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}async _call(r,n){let o=r[this.inputKey],i=await this.apiRequestChain.predict({question:o,api_docs:this.apiDocs},n?.getChild("request")),s=await(await fetch(i,{headers:this.headers})).text(),u=await this.apiAnswerChain.predict({question:o,api_docs:this.apiDocs,api_url:i,api_response:s},n?.getChild("response"));return{[this.outputKey]:u}}_chainType(){return"api_chain"}static async deserialize(r){let{api_request_chain:n,api_answer_chain:o,api_docs:i}=r;if(!n)throw new Error("LLMChain must have api_request_chain");if(!o)throw new Error("LLMChain must have api_answer_chain");if(!i)throw new Error("LLMChain must have api_docs");return new kHr({apiAnswerChain:await Qh.deserialize(o),apiRequestChain:await Qh.deserialize(n),apiDocs:i})}serialize(){return{_type:this._chainType(),api_answer_chain:this.apiAnswerChain.serialize(),api_request_chain:this.apiRequestChain.serialize(),api_docs:this.apiDocs}}static fromLLMAndAPIDocs(r,n,o={}){let{apiUrlPrompt:i=$Hr,apiResponsePrompt:a=LHr}=o,s=new Qh({prompt:i,llm:r}),u=new Qh({prompt:a,llm:r});return new this({apiAnswerChain:u,apiRequestChain:s,apiDocs:n,...o})}}});var nb,ZX=v(()=>{Qv();rv();xm();BL();nb=class extends tie{get lc_namespace(){return["langchain","chains",this._chainType()]}constructor(t,e,r){if(arguments.length===1&&typeof t=="object"&&!("saveContext"in t)){let{memory:n,callbackManager:o,...i}=t;super({...i,callbacks:o??i.callbacks}),this.memory=n}else super({verbose:e,callbacks:r}),this.memory=t}_selectMemoryInputs(t){let e={...t};return"signal"in e&&delete e.signal,"timeout"in e&&delete e.timeout,e}async invoke(t,e){let r=vi(e),n=await this._formatValues(t),i=await(await Cm.configure(r?.callbacks,this.callbacks,r?.tags,this.tags,r?.metadata,this.metadata,{verbose:this.verbose}))?.handleChainStart(this.toJSON(),n,void 0,void 0,void 0,void 0,r?.runName),a;try{if(n.signal){let s;a=await Promise.race([this._call(n,i,r),new Promise((u,l)=>{s=()=>{l(new Error("AbortError"))},n.signal?.addEventListener("abort",s)})]).finally(()=>{n.signal&&s&&n.signal.removeEventListener("abort",s)})}else a=await this._call(n,i,r)}catch(s){throw await i?.handleChainError(s),s}return this.memory!=null&&await this.memory.saveContext(this._selectMemoryInputs(t),a),await i?.handleChainEnd(a),Object.defineProperty(a,Z6,{value:i?{runId:i?.runId}:void 0,configurable:!0}),a}_validateOutputs(t){let e=this.outputKeys.filter(r=>!(r in t));if(e.length)throw new Error(`Missing output keys: ${e.join(", ")} from chain ${this._chainType()}`)}async prepOutputs(t,e,r=!1){return this._validateOutputs(e),this.memory&&await this.memory.saveContext(t,e),r?e:{...t,...e}}serialize(){throw new Error("Method not implemented.")}async run(t,e){let r=this.inputKeys.filter(s=>!this.memory?.memoryKeys.includes(s));if(!(r.length<=1))throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);let o=r.length?{[r[0]]:t}:{},i=await this.call(o,e),a=Object.keys(i);if(a.length===1)return i[a[0]];throw new Error("return values have multiple keys, `run` only supported when one key currently")}async _formatValues(t){let e={...t};if(e.timeout&&!e.signal&&(e.signal=AbortSignal.timeout(e.timeout),delete e.timeout),this.memory!=null){let r=await this.memory.loadMemoryVariables(this._selectMemoryInputs(t));for(let[n,o]of Object.entries(r))e[n]=o}return e}async call(t,e,r){let n={tags:r,...qL(e)};return this.invoke(t,n)}async apply(t,e){return Promise.all
|
||
|
|
`;)e--;return t.substring(0,e)}function c8r(t){return l8r(u8r(t))}function Xyt(t){return Zyt(t,Yci)}function f8r(t){return Zyt(t,d8r)}function Qci(t){return m8r(t,d8r)}function edi(t){return Zyt(t,p8r)}function tdi(t){return m8r(t,p8r)}function Zyt(t,e){return e.indexOf(t.nodeName)>=0}function m8r(t,e){return t.getElementsByTagName&&e.some(function(r){return t.getElementsByTagName(r).length})}function K$e(t){return t?t.replace(/(\n+\s*)+/g,`
|
||
|
|
`):""}function h8r(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function Wyt(t,e,r){for(var n=0;n<t.length;n++){var o=t[n];if(rdi(o,e,r))return o}}function rdi(t,e,r){var n=t.filter;if(typeof n=="string"){if(n===e.nodeName.toLowerCase())return!0}else if(Array.isArray(n)){if(n.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof n=="function"){if(n.call(t,e,r))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function ndi(t){var e=t.element,r=t.isBlock,n=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,a=!1,s=null,u=a8r(s,e,o);u!==e;){if(u.nodeType===3||u.nodeType===4){var l=u.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!a&&l[0]===" "&&(l=l.substr(1)),!l){u=Jyt(u);continue}u.data=l,i=u}else if(u.nodeType===1)r(u)||u.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,a=!1):n(u)||o(u)?(i=null,a=!0):i&&(a=!1);else{u=Jyt(u);continue}var c=a8r(s,u,o);s=u,u=c}i&&(i.data=i.data.replace(/ $/,""),i.data||Jyt(i))}}function Jyt(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function a8r(t,e,r){return t&&t.parentNode===e||r(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function odi(){var t=Yyt.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function idi(){var t=function(){};return adi()?t.prototype.parseFromString=function(e){var r=new window.ActiveXObject("htmlfile");return r.designMode="on",r.open(),r.write(e),r.close(),r}:t.prototype.parseFromString=function(e){var r=document.implementation.createHTMLDocument("");return r.open(),r.write(e),r.close(),r},t}function adi(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{Yyt.ActiveXObject&&(t=!0)}return t}function udi(t,e){var r;if(typeof t=="string"){var n=ldi().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");r=n.getElementById("turndown-root")}else r=t.cloneNode(!0);return ndi({element:r,isBlock:Xyt,isVoid:f8r,isPre:e.preformattedCode?cdi:null}),r}function ldi(){return Kyt=Kyt||new sdi,Kyt}function cdi(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function ddi(t,e){return t.isBlock=Xyt(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=fdi(t),t.flankingWhitespace=pdi(t,e),t}function fdi(t){return!f8r(t)&&!edi(t)&&/^\s*$/i.test(t.textContent)&&!Qci(t)&&!tdi(t)}function pdi(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var r=mdi(t.textContent);return r.leadingAscii&&s8r("left",t,e)&&(r.leading=r.leadingNonAscii),r.trailingAscii&&s8r("right",t,e)&&(r.trailing=r.trailingNonAscii),{leading:r.leading,trailing:r.trailing}}function mdi(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function s8r(t,e,r){var n,o,i;return t==="left"?(n=e.previousSibling,o=/ $/):(n=e.nextSibling,o=/^ /),n&&(n.nodeType===3?i=o.test(n.nodeValue):r.preformattedCode&&n.nodeName==="CODE"?i=!1:n.nodeType===1&&!Xyt(n)&&(i=o.test(n.textContent))),i}function G$e(t){if(!(this instanceof G$e))return new G$e(t);var e={rules:sb,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(r,n){return n.isBlock?`
|
||
|
|
|
||
|
|
`:""},keepReplacement:function(r,n){return n.isBlock?`
|
||
|
|
|
||
|
|
`+n.outerHTML+`
|
||
|
|
|
||
|
|
`:n.outerHTML},defaultReplacement:function(r,n){return n.isBlock?`
|
||
|
|
|
||
|
|
`+r+`
|
||
|
|
|
||
|
|
`:r}};this.options=Zci({},e,t),this.rules=new h8r(this.options)}function g8r(t){var e=this;return hdi.call(t.childNodes,function(r,n){n=new ddi(n,e.options);var o="";return n.nodeType===3?o=n.isCode?n.nodeValue:e.escape(n.nodeValue):n.nodeType===1&&(o=bdi.call(e,n)),y8r(r,o)},"")}function ydi(t){var e=this;return this.rules.forEach(function(r){typeof r.append=="function"&&(t=y8r(t,r.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function bdi(t){var e=this.rules.forNode(t),r=g8r.call(this,t),n=t.flankingWhitespace;return(n.leading||n.trailing)&&(r=r.trim()),n.leading+e.replacement(r,t,this.options)+n.trailing}function y8r(t,e){var r=l8r(t),n=u8r(e),o=Math.max(t.length-r.length,e.length-n.length),i=`
|
||
|
|
|
||
|
|
`.substring(0,o);return r+i+n}function _di(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var Yci,d8r,p8r,sb,Yyt,sdi,Kyt,hdi,gdi,b8r,_8r=v(()=>{Yci=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];d8r=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];p8r=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];sb={};sb.paragraph={filter:"p",replacement:function(t){return`
|
||
|
|
|
||
|
|
`+t+`
|
||
|
|
|
||
|
|
`}};sb.lineBreak={filter:"br",replacement:function(t,e,r){return r.br+`
|
||
|
|
`}};sb.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,r){var n=Number(e.nodeName.charAt(1));if(r.headingStyle==="setext"&&n<3){var o=Gyt(n===1?"=":"-",t.length);return`
|
||
|
|
|
||
|
|
`+t+`
|
||
|
|
`+o+`
|
||
|
|
|
||
|
|
`}else return`
|
||
|
|
|
||
|
|
`+Gyt("#",n)+" "+t+`
|
||
|
|
|
||
|
|
`}};sb.blockquote={filter:"blockquote",replacement:function(t){return t=c8r(t).replace(/^/gm,"> "),`
|
||
|
|
|
||
|
|
`+t+`
|
||
|
|
|
||
|
|
`}};sb.list={filter:["ul","ol"],replacement:function(t,e){var r=e.parentNode;return r.nodeName==="LI"&&r.lastElementChild===e?`
|
||
|
|
`+t:`
|
||
|
|
|
||
|
|
`+t+`
|
||
|
|
|
||
|
|
`}};sb.listItem={filter:"li",replacement:function(t,e,r){var n=r.bulletListMarker+" ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),a=Array.prototype.indexOf.call(o.children,e);n=(i?Number(i)+a:a+1)+". "}var s=/\n$/.test(t);return t=c8r(t)+(s?`
|
||
|
|
`:""),t=t.replace(/\n/gm,`
|
||
|
|
`+" ".repeat(n.length)),n+t+(e.nextSibling?`
|
||
|
|
`:"")}};sb.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){return`
|
||
|
|
|
||
|
|
`+e.firstChild.textContent.replace(/\n/g,`
|
||
|
|
`)+`
|
||
|
|
|
||
|
|
`}};sb.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){for(var n=e.firstChild.getAttribute("class")||"",o=(n.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,a=r.fence.charAt(0),s=3,u=new RegExp("^"+a+"{3,}","gm"),l;l=u.exec(i);)l[0].length>=s&&(s=l[0].length+1);var c=Gyt(a,s);return`
|
||
|
|
|
||
|
|
`+c+o+`
|
||
|
|
`+i.replace(/\n$/,"")+`
|
||
|
|
`+c+`
|
||
|
|
|
||
|
|
`}};sb.horizontalRule={filter:"hr",replacement:function(t,e,r){return`
|
||
|
|
|
||
|
|
`+r.hr+`
|
||
|
|
|
||
|
|
`}};sb.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var r=e.getAttribute("href");r&&(r=r.replace(/([()])/g,"\\$1"));var n=K$e(e.getAttribute("title"));return n&&(n=' "'+n.replace(/"/g,'\\"')+'"'),"["+t+"]("+r+n+")"}};sb.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,r){var n=e.getAttribute("href"),o=K$e(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,a;switch(r.linkReferenceStyle){case"collapsed":i="["+t+"][]",a="["+t+"]: "+n+o;break;case"shortcut":i="["+t+"]",a="["+t+"]: "+n+o;break;default:var s=this.references.length+1;i="["+t+"]["+s+"]",a="["+s+"]: "+n+o}return this.references.push(a),i},references:[],append:function(t){var e="";return this.references.length&&(e=`
|
||
|
|
|
||
|
|
`+this.references.join(`
|
||
|
|
`)+`
|
||
|
|
|
||
|
|
`,this.references=[]),e}};sb.emphasis={filter:["em","i"],replacement:function(t,e,r){return t.trim()?r.emDelimiter+t+r.emDelimiter:""}};sb.strong={filter:["strong","b"],replacement:function(t,e,r){return t.trim()?r.strongDelimiter+t+r.strongDelimiter:""}};sb.code={filter:function(t){var e=t.previousSibling||t.nextSibling,r=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!r},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",r="`",n=t.match(/`+/gm)||[];n.indexOf(r)!==-1;)r=r+"`";return r+e+t+e+r}};sb.image={filter:"img",replacement:function(t,e){var r=K$e(e.getAttribute("alt")),n=e.getAttribute("src")||"",o=K$e(e.getAttribute("title")),i=o?' "'+o+'"':"";return n?"":""}};h8r.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var e;return(e=Wyt(this.array,t,this.options))||(e=Wyt(this._keep,t,this.options))||(e=Wyt(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};Yyt=typeof window<"u"?window:{};sdi=odi()?Yyt.DOMParser:idi();hdi=Array.prototype.reduce,gdi=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];G$e.prototype={turndown:function(t){if(!_di(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=g8r.call(this,new udi(t,this.options));return ydi.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return gdi.reduce(function(e,r){return e.replace(r[0],r[1])},t)}};b8r=G$e});function PZ(t){return typeof t=="object"&&t!==null}function MZ(t){if(typeof t=="string")return t;if(t==null)return"";try{return String(t)}catch{return""}}function C8r(t){return t instanceof Error?t.message:MZ(t)}async function vdi(t){await new Promise(e=>setTimeout(e,t))}async function x8r(t,e,r,n){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new Qw(`${n} timed out after ${e}ms`);await vdi(r)}}function v8r(t,e){let r=(t??"").trim();if(!r)return"";if(!e)return r;try{return new URL(r,e).href}catch{return r}}function w8r(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function wdi(t){let e=new b8r({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(r,n)=>{let o=n,i=o.getAttribute("href")??"",a=w8r(v8r(i,t)),s=r?.trim()||o.textContent||a;return a?`[${s}](${a})`:s}}),e.addRule("webviewer-image",{filter:"img",replacement:(r,n)=>{let o=n,i=o.getAttribute("alt")??"",a=o.getAttribute("src")??"",s=w8r(v8r(a,t));return s?``:""}}),e}function Qyt(t,e){if(!t.trim())return"";let r=wdi(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?r.turndown(i).replace(/\n{3,}/g,`
|
||
|
|
|
||
|
|
`).trim():""}function ebt(t){let e=t.commands;return!e||!PZ(e)||typeof e.executeCommandById!="function"?null:e}function T8r(t,e){let r=ebt(t);if(!r)return!1;if(r.commands){if(r.commands instanceof Map)return r.commands.has(e);if(typeof r.commands=="object")return e in r.commands}return typeof r.listCommands=="function"?r.listCommands().some(o=>o.id===e):!1}function O8r(t,e){return t.workspace.getLeavesOfType(C3).includes(e)}function S8r(t){if(!PZ(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!PZ(e))return null;let r=e;return typeof r.openUrl=="function"||typeof r.handleOpenUrl=="function"?r:null}function E8r(t,e){let r=t.internalPlugins;if(!r||!PZ(r))return null;let n=r.plugins;if(!n)return null;let o=n instanceof Map?n.get(C3):PZ(n)?n[C3]:null;if(o){let a=S8r(o);if(a)return a}let i;if(n instanceof Map)i=Array.from(n.values());else if(PZ(n))i=Object.values(n);else return e&&e(),null;for(let a of i){let s=S8r(a);if(s)return s}return null}var X$e=v(()=>{_8r();EZ()});function RZ(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function P8r(t,e={}){let{signal:r}=e;if(r?.aborted)throw new hU("Operation was aborted");try{let n=Promise.resolve(t.view.getReaderModeContent());if(!r){let i=await n;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,a)=>{let s=()=>{a(new hU("Operation was aborted"))};r.addEventListener("abort",s,{once:!0}),n.then(u=>{r.removeEventListener("abort",s),i(u)}).catch(u=>{r.removeEventListener("abort",s),a(u)})});return typeof o?.md=="string"?o.md:""}catch(n){throw n instanceof hU||ie("Failed to get reader mode content:",n),n}}async function Z$e(t,e=!0){let r=OZ(t),n='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n),i=MZ(o);return e?i.trim():i}catch(o){throw ie("Failed to get selected text:",o),o}}async function Y$e(t){let e=OZ(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
|
||
|
|
const sel = window.getSelection();
|
||
|
|
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
|
||
|
|
const div = document.createElement("div");
|
||
|
|
for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
|
||
|
|
return div.innerHTML;
|
||
|
|
})()`,o="";try{let i=await e.executeJavaScript(n);o=MZ(i)}catch(i){throw ie("Failed to get selection HTML:",i),i}try{return Qyt(o,r)}catch(i){throw ie("Failed to convert HTML to Markdown:",i),i}}async function M8r(t){let e=OZ(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
|
||
|
|
const clone = document.body.cloneNode(true);
|
||
|
|
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
|
||
|
|
return clone.innerHTML;
|
||
|
|
})()`,o="";try{let i=await e.executeJavaScript(n);o=MZ(i)}catch(i){throw ie("Failed to get page HTML:",i),i}try{return Qyt(o,r)}catch(i){throw ie("Failed to convert page HTML to Markdown:",i),i}}async function R8r(t,e=!0){let r=OZ(t),n=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n);return MZ(o)}catch(o){throw ie("Failed to get HTML:",o),o}}function Q$e(t){try{let e=new URL(t),r=e.hostname.replace(/^www\./,"").replace(/^m\./,"");return r==="youtube.com"&&e.pathname==="/watch"?e.searchParams.get("v"):r==="youtu.be"&&e.pathname.length>1?e.pathname.slice(1).split("/")[0]:(r==="youtube.com"&&e.pathname.startsWith("/shorts/")||r==="youtube.com"&&e.pathname.startsWith("/embed/"))&&e.pathname.split("/")[2]||null}catch{return null}}function I8r(t){return Q$e(t)!==null}function Sdi(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(r=>typeof r=="object"&&r!==null&&typeof r.timestamp=="string"&&typeof r.text=="string")}async function A8r(t,e={}){let r=OZ(t),{timeoutMs:n=1e4}=e,o=Math.ceil(n/500),i="";try{i=typeof r.getURL=="function"?r.getURL():""}catch{i=""}i||(i=t.view?.url??"");let a=Q$e(i);if(!a)throw new Error("Not a YouTube video page");let s=`(async () => {
|
||
|
|
const videoId = ${JSON.stringify(a)};
|
||
|
|
|
||
|
|
// =========================================================================
|
||
|
|
// Step 1: Extract video metadata from JSON-LD (structured data)
|
||
|
|
// JSON-LD is more reliable than DOM selectors as it's machine-readable
|
||
|
|
// =========================================================================
|
||
|
|
let title = '';
|
||
|
|
let channel = '';
|
||
|
|
let description = '';
|
||
|
|
let uploadDate = '';
|
||
|
|
let duration = '';
|
||
|
|
let genre = '';
|
||
|
|
|
||
|
|
// Helper to extract fields from a VideoObject schema
|
||
|
|
const extractVideoObject = (data) => {
|
||
|
|
if (!data || data['@type'] !== 'VideoObject') return;
|
||
|
|
if (!title && data.name && typeof data.name === 'string') {
|
||
|
|
title = data.name;
|
||
|
|
}
|
||
|
|
if (!description && data.description && typeof data.description === 'string') {
|
||
|
|
description = data.description;
|
||
|
|
}
|
||
|
|
if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
|
||
|
|
uploadDate = data.uploadDate;
|
||
|
|
}
|
||
|
|
// JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
|
||
|
|
if (!duration && data.duration && typeof data.duration === 'string') {
|
||
|
|
const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
|
||
|
|
if (match) {
|
||
|
|
const h = match[1] ? match[1] + ':' : '';
|
||
|
|
const m = match[2] || '0';
|
||
|
|
const s = match[3] || '0';
|
||
|
|
duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (!genre && data.genre) {
|
||
|
|
genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
|
||
|
|
}
|
||
|
|
// author can be string, object {name}, or array [{name}]
|
||
|
|
if (!channel && data.author) {
|
||
|
|
const author = data.author;
|
||
|
|
if (typeof author === 'string') {
|
||
|
|
channel = author;
|
||
|
|
} else if (Array.isArray(author) && author[0]?.name) {
|
||
|
|
channel = String(author[0].name);
|
||
|
|
} else if (author?.name) {
|
||
|
|
channel = String(author.name);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
// Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
|
||
|
|
const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
|
||
|
|
for (const el of ldJsonEls) {
|
||
|
|
try {
|
||
|
|
const data = JSON.parse(el.textContent || '');
|
||
|
|
if (Array.isArray(data)) {
|
||
|
|
for (const item of data) {
|
||
|
|
extractVideoObject(item);
|
||
|
|
}
|
||
|
|
} else if (data['@graph'] && Array.isArray(data['@graph'])) {
|
||
|
|
for (const item of data['@graph']) {
|
||
|
|
extractVideoObject(item);
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
extractVideoObject(data);
|
||
|
|
}
|
||
|
|
// Stop if we have all essential fields
|
||
|
|
if (title && channel && description) break;
|
||
|
|
} catch {}
|
||
|
|
}
|
||
|
|
|
||
|
|
// =========================================================================
|
||
|
|
// Step 2: Fallback to DOM selectors for missing metadata
|
||
|
|
// =========================================================================
|
||
|
|
if (!title) {
|
||
|
|
title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
|
||
|
|
|| document.querySelector('#title h1')?.textContent?.trim() || '';
|
||
|
|
}
|
||
|
|
if (!channel) {
|
||
|
|
channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
|
||
|
|
|| document.querySelector('#channel-name a')?.textContent?.trim()
|
||
|
|
|| document.querySelector('#channel-name')?.textContent?.trim() || '';
|
||
|
|
}
|
||
|
|
if (!duration) {
|
||
|
|
duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
|
||
|
|
}
|
||
|
|
|
||
|
|
// =========================================================================
|
||
|
|
// Step 3: Find or open the transcript panel
|
||
|
|
// Reason: YouTube has two coexisting transcript panel DOM structures:
|
||
|
|
// - Classic ("In this video"): ytd-transcript-segment-renderer
|
||
|
|
// - Modern ("Transcript"): transcript-segment-view-model
|
||
|
|
// YouTube selects the panel type server-side per video. We must support both.
|
||
|
|
// All segment queries are scoped to the panel to avoid false matches.
|
||
|
|
// =========================================================================
|
||
|
|
|
||
|
|
// Reason: Find panel by checking for transcript segment elements inside it,
|
||
|
|
// rather than relying on fragile target-id strings that YouTube changes.
|
||
|
|
// Prefer visible panels to avoid picking up hidden/stale panels YouTube
|
||
|
|
// leaves in the DOM during page transitions.
|
||
|
|
const findTranscriptPanel = () => {
|
||
|
|
const panels = document.querySelectorAll('ytd-engagement-panel-section-list-renderer');
|
||
|
|
for (const panel of panels) {
|
||
|
|
const hasSegments = panel.querySelector('ytd-transcript-segment-renderer')
|
||
|
|
|| panel.querySelector('transcript-segment-view-model');
|
||
|
|
if (!hasSegments) continue;
|
||
|
|
const style = window.getComputedStyle(panel);
|
||
|
|
if (style.display !== 'none' && style.visibility !== 'hidden') return panel;
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
};
|
||
|
|
|
||
|
|
// Reason: Auto-detect classic vs modern layout and use the correct selectors
|
||
|
|
// for each. Queries are scoped to the panel to prevent matching unrelated UI.
|
||
|
|
const extractFromPanel = (panel) => {
|
||
|
|
const classicSegs = panel.querySelectorAll('ytd-transcript-segment-renderer');
|
||
|
|
if (classicSegs.length > 0) {
|
||
|
|
return [...classicSegs].map(seg => ({
|
||
|
|
timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
|
||
|
|
text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
|
||
|
|
})).filter(t => t.timestamp && t.text);
|
||
|
|
}
|
||
|
|
const modernSegs = panel.querySelectorAll('transcript-segment-view-model');
|
||
|
|
if (modernSegs.length > 0) {
|
||
|
|
return [...modernSegs].map(seg => ({
|
||
|
|
timestamp: seg.querySelector('.ytwTranscriptSegmentViewModelTimestamp')?.textContent?.trim() || '',
|
||
|
|
text: [...seg.querySelectorAll('span.yt-core-attributed-string')].map(s => s.textContent || '').join('').trim() || ''
|
||
|
|
})).filter(t => t.timestamp && t.text);
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
};
|
||
|
|
|
||
|
|
let panel = findTranscriptPanel();
|
||
|
|
let needClose = false;
|
||
|
|
|
||
|
|
if (!panel) {
|
||
|
|
const btn = document.querySelector('ytd-video-description-transcript-section-renderer button')
|
||
|
|
|| document.querySelector('ytd-video-description-transcript-section-renderer [role="button"]');
|
||
|
|
if (btn) {
|
||
|
|
btn.click();
|
||
|
|
needClose = true;
|
||
|
|
|
||
|
|
// Poll for the panel container to appear (not individual segments)
|
||
|
|
for (let i = 0; i < ${o}; i++) {
|
||
|
|
await new Promise(r => setTimeout(r, 500));
|
||
|
|
panel = findTranscriptPanel();
|
||
|
|
if (panel) break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// =========================================================================
|
||
|
|
// Step 4: Extract transcript segments from the panel
|
||
|
|
// =========================================================================
|
||
|
|
|
||
|
|
// Reason: Close via captured panel element rather than hardcoded target-id.
|
||
|
|
// This is resilient to YouTube changing the target-id string.
|
||
|
|
const closePanel = () => {
|
||
|
|
if (!needClose || !panel) return;
|
||
|
|
const closeBtn = panel.querySelector('#visibility-button button')
|
||
|
|
|| panel.querySelector('#visibility-button [role="button"]');
|
||
|
|
if (closeBtn) closeBtn.click();
|
||
|
|
};
|
||
|
|
|
||
|
|
try {
|
||
|
|
const transcript = panel ? (extractFromPanel(panel) || []) : [];
|
||
|
|
return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
|
||
|
|
} finally {
|
||
|
|
closePanel();
|
||
|
|
}
|
||
|
|
})()`,u=await r.executeJavaScript(s);if(!Sdi(u))throw new Error("Invalid transcript data structure");return u}async function N8r(t,e,r={}){let{preferCommand:n=!0,focusLeafBeforeCommand:o=!0}=r;if(n)try{return await e(J$e.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),F("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){Ce("save-to-vault command failed, falling back:",i)}try{return await Promise.resolve(t.view.saveAsMarkdown()),F("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw ie("Failed to save Web Viewer page:",i),i}}var tbt=v(()=>{Xe();EZ();X$e()});function ub(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function IZ(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let r=new URL(e);r.hash="",(r.protocol==="http:"&&r.port==="80"||r.protocol==="https:"&&r.port==="443")&&(r.port=""),r.pathname!=="/"&&(r.pathname=r.pathname.replace(/\/+$/,""));let n=Array.from(r.searchParams.entries());return n.length>0?(n.sort(([o,i],[a,s])=>o!==a?o.localeCompare(a):i.localeCompare(s)),r.search=`?${new URLSearchParams(n).toString()}`):r.search="",r.toString()}catch{return e}}function j8r(t){return ub(t)??void 0}function rbt(t){let e=ub(t.url);if(!e)return null;let r=j8r(t.title),n=j8r(t.faviconUrl);return{url:e,title:r,faviconUrl:n,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function x3(t){let e=new Map;for(let r of t){let n=rbt(r);if(!n)continue;let o=e.get(n.url);if(!o){e.set(n.url,n);continue}e.set(n.url,{...o,title:n.title??o.title,faviconUrl:n.faviconUrl??o.faviconUrl,isLoaded:n.isLoaded??o.isLoaded,isActive:o.isActive||n.isActive?!0:void 0})}return Array.from(e.values())}function $8r(t){let e=x3(t),r=!1;return e.map(n=>{if(!n.isActive)return n;if(!r)return r=!0,n;let{isActive:o,...i}=n;return i})}var AZ=v(()=>{});var Cdi,eLe,L8r=v(()=>{Xe();X$e();EZ();AZ();Cdi=["did-finish-load","page-favicon-updated","page-title-updated"],eLe=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!hde(e)?(this.lastActiveLeaf=null,null):O8r(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,r={}){let n=e.trim();if(!n)return null;let o=this.getLeaves();for(let c of o)if(c?.view?.url===n)return c;let i=IZ(n);if(!i)return null;let a=[];for(let c of o){let d=c?.view?.url;if(!d)continue;IZ(d)===i&&a.push(c)}if(a.length===0)return null;if(a.length===1)return a[0];let s=(r.title??"").trim();if(s){let c=s.toLowerCase(),d=[];for(let f of a)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===c&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(Ce("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:n,title:s,matches:d.length}),d[0])}}let u=this.getActiveLeaf();if(u&&a.includes(u))return u;let l=this.getLastActiveLeaf();return l&&a.includes(l)?l:(Ce("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:n,matches:a.length}),a[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let r=this.app.workspace.on("active-leaf-chan
|
||
|
|
- Key concepts and main ideas
|
||
|
|
- Important facts, names, and dates
|
||
|
|
- Technical details relevant for Q&A
|
||
|
|
|
||
|
|
Keep the summary concise but information-dense. Output only the summary.
|
||
|
|
|
||
|
|
Title: {title}
|
||
|
|
Path: {path}
|
||
|
|
|
||
|
|
Content:
|
||
|
|
{content}
|
||
|
|
|
||
|
|
Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=U0.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let r=e.length;F(`[ContextCompactor] Starting compaction of ${r} chars`);let n=this.parseItems(e);if(n.length===0)return this.noOpResult(e);let o=await this.summarizeItems(n);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,n,o);return F(`[ContextCompactor] Done: ${r} -> ${i.length} chars (${((1-i.length/r)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:r,compactedCharCount:i.length,itemsProcessed:n.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let r=[];for(let n of this.BLOCK_TYPES){let o=new RegExp(`<${n}>[\\s\\S]*?<\\/${n}>`,"g"),i;for(;(i=o.exec(e))!==null;){let a=this.parseBlock(i[0],n,i.index);a&&r.push(a)}}return r.sort((n,o)=>n.startIndex-o.startIndex),r.filter((n,o)=>!r.some((i,a)=>o!==a&&i.startIndex<=n.startIndex&&i.endIndex>=n.endIndex))}parseBlock(e,r,n){let o=l=>new RegExp(`<${l}>([^<]*)</${l}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",a=o("path")||o("url"),s=o("title")||a.split("/").pop()||"Untitled",u=i();return{type:r,path:a,title:s,content:u,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:n,endIndex:n+e.length}}async summarizeItems(e){let r=new Map,n=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(n.length===0)return r;F(`[ContextCompactor] Summarizing ${n.length} items`);for(let o=0;o<n.length;o+=this.MAX_CONCURRENCY){let i=n.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:s,item:u})=>{try{return{index:s,summary:await this.summarize(u)}}catch(l){return F(`[ContextCompactor] Failed to summarize item ${s}:`,l),{index:s,summary:null}}}))).forEach(({index:s,summary:u})=>{u&&r.set(s,u)})}return r.size<n.length*.5?(F("[ContextCompactor] High failure rate, aborting compaction"),new Map):r}async summarize(e){let r=e.content;r.length>this.MAX_ITEM_SIZE&&(r=r.slice(0,this.MAX_ITEM_SIZE)+`
|
||
|
|
[TRUNCATED]`);let n=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",r),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new Au(n)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,r,n){let o=e;return Array.from(n.keys()).sort((i,a)=>a-i).forEach(i=>{let a=r[i],s=n.get(i),u=this.buildBlock(a,s);o=o.slice(0,a.startIndex)+u+o.slice(a.endIndex)}),o}buildBlock(e,r){let n=[`<${e.type}>`];if(e.title&&n.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";n.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&n.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&n.push(`<mtime>${e.metadata.mtime}</mtime>`),n.push(`<content>[SUMMARIZED]
|
||
|
|
${r}</content>`),n.push(`</${e.type}>`),n.join(`
|
||
|
|
`)}}});var $0i={};En($0i,{default:()=>cBe});module.exports=wpe($0i);aA();na();Xe();var qbr=$(oH()),ZG=class t{constructor(e){this.memoryCache=new Map;this.cacheDir=e}static getInstance(e=".copilot/file-content-cache"){return t.instance||(t.instance=new t(e)),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(F("Creating file cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e,r){let n=`${e.path}:${e.stat.size}:${e.stat.mtime}${r?`:${r}`:""}`;return(0,qbr.MD5)(n).toString()}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e){try{let r=this.memoryCache.get(e);if(r)return F("Memory cache hit for file:",e),r.content;let n=this.getCachePath(e);if(await app.vault.adapter.exists(n)){F("File cache hit:",e);let o=await app.vault.adapter.read(n),i,a=o.trim();if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{i=JSON.parse(o)}catch{i=o}else i=o;let s={content:i,timestamp:Date.now()};return this.memoryCache.set(e,s),s.content}return F("Cache miss for file:",e),null}catch(r){return ie("Error reading from file cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCachePath(e),o=Date.now(),i={content:r,timestamp:o};this.memoryCache.set(e,i);let a;typeof r=="string"?a=r:a=JSON.stringify(r,null,2),await app.vault.adapter.write(n,a),F("Cached file content:",e)}catch(n){ie("Error writing to file cache:",n)}}async remove(e){try{this.memoryCache.delete(e);let r=this.getCachePath(e);await app.vault.adapter.exists(r)&&(await app.vault.adapter.remove(r),F("Removed file from cache:",e))}catch(r){ie("Error removing file from cache:",r)}}async clear(){try{if(this.memoryCache.clear(),await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);F("Clearing file cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ie("Error clearing file cache:",e)}}};Xe();Wb();Qe();var Vbr=$(oH()),tEe=require("obsidian"),Hbr=$(YG());oat();var dq=class dq{constructor(){this.cacheDir=".copilot/project-context-cache";this.memoryCache=new Map;this.projectMutexMap=new Map;this.mutexCreationMutex=new nH;this.handleFileEvent=e=>{e instanceof tEe.TFile&&this.debouncedHandleFileChange(e)};this.handleFileChange=async e=>{try{if(e.extension!=="md")return;let n=ee().projectList||[];for(let o of n){let{inclusions:i,exclusions:a}=Zl({inclusions:o.contextSource.inclusions,exclusions:o.contextSource.exclusions,isProject:!0});fu(e,i,a,!0)&&(await this.invalidateMarkdownContext(o),F(`Invalidated markdown context for project ${o.name} due to file change: ${e.path}`))}}catch(r){ie("Error handling file change for project context cache:",r)}};this.debouncedHandleFileChange=(0,Hbr.default)(e=>{this.handleFileChange(e)},dq.DEBOUNCE_DELAY,{leading:!0,trailing:!0});this.vault=app.vault,this.fileCache=ZG.getInstance(),this.initializeEventListeners()}static getInstance(){return dq.instance||(dq.instance=new dq),dq.instance}cleanup(){this.debouncedHandleFileChange.cancel(),this.vault.off("create",this.handleFileEvent),this.vault.off("modify",this.handleFileEvent),this.vault.off("delete",this.handleFileEvent),this.vault.off("rename",this.handleFileEvent),this.projectMutexMap.clear()}initializeEventListeners(){this.vault.on("create",this.handleFileEvent),this.vault.on("modify",this.handleFileEvent),this.vault.on("delete",this.handleFileEvent),this.vault.on("rename",this.handleFileEvent)}async ensureCacheDir(){await this.vault.adapter.exists(this.cacheDir)||(F("Creating project context cache directory:",this.cacheDir),await this.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){return(0,Vbr.MD5)(e.id).toString()}getCachePath(e){return`${this.cacheDir}/${e}.json`}async getOrCreateProjectMutex(e){let r=e.id,n=this.projectMutexMap.get(r);return n||await this.mutexCreationMutex.runExclusive(async()=>{let o=this.projectMutexMap.get(r);if(o)return o;let i=new nH;return this.projectMutexMap.set(r,i),F(`Created new mutex for project: ${e.name} (ID: ${r})`),i})}async get(e){try{let r=this
|
||
|
|
${e.join(`
|
||
|
|
`)}`)}};aA();BC();Xe();Qe();var rfo="https://api.firecrawl.dev/v2/search",nfo="https://api.perplexity.ai/chat/completions",Jbr="https://api.supadata.ai/v1/transcript",ofo=2e3,Wbr=6e4;function Kbr(){let t=ee();switch(t.selfHostSearchProvider){case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function ifo(t,e){let r=Date.now(),n=await fetch(rfo,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!n.ok){let c=await n.text();throw new Error(`Firecrawl search failed (${n.status}): ${c}`)}let i=(await n.json())?.data,a=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],s=[],u=[];for(let c of a){let d=c.title||"Untitled",f=c.description||"",p=c.url||"";s.push(`### ${d}
|
||
|
|
${f}
|
||
|
|
Source: ${p}`),p&&u.push(p)}let l=Date.now()-r;return F(`[selfHostWebSearch] Firecrawl: ${a.length} results in ${l}ms`),{content:s.join(`
|
||
|
|
|
||
|
|
`),citations:u}}async function afo(t,e){let r=await fetch(nfo,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!r.ok){let a=await r.text();throw new Error(`Perplexity Sonar search failed (${r.status}): ${a}`)}let n=await r.json(),o=n?.choices?.[0]?.message?.content??"",i=Array.isArray(n?.citations)?n.citations:[];return{content:o,citations:i}}async function Gbr(t){let e=ee();switch(e.selfHostSearchProvider){case"perplexity":return afo(t,await kn(e.perplexityApiKey));case"firecrawl":default:return ifo(t,await kn(e.firecrawlApiKey))}}async function rEe(t){let e=Date.now(),r=await kn(ee().supadataApiKey),n=`${Jbr}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await fetch(n,{method:"GET",headers:{"x-api-key":r,Accept:"application/json"}});if(o.status===200){let a=await o.json(),s=Date.now()-e;return F(`[selfHostYoutube4llm] transcript received in ${s}ms`),{response:{transcript:a.content||""},elapsed_time_ms:s}}if(o.status===201||o.status===202){let s=(await o.json()).job_id;if(!s)throw new Error("Supadata returned async status but no job_id");return await sfo(s,r,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function sfo(t,e,r){let n=Date.now()+Wbr,o=`${Jbr}/${t}`;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,ofo));let i=await fetch(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let s=await i.json(),u=Date.now()-r;return F(`[selfHostYoutube4llm] async transcript completed in ${u}ms`),{response:{transcript:s.content||""},elapsed_time_ms:u}}if(i.status===202)continue;let a=await i.text();throw ie(`[selfHostYoutube4llm] poll failed (${i.status}): ${a}`),new Error(`Supadata poll failed (${i.status}): ${a}`)}throw new Error(`Supadata transcript timed out after ${Wbr}ms`)}Dt();Xe();id();Qe();var QG=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Xl.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)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){let n=Wr(r);return ie(`Error processing URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processYoutubeUrl(e){try{return{transcript:(Wy()&&ee().supadataApiKey?await rEe(e):await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(r){let n=Wr(r);return ie(`Error processing YouTube URL ${e}: ${n}`),{transcript:"",error:n}}}async processTwitterUrl(e){try{return await this.brevilabsClient.twitter4llm(e)}catch(r){let n=Wr(r);return ie(`Error processing Twitter URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processUrlList(e){let r="",n=[],o={};if(e.length===0)return{urlContext:r,imageUrls:n,processedErrorUrls:o};let i=e.map(async s=>{if(await cA.isImageUrl(s,app.vault))return n.push(s),{type:"image",url:s};if(wNt(s)){let l=this.mentions.get(s);if(!l||l.error){let c=await this.processYoutubeUrl(s);this.mentions.set(s,{type:"youtube",original:s,processed:c.transcript,error:c.error})}return{type:"youtube",data:this.mentions.get(s)}}if(SNt(s)){let l=this.mentions.get(s);if(!l||l.error){let c=await this.processTwitterUrl(s);this.mentions.set(s,{type:"twitter",original:s,processed:c.response,error:c.error})}return{type:"twitter",data:this.mentions.get(s)}}let u=this.mentions.get(s);if(!u||u.error){let l=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:l.response,error:l.error})}return{type:"url",data:this.mentions.get(s)}});return(await Promise.all(i)).forEach(s=>{if(s.type==="image")return;let u=s.data;u&&(u.processed&&(s.type==="youtube"?r+=`
|
||
|
|
|
||
|
|
<youtube_video_context>
|
||
|
|
<url>${u.original}</url>
|
||
|
|
<content>
|
||
|
|
${u.processed}
|
||
|
|
</content>
|
||
|
|
</youtube_video_context>`:s.type==="twitter"?r+=`
|
||
|
|
|
||
|
|
<twitter_content>
|
||
|
|
<url>${u.original}</url>
|
||
|
|
<content>
|
||
|
|
${u.processed}
|
||
|
|
</content>
|
||
|
|
</twitter_content>`:r+=`
|
||
|
|
|
||
|
|
<url_content>
|
||
|
|
<url>${u.original}</url>
|
||
|
|
<content>
|
||
|
|
${u.processed}
|
||
|
|
</content>
|
||
|
|
</url_content>`),u.error&&(o[u.original]=u.error))}),{urlContext:r,imageUrls:n,processedErrorUrls:o}}async processUrls(e){let r=this.extractUrls(e);return this.processUrlList(r)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};Wb();Qe();Xe();var Xbr=$(oH()),nEe=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)||(F("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,Xbr.MD5)(r).toString();return F("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)){F("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return F("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);F("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);F("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)}}};Xe();DG();u0();id();Qe();Xe();Dt();async function Zbr(t,e,r,n){let o=n?.trim();if(o&&t.extension!=="md"&&!(!e||e.startsWith("[Error:")))try{await ql(o);let i=`${o}/${t.basename}.md`;if(await r.adapter.exists(i)){let s=await r.adapter.read(i);if(s&&!s.startsWith(`<!-- source: ${t.path} -->`)){let u=t.path.replace(/\.[^.]+$/,"").replace(/[/\\]/g,"__");if(i=`${o}/${u}.md`,await r.adapter.exists(i)){let l=await r.adapter.read(i);if(l&&!l.startsWith(`<!-- source: ${t.path} -->`)){Ce(`Skipping converted doc output for ${t.path}: collision at ${i}`);return}}}}let a=`<!-- source: ${t.path} -->
|
||
|
|
${e}`;if(await r.adapter.exists(i)&&await r.adapter.read(i)===a)return;await r.adapter.write(i,a),F(`Saved converted doc output: ${i}`)}catch(i){ie(`Failed to save converted doc output for ${t.path}:`,i)}}function ED(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 Ybr(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var t_r=require("obsidian");var Qbr=require("obsidian");var iEe,e_r,oEe=class{constructor(e){this.vault=e;PBe(this,iEe)}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 Qbr.TFile?await this.vault.read(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];z0t(this,iEe,e_r).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:
|
||
|
|
|
||
|
|
`,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
|
||
|
|
`,o}};iEe=new WeakSet,e_r=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"})}};async function fq(t,e,r){let n=ee().convertedDocOutputFolder??"";await Zbr(t,e,r,n)}var aEe=class{constructor(){this.miyoClient=new l0}async parsePdf(e,r){let n=ee();if(!n.enableMiyo||e.extension.toLowerCase()!=="pdf")return null;try{let o=await this.miyoClient.resolveBaseUrl(Mx(n)),i=r.getName(),a=await this.miyoClient.parseDoc(o,i,e.path);return typeof a.text!="string"||a.text.trim().length===0?{error:"Miyo parse-doc returned empty text"}:(F(`[SelfHostPdfParser] Parsed PDF via Miyo: ${e.path}`),{content:a.text})}catch(o){let i=o instanceof Error?o.message:String(o);return Ce(`[SelfHostPdfParser] Failed to parse ${e.path} via Miyo parse-doc: ${i}`),{error:i}}}},Aat=class{constructor(){this.supportedExtensions=["md","base"]}async parseFile(e,r){return await r.read(e)}},sEe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=nEe.getInstance(),this.selfHostPdfParser=new aEe}async parseFile(e,r){try{F("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return F("Using cached PDF content for:",e.path),await fq(e,n.response,r),n.response;let o=ee();if(Wy()&&o.enableMiyo&&e.extension.toLowerCase()==="pdf"){let s=await this.selfHostPdfParser.parsePdf(e,r);if(s&&"content"in s)return await this.pdfCache.set(e,{response:s.content,elapsed_time_ms:0}),await fq(e,s.content,r),s.content;if(s&&"error"in s)return Ce(`[PDFParser] Miyo parse failed for ${e.path}: ${s.error}`),`[Error: Could not extract content from PDF ${e.basename}. ${s.error}]`}let i=await r.readBinary(e);F("Calling pdf4llm API for:",e.path);let a=await this.brevilabsClient.pdf4llm(i);return await this.pdfCache.set(e,a),await fq(e,a.response,r),a.response}catch(n){return ie(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){F("Clearing PDF cache"),await this.pdfCache.clear()}},Nat=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{F("Parsing Canvas file:",e.path);let n=new oEe(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}]`}}},e9=class e9{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=Iw.getInstance(),this.selfHostPdfParser=new aEe,this.currentProject=r}static resetRateLimitNoticeTimer(){e9.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(F(`[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 F(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),await fq(e,n,r),n;if(F(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`),Wy()&&ee().enableMiyo&&e.extension.toLowerCase()==="pdf"){let s=await this.selfHostPdfParser.parsePdf(e,r);if(s&&"content"in s)return await this.projectContextCache.setFileConte
|
||
|
|
|
||
|
|
`)}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),await fq(e,a,r),F(`[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),ED(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-e9.lastRateLimitNoticeTime<6e4)return;e9.lastRateLimitNoticeTime=r;let n=Ybr(e);new t_r.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(){F("Cache clearing is now handled at the project level")}};e9.lastRateLimitNoticeTime=0;var lae=e9,pq=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.registerParser(new Aat),this.registerParser(new lae(e,o)),n||this.registerParser(new sEe(e)),this.registerParser(new Nat)}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 sEe&&await e.clearCache()}};Dt();t1();var e3=require("obsidian");aA();na();rd();gr();gr();Xe();Dt();var PD=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a,s,u){if((e||u?.wasTruncated)&&!(n.signal.aborted&&n.signal.reason==="new-chat")){let p=r.contextEnvelope?.layers.find(g=>g.id==="L5_USER")?.text||r.originalMessage||r.message,m=s||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let y={message:e||(u?.wasTruncated?"_[The response was truncated before any content could be generated. Try increasing the max tokens limit.]_":""),sender:ow,isVisible:!0,timestamp:vg(new Date),sources:a,responseMetadata:u};o(y),i("")}else n.signal.reason==="new-chat"&&i("");let c=this.chainManager.memoryManager.getMemory().chatHistory.messages;F(`Chat memory updated:
|
||
|
|
`,{turns:Array.isArray(c)?c.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(Fat(),r_r)),m=f(e).segments.map(y=>y.type==="text"?y.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;F(`Final AI response (truncated):
|
||
|
|
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;F(`Final AI response (truncated):
|
||
|
|
`,p)}return e}async handleError(e,r){let n=Wr(e);ie("Error during LLM invocation:",n);let o=e?.response?.data?.error||n,i=o?.code||n,a="";e?.message?.includes("Invalid license key")?a="Invalid Copilot Plus license key. Please check your license key in settings.":i==="model_not_found"?a="You do not have access to this model or the model does not exist, please check with your API provider.":a=`${i}`,ie(o),r(this.enhancedErrorMsg(a,n,e))}enhancedErrorMsg(e,r,n){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(n,r)&&(e=`Something went wrong. Please check if you have set your API key.
|
||
|
|
Path: Settings > copilot plugin > Basic Tab > Set Keys.
|
||
|
|
Or check model config
|
||
|
|
Error Details: `+e),e}isAuthenticationError(e,r){let n=e?.response,o=n?.data?.error??e?.error,i=n?.status??o?.status,a=typeof i=="string"?Number.parseInt(i,10):i,s=typeof o=="object"&&o!==null?o:void 0,u=(typeof s?.message=="string"?s.message:r).toLowerCase(),l=typeof s?.code=="string"?s.code.toLowerCase():"",c=typeof s?.type=="string"?s.type.toLowerCase():"";return a===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>u.includes(f)||l.includes(f)||c.includes(f))}};gr();Xe();var dA=class{static convert(e,r={}){let{includeSystemMessage:n=!0,mergeUserContent:o=!0,debug:i=!1}=r,a=[],s=e.layers.find(f=>f.id==="L1_SYSTEM"),u=e.layers.find(f=>f.id==="L2_PREVIOUS"),l=e.layers.find(f=>f.id==="L3_TURN"),c=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(n&&s&&s.text){let f=[s.text];u&&u.text&&(f.push(`
|
||
|
|
## Context Library
|
||
|
|
|
||
|
|
The following notes are available for reference:
|
||
|
|
|
||
|
|
`+u.text),i&&F("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),a.push({role:"system",content:f.join(`
|
||
|
|
`)}),i&&F("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(c&&c.text&&i&&F("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(l&&l.segments.length>0&&u){let p=new Set(u.segments.map(y=>y.id)),m=[],h=[];for(let y of l.segments)p.has(y.id)?m.push(y.id):h.push(y);if(m.length>0||h.length>0){let y=[];m.length>0&&y.push(`Context attached to this message:
|
||
|
|
`+m.map(g=>`- ${g}`).join(`
|
||
|
|
`)+`
|
||
|
|
|
||
|
|
Find them in the Context Library in the system prompt above.`),h.length>0&&y.push(h.map(g=>g.content).join(`
|
||
|
|
`)),f.push(y.join(`
|
||
|
|
|
||
|
|
`)),i&&F(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else l&&l.text&&(f.push(l.text),i&&F("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
|
||
|
|
|
||
|
|
[User query]:`),d&&d.text&&(f.push(d.text),i&&F("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&a.push({role:"user",content:f.join(`
|
||
|
|
|
||
|
|
`)})}else l&&l.text&&a.push({role:"user",content:l.text}),d&&d.text&&a.push({role:"user",content:d.text});return i&&(F(`[LayerToMessagesConverter] Converted envelope to ${a.length} messages`),a.forEach((f,p)=>{let m=f.content.substring(0,100);F(` Message ${p+1} [${f.role}]: ${m}...`)})),a}static extractUserContent(e){let r=e.layers.find(i=>i.id==="L3_TURN"),n=e.layers.find(i=>i.id==="L5_USER"),o=[];return r&&r.text&&o.push(r.text),n&&n.text&&o.push(n.text),o.join(`
|
||
|
|
|
||
|
|
`)}static extractFullContext(e){let r=e.layers.find(a=>a.id==="L2_PREVIOUS"),n=e.layers.find(a=>a.id==="L3_TURN"),o=e.layers.find(a=>a.id==="L5_USER"),i=[];return r&&r.text&&i.push(r.text),n&&n.text&&i.push(n.text),o&&o.text&&i.push(o.text),i.join(`
|
||
|
|
|
||
|
|
`)}static extractSystemMessage(e){return e.layers.find(n=>n.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}};Xe();Qe();Dt();Xe();function kat(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=mfo(r);n&&e.push({role:n,content:r.content})}}return e}function mfo(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function hfo(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>r.type==="text").map(r=>r.text||"").join(" ")||"[Image content]":String(t||"")}function n_r(t){return t.map(e=>({role:e.role,content:hfo(e.content)}))}async function mq(t,e){let n=(await t.loadMemoryVariables({})).history||[],o=n.length?kat(n):[];for(let u of o)e.push({role:u.role,content:u.content});let i=0;for(let u of e)typeof u.content=="string"&&u.role==="system"&&(i+=u.content.length);let a=0;for(let u of o)typeof u.content=="string"&&(a+=u.content.length);let s=i+a;return s>2e6&&F("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(a/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(s/4e3)}k tokens`}),o}Xe();var Uc=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)}getCopilotCommandMappings(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.copilotCommands;if(n)for(let o of n){let i=o.toLowerCase();e.has(i)||e.set(i,r)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}getToolDefinition(e){return this.tools.get(e)}clear(){this.tools.clear()}};var t9=null;function gfo(t){let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return typeof n=="bigint"?n.toString():n},2)}function yfo(t,e){let r=[];e&&(r.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),r.push(""));let n=Uc.getInstance(),o=new Set(n.getAllTools().map(c=>c.tool.name)),i=c=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(c))!==null;){let m=p[1],h=p[2];if(o.has(m)){let y=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:y})}}return d},a=c=>typeof c.content=="string"?c.content:Array.isArray(c.content)?c.content.filter(f=>f.type==="text").map(f=>f.text).join(`
|
||
|
|
`):"",s=Array.isArray(t)?t:[],u=0;for(let c=0;c<s.length;c++){let d=s[c],f=a(d);if(d.role==="system"){r.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),r.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);r.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let y=f.indexOf(p.text)+p.text.length,g=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(r.push(g),r.push(""),m&&m.text){let w=m.hash.substring(0,8);r.push(`\u{1F512} L2_PREVIOUS (${w}) [CACHEABLE]`);let T=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;r.push(T),r.push("")}let b=f.substring(y),_=i(b);if(_.length>0){r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let w of _)r.push(`\u{1F4E6} TOOL: ${w.tool} (turn-specific RAG)`),r.push(w.preview),r.push("")}}else{let h=i(f);if(h.length>0){let y=f.match(/<(\w+)>/);if(y){let g=f.substring(0,y.index);if(g.trim()){let b=g.length>300?g.substring(0,300)+"...[truncated]":g;r.push(b),r.push("")}}r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let g of h)r.push(`\u{1F4E6} TOOL: ${g.tool}`),r.push(g.preview),r.push("")}else{let y=f.length>300?f.substring(0,300)+"...[truncated]":f;r.push(y),r.push("")}}}else(d.role==="user"||d.role==="assistant")&&c<s.length-1&&u++}u>0&&(r.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),r.push(""),r.push(`${u} message(s)`),r.push(""));let l=s[s.length-1];if(l&&l.role==="user"){r.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),r.push("");let c=a(l),d=i(c);if(d.length>0){r.push("--- PER-TURN TOOL RESULTS ---"),r.push("");for(let m of d)r.push(`\u{1F4E6} TOOL: ${m.tool}`),r.push(m.preview),r.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&c.includes(f.text)){let m=f.hash.substring(0,8);r.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;r.push(h),r.push("")}if(p&&p.text&&c.includes(p.text)){let m=p.hash.substring(0,8);r.push(`\u26A1 L5_USER (${m})`),r.push(p.text),r.push("")}}return r.join(`
|
||
|
|
`)}function hq(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{t9={timestamp:new Date().toISOString(),modelName:r,serializedMessages:gfo(e),messagesArray:e,contextEnvelope:n}}catch{t9={timestamp:new Date().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}function r9(){t9=null}async function uEe(){if(!t9)return;let{timestamp:t,modelName:e,serializedMessages:r,messagesArray:n,contextEnvelope:o}=t9,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",r,"```",""],a=yfo(n,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(a),i.push("```"),i.push(""),xge(i),t9=null}function o_r(t){let e=t.response_metadata||{};return e.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}function i_r(t){let e=t.response_metadata||{};return e.tokenUsage?{inputTokens:e.tokenUsage.promptTokens,outputTokens:e.tokenUsage.completionTokens,totalTokens:e.tokenUsage.totalTokens}:e.usage?{inputTokens:e.usage.input_tokens||e.usage.inputTokens||e.usage.inputTokenCount||e.usage.prompt_tokens,outputTokens:e.usage.output_tokens||e.usage.outputTokens||e.usage.outputTokenCount||e.usage.completion_tokens,totalTokens:e.usage.total_tokens||e.usage.totalTokens||(e.usage.input_tokens||e.usage.inputTokenCount||0)+(e.usage.output_tokens||e.usage.outputTokenCount||0)}:t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function bfo(t){return`<errorChunk>${t}</errorChunk>`}function lEe(t,e){let r=bfo(t);return e?`${e}
|
||
|
|
${r}`:`
|
||
|
|
${r}`}ra();Xe();function cEe(t,e,r){return new Kv({content:r,tool_call_id:t,name:e})}function cae(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function a_r(t,e){let r=e.index??0,n=t.get(r)||{name:"",args:""};e.id&&(n.id=e.id);let o=e.name??e.functionCall?.name;o&&(n.name+=o),e.args&&(n.args+=e.args),t.set(r,n)}function dEe(t){let e=[];for(let r of t.values()){if(!r.name)continue;let n={};if(r.args)try{n=JSON.parse(r.args)}catch{ie(`[ToolCall] Failed to parse args for tool "${r.name}": ${r.args}`),n={}}e.push({id:r.id||cae(),name:r.name,args:n})}return e}function s_r(t,e){return new uo({content:t,tool_calls:e.map(r=>({id:r.id,name:r.name,args:r.args,type:"tool_call"}))})}Xe();var _fo=["<|im_end|>","<|im_start|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>","<end_of_turn>","<start_of_turn>","<|end|>","<|assistant|>","<|user|>","<|system|>","</s>","[INST]","[/INST]","<|endoftext|>","<|end\u2581of\u2581sentence|>","<|END_OF_TURN_TOKEN|>","<|START_OF_TURN_TOKEN|>"],vfo=new RegExp(_fo.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");function qat(t){return t.replace(vfo,"")}var iv=class{constructor(e,r=!1){this.updateCurrentAiMessage=e;this.excludeThinking=r;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.excludedThinkBlockStart=-1;this.toolCallChunks=new Map;this.accumulatedToolCalls=[];F(`[ThinkBlockStreamer] Created with excludeThinking=${r}`)}handleTextLevelThinkTags(){if(this.excludeThinking){this.handleExcludedThinkTags();return}let e=this.fullResponse.includes("</think>"),r=this.fullResponse.includes("<think>");e&&!r&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,Ce("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}handleExcludedThinkTags(){if(this.excludedThinkBlockStart>=0){let n=this.fullResponse.indexOf("</think>",this.excludedThinkBlockStart);if(n!==-1){let o=this.fullResponse.substring(0,this.excludedThinkBlockStart),i=this.fullResponse.substring(n+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,this.excludedThinkBlockStart);return}let e=this.fullResponse.indexOf("<think>");if(e!==-1){this.excludedThinkBlockStart=e;let n=this.fullResponse.indexOf("</think>",e);if(n!==-1){let o=this.fullResponse.substring(0,e),i=this.fullResponse.substring(n+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,e);return}let r=this.fullResponse.indexOf("</think>");r!==-1&&(this.fullResponse=this.fullResponse.substring(r+8).trimStart())}handleClaudeChunk(e){let r="",n=!1;for(let o of e)switch(o.type){case"text":r+=o.text;break;case"thinking":if(n=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
|
||
|
|
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return r&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),r&&(this.fullResponse+=qat(r)),n}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=qat(e.content)),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
|
||
|
|
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
|
||
|
|
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){let r=e.tool_call_chunks;if(!(!r||!Array.isArray(r)))for(let n of r){let o=n.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};n.id&&(i.id=n.id),n.name&&(i.name+=n.name),n.args&&(i.args+=n.args),this.toolCallChunks.set(o,i)}}processChunk(e){o_r(e).wasTruncated&&(this.wasTruncated=!0);let n=i_r(e);n&&(this.tokenUsage=n),this.handleToolCallChunks(e);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=lEe(e)}getToolCalls(){return this.accumulatedToolCalls.length>0?this.accumulatedToolCalls:dEe(this.toolCallChunks)}hasToolCalls(){return this.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){let e=this.getToolCalls();return s_r(this.fullResponse,e)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};na();var dae=class extends PD{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");F("[LLMChainRunner] Using envelope-based context");let r=dA.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),n=[],o=r.find(s=>s.role==="system");o&&n.push(o);let i=this.chainManager.memoryManager.getMemory();await mq(i,n);let a=r.find(s=>s.role==="user");if(a)if(e.content&&Array.isArray(e.content)){let s=e.content.map(u=>u.type==="text"?{...u,text:a.content}:u);n.push({role:"user",content:s})}else n.push(a);return n}async run(e,r,n,o,i){let a=ee(),s=j_(),u=!1;try{u=!PS(s,a.activeModels).capabilities?.includes("reasoning")}catch(f){F("Could not determine model capabilities, defaulting to include thinking blocks",f)}let l=new iv(n,u);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;hq({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
|
||
|
|
`,f);let h=await Ib(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));for await(let y of h){if(r.signal.aborted){F("Stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(y)}}catch(f){f.name==="AbortError"||r.signal.aborted?F("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(f,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(await this.handleResponse(c.content,e,r,o,n,void 0,void 0,d),c.content)}};gr();Dt();async function fEe(t,e){let r=`Given the following conversation and a follow up question,
|
||
|
|
summarize the conversation as context and keep the follow up question unchanged, in its original language.
|
||
|
|
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
|
||
|
|
If it is related, then combine the summary and the follow up question to construct a standalone question.
|
||
|
|
Make sure to keep any [[]] wrapped note titles in the question unchanged.
|
||
|
|
If there's nothing in the chat history, just return the follow up question.
|
||
|
|
|
||
|
|
Chat History:
|
||
|
|
{chat_history}
|
||
|
|
Follow Up Input: {question}
|
||
|
|
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
|
||
|
|
`);return await Ib(async()=>{let o=await Vg.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0),i="",a=await o.stream([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);for await(let u of a)i+=tF(u.content);let s=lte(i);return Nge(s)})}Xe();Xe();id();u0();Qe();Xe();Dt();OD();o9();var pEe=class extends fA{constructor(r,n,o){super();this.lc_namespace=["self_host_retriever"];this.app=r,this.backend=n,this.options={...o,minSimilarityScore:o.minSimilarityScore??.01,salientTerms:o.salientTerms??[],returnAll:o.returnAll??!1}}async getRelevantDocuments(r,n){try{if(!await this.backend.isAvailable())return Ce("SelfHostRetriever: Backend is not available"),[];let a=ES(r,this.app.vault).map(f=>f.basename),s=[...new Set([...this.options.salientTerms||[],...a])],u=this.buildFilter(),l=this.options.returnAll?100:this.options.maxK,c=await this.backend.search(r,{limit:l,minScore:this.options.minSimilarityScore,filter:u});F(`SelfHostRetriever: Found ${c.length} results for query "${r.substring(0,50)}..."`);let d=this.convertToDocuments(c);return s.length>0?this.boostBySalientTerms(d,s):d}catch(o){return Ce(`SelfHostRetriever: Search failed: ${o}`),[]}}buildFilter(){let r={};return this.options.timeRange&&(r.mtime={gte:this.options.timeRange.startTime,lte:this.options.timeRange.endTime}),this.options.tagTerms&&this.options.tagTerms.length>0&&(r.tags={containsAny:this.options.tagTerms}),Object.keys(r).length>0?r:void 0}convertToDocuments(r){return r.map(n=>new Yl({pageContent:n.content,metadata:{...n.metadata,score:n.score,rerank_score:n.score,id:n.id,source:"self_host"}}))}boostBySalientTerms(r,n){return r.map(a=>{let s=a.pageContent.toLowerCase(),u=(a.metadata?.title||"").toLowerCase();if(n.some(c=>s.includes(c.toLowerCase())||u.includes(c.toLowerCase()))){let c=(a.metadata?.score||0)*1.1;return new Yl({pageContent:a.pageContent,metadata:{...a.metadata,score:c,rerank_score:c,salientBoost:!0}})}return a}).sort((a,s)=>(s.metadata?.score||0)-(a.metadata?.score||0))}getBackend(){return this.backend}};OD();o9();Xe();DG();u0();Qe();cH();var EEe=class extends fA{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["miyo_semantic_retriever"];this.client=new l0,this.returnAll=!!n.returnAll,this.maxK=Math.max(1,n.maxK),this.minSimilarityScore=n.minSimilarityScore??.1}async getRelevantDocuments(r,n){let o=await this.searchMiyo(r),i=this.deduplicateResults(o);return ee().debug&&this.logDebugInfo(r,o,i),i}async searchMiyo(r){try{let n=await this.client.resolveBaseUrl(Mx(ee())),o=this.returnAll?Pl:this.maxK,i=this.buildSearchFilters();ee().debug&&F("MiyoSemanticRetriever: search params:",{baseUrl:n,limit:o,maxK:this.maxK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:i});let a=ee().miyoSearchAll?void 0:tq(this.app),u=(await this.client.search(n,a,r,o,i)).results||[],l=u.filter(c=>this.isScoreAboveThreshold(c));return ee().debug&&F(`MiyoSemanticRetriever: received ${u.length} results, ${l.length} after threshold`),l.map(c=>this.toDocument(c))}catch(n){return Ce(`MiyoSemanticRetriever: search failed: ${n}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:r,endTime:n}=this.options.timeRange;return[{field:"mtime",gte:r,lte:n}]}toDocument(r){let n=NG(this.app,r.path),o=r.metadata??{},i=o.chunkId||(r.chunk_index!==void 0?`${n}#${r.chunk_index}`:void 0),a=typeof r.score=="number"?r.score.toFixed(2):"?";return new Yl({pageContent:r.chunk_text??"",metadata:{...o,score:r.score,explanation:`miyo ${a}`,path:n,mtime:r.mtime,ctime:r.ctime,title:r.title??"",id:r.id,embeddingModel:r.embedding_model,tags:r.tags??[],extension:r.extension,created_at:r.created_at,nchars:r.nchars,chunkId:i}})}isScoreAboveThreshold(r){let n=r.score;return typeof n!="number"||Number.isNaN(n)?!0:n>=this.minSimilarityScore}deduplicateResults(r){let n=new Map,o=i=>{let a=this.getDocumentKey(i);n.has(a)||n.set(a,i)};return r.forEach(o),ee().debug&&n.size!==r.length&&F(`MiyoSemanticRetriever: deduplicated semantic results from ${r.length} to ${n.size}`),Array.from(n.va
|
||
|
|
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
|
||
|
|
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
|
||
|
|
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
|
||
|
|
4. DO NOT cite for:
|
||
|
|
- General knowledge or common facts
|
||
|
|
- Your own analysis or synthesis
|
||
|
|
- Transitional or concluding statements
|
||
|
|
- Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
|
||
|
|
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
|
||
|
|
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
|
||
|
|
7. Place citations immediately after the specific claim: "The study found X [^1]" not "The study found X. [^1]"
|
||
|
|
8. Do not reuse any bracketed numbers that appear inside the source content itself
|
||
|
|
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
|
||
|
|
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,ZQo=`WEB CITATION RULES:
|
||
|
|
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
|
||
|
|
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
|
||
|
|
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
|
||
|
|
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
|
||
|
|
|
||
|
|
IMPORTANT: Each source definition must follow this exact pattern:
|
||
|
|
- Start with [^n]: (where n is the citation number)
|
||
|
|
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
|
||
|
|
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
|
||
|
|
- DO NOT write long descriptions - keep titles concise`;function Dzr(t,e=!0){return e?`
|
||
|
|
|
||
|
|
<guidance>
|
||
|
|
${Nzr}
|
||
|
|
|
||
|
|
IMAGE INCLUSION:
|
||
|
|
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
|
||
|
|
|
||
|
|
Source Catalog (for reference only):
|
||
|
|
${t.join(`
|
||
|
|
`)}
|
||
|
|
</guidance>`:`
|
||
|
|
|
||
|
|
<guidance>
|
||
|
|
IMAGE INCLUSION:
|
||
|
|
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
|
||
|
|
|
||
|
|
Source Catalog (for reference only):
|
||
|
|
${t.join(`
|
||
|
|
`)}
|
||
|
|
</guidance>`}function jzr(t,e=!0){return e?`
|
||
|
|
|
||
|
|
${Nzr}
|
||
|
|
|
||
|
|
Source Catalog (for reference only):
|
||
|
|
${t}`:""}function $zr(t){return t?"REMINDER: End your response with an '#### Sources' section listing each cited source as [^n]: [[Title]], numbered sequentially from [^1].":null}var YQo=20;function uDe(t,e,r=!0){if(!r||!e?.length||!t)return t||"";if(QQo(t))return t;let n=e.slice(0,YQo).map((o,i)=>{let a=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${a}]]`}).join(`
|
||
|
|
`);return`${t}
|
||
|
|
|
||
|
|
#### Sources:
|
||
|
|
|
||
|
|
${n}`}function hX(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function QQo(t){let e=t||"",r=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),n=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return r||n||o||i}function Lzr(t){let e=t||"";return/\[\^\d+\]/.test(e)}function Fzr(t=!0){return t?`
|
||
|
|
|
||
|
|
${ZQo}`:""}function eei(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,r=t.match(e);if(r)return{mainContent:r[1],sourcesBlock:(r[2]||"").trim()};let n=t.match(/([\s\S]*?)\n+---+\s*\n+([\s\S]*)$/);if(n){let i=(n[2]||"").trim();if(i.length>0&&i.split(`
|
||
|
|
`).every(s=>!s.trim()||/^\[\^\d+\]:/.test(s.trim())))return{mainContent:n[1],sourcesBlock:i}}let o=t.match(/([\s\S]*?)\n{2,}(\[\^\d+\]:[\s\S]*)$/);if(o){let i=(o[2]||"").trim();if(i.split(`
|
||
|
|
`).every(s=>!s.trim()||/^\[\^\d+\]:/.test(s.trim())))return{mainContent:o[1],sourcesBlock:i}}return null}function tei(t){return t.includes(`
|
||
|
|
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
|
||
|
|
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
|
||
|
|
$1. `),t=t.trim()),t}function rei(t){return t.split(`
|
||
|
|
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function nei(t,e){let r=new Map,n=new Set,o=[],i=/\[\^(\d+)\]/g,a;for(;(a=i.exec(t))!==null;){let s=parseInt(a[1],10);n.has(s)||(n.add(s),o.push(s))}if(o.length>0)o.forEach((s,u)=>r.set(s,u+1));else{let s=1;for(let u of e){let l=u.match(/^\[\^(\d+)\]:/);if(l){let c=parseInt(l[1],10);r.has(c)||r.set(c,s++)}}}return r}function oei(t,e){let r=t,n;do n=!1,r=r.replace(/\[\^(\d+)\]/g,(o,i)=>{let a=parseInt(i,10),u=`[${e.get(a)??a}]`;return u!==o&&(n=!0),u}),r=r.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let s=`[${i.split(",").map(u=>{let l=u.trim().replace(/^\^/,""),c=parseInt(l,10);return e.get(c)??c}).sort((u,l)=>u-l).map(u=>u.toString()).join(", ")}]`;return s!==o&&(n=!0),s});while(n);return r=r.replace(/\[(\d+)\]\./g,"[$1]"),r}function iei(t,e){let r=[];return t.split(`
|
||
|
|
`).forEach(n=>{let o=n.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),a=e.get(i)??i,s=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),u=o[2].match(/\[\[(.*?)\]\]/),l;if(s)l=`<a href="${s[2]}">${s[1]}</a>`;else if(u)l=`[[${u[1]}]]`;else{let c=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(c){let d=c[1].trim();l=`<a href="${c[2].trim()}">${d}</a>`}else l=o[2].replace(/\s*\([^)]*\)\s*$/,"")}r[a-1]=l}),r}function aei(t){let e=[],r=new Set,n=new Map;return t.forEach((o,i)=>{if(!o)return;let a=o.match(/\[\[(.*?)\]\]/),s=a?a[1].toLowerCase():o.toLowerCase();if(!r.has(s))r.add(s),e.push(o),n.set(i+1,e.length);else{let u=e.findIndex(l=>{let c=l.match(/\[\[(.*?)\]\]/);return(c?c[1].toLowerCase():l.toLowerCase())===s});u>=0&&n.set(i+1,u+1)}}),{uniqueItems:e,consolidationMap:n}}function sei(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,n)=>{let o=n.split(/\s*,\s*/),i=new Set,a=[];for(let s of o){let u=e.get(parseInt(s,10))||parseInt(s,10);i.has(u)||(i.add(u),a.push(u))}return`[${a.join(", ")}]`})}function uei(t){let e=t,r;do r=e,e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?:\s*(?:and|,)\s*|\s*)\[(\d+(?:\s*,\s*\d+)*)\]/g,(n,o,i)=>{let a=new Set(o.split(/\s*,\s*/).map(u=>u.trim()));return i.split(/\s*,\s*/).map(u=>u.trim()).every(u=>a.has(u))?`[${[...a].join(", ")}]`:n});while(e!==r);return e}function lei(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function cei(t){return t!=null}function dei(t){let e=t.split(`
|
||
|
|
`),r=[];return e.forEach(n=>{let o=n.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let a=i.match(/\[([^\]]+)\]\(([^)]+)\)/),s=i.match(/\[\[(.*?)\]\]/),u;a?u=`<a href="${a[2]}">${a[1]}</a>`:s?u=`[[${s[1]}]]`:u=lei(i),r.push({index:r.length+1,html:u})}),r}function Azr(t,e){let r=e.filter(o=>o.html.trim().length>0);if(r.length===0)return t;let n=r.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
|
||
|
|
`);return`${t}
|
||
|
|
|
||
|
|
<br/>
|
||
|
|
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
|
||
|
|
<ul class="copilot-sources__list">
|
||
|
|
${n}
|
||
|
|
</ul>
|
||
|
|
</details>`}function fei(t){return t.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,'<span class="copilot-citation-ref">[$1]</span>')}function kzr(t,e=!0){if(!e)return t;let r=eei(t);if(!r)return t;let{mainContent:n,sourcesBlock:o}=r;o=tei(o);let i=rei(o);if(i.length===0){let d=dei(o);return Azr(n,d)}let a=nei(n,i);n=oei(n,a);let s=iei(o,a),{uniqueItems:u,consolidationMap:l}=aei(s);l.size>0&&(n=sei(n,l),n=uei(n),s=u),n=fei(n);let c=s.map((d,f)=>d?{index:f+1,html:d}:null).filter(cei);return Azr(n,c)}function lDe(t){return t.map(e=>{let r=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}na();var nle=class extends PD{async run(e,r,n,o,i){let a=ee(),s=j_(),u=!1;try{u=!PS(s,a.activeModels).capabilities?.includes("reasoning")}catch(p){F("Could not determine model capabilities, defaulting to include thinking blocks",p)}let l=new iv(n,u);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(oe=>oe.id==="L5_USER")?.text||e.message,y=this.extractTagTerms(h);F("[VaultQA] Extracted tags before condensing:",y);let g=this.chainManager.memoryManager.getMemory(),b=await g.loadMemoryVariables({}),_=Mge(b),w=h;_.length>0&&(F("[VaultQA] Condensing query with chat history for better retrieval"),w=await fEe(h,_),F("[VaultQA] Standalone question:",w));let T=ee(),O=y.length>0,P=await new IB(app,{salientTerms:O?[...y]:[],maxK:T.maxSourceChunks,returnAll:O}).getRelevantDocuments(w),R=Qx.isMiyoActive(),I=await Qx.createRetriever(app,{minSimilarityScore:.01,maxK:T.maxSourceChunks,salientTerms:O?[...y]:[],tagTerms:y,returnAll:O},R?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),A=I.retriever;F(`VaultQA: Using ${I.type} retriever - ${I.reason}`);let B=await A.getRelevantDocuments(w),{filterResults:k,searchResults:q}=mX(P,B),Z=[...k,...q],V=Z.length>T.maxSourceChunks,Y=Z.slice(0,T.maxSourceChunks);this.chainManager.storeRetrieverDocuments(Y);let X=Y.map(oe=>{let Q=oe.metadata?.title||"Untitled",de=oe.metadata?.path||Q;return`<${e3e}>
|
||
|
|
<title>${Q}</title>
|
||
|
|
<path>${de}</path>
|
||
|
|
<content>
|
||
|
|
${hX(oe.pageContent)}
|
||
|
|
</content>
|
||
|
|
</${e3e}>`}).join(`
|
||
|
|
|
||
|
|
`),W=[],re=this.chainManager.chatModelManager.getChatModel(),ue=Y.slice(0,Math.max(5,Math.min(20,Y.length))).map(oe=>({title:oe.metadata?.title||oe.metadata?.path||"Untitled",path:oe.metadata?.path||oe.metadata?.title||""})),le=lDe(ue).join(`
|
||
|
|
`),L=V?`
|
||
|
|
|
||
|
|
IMPORTANT: The retrieval limit of ${T.maxSourceChunks} documents was reached. ${Z.length-T.maxSourceChunks} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",J=`
|
||
|
|
|
||
|
|
Answer the question based only on the following context:
|
||
|
|
`+X+jzr(le,T.enableInlineCitations)+L;F("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let ne=dA.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),D=ne.find(oe=>oe.role==="system");D&&W.push({role:ute(re),content:D.content}),await mq(g,W);let N=ne.find(oe=>oe.role==="user");if(N){let oe=J+`
|
||
|
|
|
||
|
|
`+N.content;if(e.content&&Array.isArray(e.content)){let Q=e.content.map(de=>de.type==="text"?{...de,text:oe}:de);W.push({role:"user",content:Q})}else W.push({role:"user",content:oe})}let z=re?.modelName;hq({messages:W,modelName:z,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
|
||
|
|
`,W);let H=await Ib(()=>this.chainManager.chatModelManager.getChatModel().stream(W,{signal:r.signal}));for await(let oe of H){if(r.signal.aborted){F("VaultQA stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(oe)}}catch(p){p.name==="AbortError"||r.signal.aborted?F("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(p,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};if(r.signal.aborted&&r.signal.reason==="new-chat")return n(""),"";let f=this.addSourcestoResponse(c.content);return await this.handleResponse(f,e,r,o,n,void 0,void 0,d),f}addSourcestoResponse(e){let r=ee();if(!Lzr(e))return e;let n=this.chainManager.getRetrievedDocuments(),o=_Nt(n).map(i=>({title:i}));return uDe(e,o,r.enableInlineCitations)}extractTagTerms(e){return a9(e)}};var gX=["@vault","@websearch","@composer","@memory"];gr();Xe();id();Qe();Qe();gr();Xe();LC();LC();Qe();var Ww=QL(),AB=yc([]),cmt=yc(""),qzr=yc(!1);function cDe(){return I_(AB,{store:Ww})}function Bzr(){return e1(cmt,{store:Ww})}function yX(){return Ww.get(AB)}function kW(){return Ww.get(cmt)}function dDe(t){Ww.set(AB,t)}function qW(t){let e=Ww.get(AB),r=e.findIndex(n=>n.title===t.title);if(r!==-1){let n=[...e];n[r]=t,Ww.set(AB,n)}else Ww.set(AB,[...e,t])}function bX(t){let e=Ww.get(AB);Ww.set(AB,e.filter(r=>r.title!==t))}function NB(t){Ww.set(cmt,t)}function ole(t){Ww.set(qzr,t)}function ile(){return Ww.get(qzr)}var dmt=new Set;function DB(t){dmt.add(t)}function jB(t){dmt.delete(t)}function y$(t){return dmt.has(t)}function fDe(){return ee().defaultSystemPromptTitle}function Uzr(){let t=yX(),e=kW();if(e){let n=t.find(o=>o.title===e);if(n)return n.content}let r=fDe();if(r){let n=t.find(o=>o.title===r);if(n)return n.content}return""}function zzr(){let t=fDe();NB(t)}function fmt(){ole(!1),NB("")}function pDe(){return Uzr()||ee()?.userSystemPrompt||""}function b$(){let t=pDe();if(ile())return t;let r=RNt;return t?`${r}
|
||
|
|
<user_custom_instructions>
|
||
|
|
${t}
|
||
|
|
</user_custom_instructions>`:r}async function _$(t){let e=b$();if(!t)return F("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let r=await t.getUserMemoryPrompt();return r?`${r}
|
||
|
|
${e}`:e}var _X=require("obsidian");zr();Xe();Qe();function eT(){}eT.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={});var a=this;function s(w){return w=a.postProcess(w,o),i?(setTimeout(function(){i(w)},0),!0):w}e=this.castInput(e,o),r=this.castInput(r,o),e=this.removeEmpty(this.tokenize(e,o)),r=this.removeEmpty(this.tokenize(r,o));var u=r.length,l=e.length,c=1,d=u+l;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var f=(n=o.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+f,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=u)return s(Vzr(a,m[0].lastComponent,r,e,a.useLongestToken));var y=-1/0,g=1/0;function b(){for(var w=Math.max(y,-c);w<=Math.min(g,c);w+=2){var T=void 0,O=m[w-1],E=m[w+1];O&&(m[w-1]=void 0);var P=!1;if(E){var R=E.oldPos-w;P=E&&0<=R&&R<u}var I=O&&O.oldPos+1<l;if(!P&&!I){m[w]=void 0;continue}if(!I||P&&O.oldPos<E.oldPos?T=a.addToPath(E,!0,!1,0,o):T=a.addToPath(O,!1,!0,1,o),h=a.extractCommon(T,r,e,w,o),T.oldPos+1>=l&&h+1>=u)return s(Vzr(a,T.lastComponent,r,e,a.useLongestToken));m[w]=T,T.oldPos+1>=l&&(g=Math.min(g,w-1)),h+1>=u&&(y=Math.max(y,w+1))}c++}if(i)(function w(){setTimeout(function(){if(c>d||Date.now()>p)return i();b()||w()},0)})();else for(;c<=d&&Date.now()<=p;){var _=b();if(_)return _}},addToPath:function(e,r,n,o,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===r&&a.removed===n?{oldPos:e.oldPos+o,lastComponent:{count:a.count+1,added:r,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:r,removed:n,previousComponent:a}}},extractCommon:function(e,r,n,o,i){for(var a=r.length,s=n.length,u=e.oldPos,l=u-o,c=0;l+1<a&&u+1<s&&this.equals(n[u+1],r[l+1],i);)l++,u++,c++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!i.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=u,l},equals:function(e,r,n){return n.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join("")},postProcess:function(e){return e}};function Vzr(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,m){var h=n[c+m];return h.length>p.length?h: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}var zps=new eT;function Hzr(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 Wzr(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 pmt(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 mmt(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 ale(t,e){return pmt(t,e,"")}function mDe(t,e){return mmt(t,e,"")}function Jzr(t,e){return e.slice(0,pei(t,e))}function pei(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}var hDe="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\
|
||
|
|
`));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};bDe.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
||
|
|
`))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
|
||
|
|
`))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
||
|
|
`)&&(t=t.slice(0,-1)),e.endsWith(`
|
||
|
|
`)&&(e=e.slice(0,-1))),eT.prototype.equals.call(this,t,e,r)};function Gzr(t,e,r){var n=gei(r,{ignoreWhitespace:!0});return bDe.diff(t,e,n)}var yei=new eT;yei.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var bei=new eT;bei.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function hmt(t){"@babel/helpers - typeof";return hmt=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},hmt(t)}var sle=new eT;sle.useLongestToken=!0;sle.tokenize=bDe.tokenize;sle.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(gmt(t,null,null,o),o," ")};sle.equals=function(t,e,r){return eT.prototype.equals.call(sle,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function gmt(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]=gmt(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),hmt(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]=gmt(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var gDe=new eT;gDe.tokenize=function(t){return t.slice()};gDe.join=gDe.removeEmpty=function(t){return t};function Xzr(t,e,r){return gDe.diff(t,e,r)}Mr();var v$=require("obsidian"),Lt=$(K()),Yzr=$(Im());xn();var ule=$(K());zr();var tT=ule.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:r=!1,className:n,...o},i)=>{let a=()=>{r||e?.(!t)},s=u=>{r||(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),e?.(!t))};return ule.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":r,"data-state":t?"checked":"unchecked","data-disabled":r?"":void 0,ref:i,tabIndex:r?-1:0,className:Se("tw-relative tw-inline-flex tw-h-5.5 tw-w-10 tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-full tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",r&&"tw-cursor-not-allowed tw-opacity-50",n),onClick:a,onKeyDown:s,...o},ule.createElement("div",{className:Se("tw-pointer-events-none tw-block tw-size-4 tw-rounded-full tw-bg-toggle-thumb tw-shadow-lg tw-ring-0 tw-transition-transform",t?"tw-translate-x-5.5":"tw-translate-x-0.5")}))});tT.displayName="SettingSwitch";function Zzr(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}Dt();function _ei(t,e){let r=o=>o.split(/(\s+)/).filter(Boolean);return Xzr(r(t),r(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function lle(t){let e=t.split(`
|
||
|
|
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function Qzr(t){let e=[],r=0;for(;r<t.length;){let n=t[r];if(!n.added&&!n.removed)lle(n.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),r++;else if(n.removed){let o=t[r+1];if(o?.added){let i=lle(n.value),a=lle(o.value),s=Math.max(i.length,a.length);for(let u=0;u<s;u++)e.push({original:i[u]??null,modified:a[u]??null,isUnchanged:!1});r+=2}else lle(n.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),r++}else n.added&&lle(n.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),r++}return e}var e4r=(0,Lt.memo)(({original:t,modified:e,side:r})=>{let n=_ei(t,e);return Lt.default.createElement("span",null,n.map((o,i)=>{if(r==="original"){if(o.removed)return Lt.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return Lt.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return Lt.default.createElement("span",{key:i},o.value)}))});e4r.displayName="WordDiffSpan";var cle=(0,Lt.memo)(({row:t,side:e})=>{let r=e==="original"?t.original:t.modified,n=e==="original"?t.modified:t.original;return r===null?Lt.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?Lt.default.createElement("span",{className:"tw-text-normal"},r||"\xA0"):n!==null?Lt.default.createElement(e4r,{original:t.original,modified:t.modified,side:e}):Lt.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},r||"\xA0")});cle.displayName="DiffCell";var dle="obsidian-copilot-apply-view",_De=class extends v$.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return dle}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,Yzr.createRoot)(n)),this.root.render(Lt.default.createElement(vei,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},t4r=(0,Lt.memo)(({block:t})=>{let e=(0,Lt.useMemo)(()=>Qzr(t),[t]);return Lt.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},Lt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>Lt.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Lt.default.createElement(cle,{row:r,side:"original"})))),Lt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>Lt.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Lt.default.createElement(cle,{row:r,side:"modified"})))))});t4r.displayName="SideBySideBlock";var r4r=(0,Lt.memo)(({block:t})=>{let e=t.some(n=>n.added||n.removed),r=(0,Lt.useMemo)(()=>Qzr(t),[t]);return e?Lt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Lt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Lt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),Lt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},r.map((n,o)=>n.original!==null?Lt.default.createElement("div",{key:o},Lt.default.createElement(cle,{row:n,side:"original"})):null))),Lt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Lt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Modified"),Lt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},r.map((n,o)=>n.modified!==null?Lt.default.cr
|
||
|
|
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.
|
||
|
|
The path must be relative to the root of the vault.`),content:Ae.union([Ae.string(),Ae.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
|
||
|
|
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.
|
||
|
|
|
||
|
|
# 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
|
||
|
|
|
||
|
|
# Canvas JSON Format (JSON Canvas spec 1.0)
|
||
|
|
Required node fields: id, type, x, y, width, height
|
||
|
|
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
|
||
|
|
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
|
||
|
|
Required edge fields: id, fromNode, toNode
|
||
|
|
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
|
||
|
|
All IDs must be unique. Edge nodes must reference existing node IDs.
|
||
|
|
|
||
|
|
Example:
|
||
|
|
{
|
||
|
|
"nodes": [
|
||
|
|
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
|
||
|
|
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
|
||
|
|
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
|
||
|
|
],
|
||
|
|
"edges": [
|
||
|
|
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
|
||
|
|
]
|
||
|
|
}`),confirmation:Ae.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},Ae.boolean()).optional().default(!0).describe("(Optional) Hint for confirmation preference. Note: preview is always shown unless the user has enabled auto-accept in settings.")}),SDe=rs({name:"writeFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
|
||
|
|
|
||
|
|
# 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.
|
||
|
|
`,schema:wei,func:async({path:t,content:e,confirmation:r=!0})=>{let n=KWe(t);n!==t&&(Ce(`Filename too long, truncated for filesystem compatibility: "${t}" \u2192 "${n}"`),t=n);let o=typeof e=="string"?e:JSON.stringify(e,null,2);if(ee().autoAcceptEdits)try{let u=await o4r(t);return await app.vault.modify(u,o),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."}}catch(u){return{result:"failed",message:`Error writing to file without preview: ${u?.message||u}`}}let s=await i4r(t,o);return{result:s,message:`File change result: ${s}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),Sei=Ae.object({path:Ae.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),oldText:Ae.string().describe(`(Required) The exact text to find and replace. Must match the file content exactly, including whitespace and indentation.
|
||
|
|
Fuzzy matching handles minor differences like trailing spaces or smart quotes, but the overall structure must be correct.
|
||
|
|
To make the match unique, include enough surrounding context lines (not just the changed line).`),newText:Ae.string().describe("(Required) The new text to replace the old text with. Can be empty string to delete the old text.")});function ymt(t){return t.replace(/\r\n/g,`
|
||
|
|
`).replace(/\r/g,`
|
||
|
|
`)}function wDe(t){return t.normalize("NFKC").split(`
|
||
|
|
`).map(e=>e.trimEnd()).join(`
|
||
|
|
`).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/[\u2010-\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function vDe(t,e){if(!e)return 0;let r=0,n=0;for(;(n=t.indexOf(e,n))!==-1;)r++,n+=1;return r}function Cei(t){return t.charCodeAt(0)===65279?{content:t.slice(1),hasBOM:!0}:{content:t,hasBOM:!1}}function xei(t,e,r){let n=vDe(t,e);if(n>0)return{found:!0,occurrences:n,workingContent:t,workingSearch:e,workingReplace:r,usedFuzzyMatch:!1};let o=wDe(t),i=wDe(e),a=vDe(o,i);if(a>0)return{found:!0,occurrences:a,workingContent:o,workingSearch:i,workingReplace:r,usedFuzzyMatch:!0};if(e.endsWith(`
|
||
|
|
`)){let s=e.slice(0,-1),u=r.endsWith(`
|
||
|
|
`)?r.slice(0,-1):r,l=vDe(t,s);if(l>0)return{found:!0,occurrences:l,workingContent:t,workingSearch:s,workingReplace:u,usedFuzzyMatch:!1};let c=wDe(s),d=vDe(o,c);if(d>0)return{found:!0,occurrences:d,workingContent:o,workingSearch:c,workingReplace:u,usedFuzzyMatch:!0}}return{found:!1,occurrences:0,workingContent:o,workingSearch:i,workingReplace:r,usedFuzzyMatch:!0}}function n4r(t,e,r){let n=r,o=0;for(let i=0;i<e.length;i++){let a=e[i].length,s=t[i]??"",u=s.length;if(n<=a){if(n===a)return o+u;let l=0,c=0;for(;c<s.length&&l<n;){let d=s[c].normalize("NFKC").length;if(l+d>n)break;l+=d,c++}return o+c}n-=a+1,o+=u+1}return o}function Tei(t,e,r){let{content:n,hasBOM:o}=Cei(t),i=(n.match(/\r\n/g)||[]).length,a=(n.match(/(?<!\r)\n/g)||[]).length,s=i>a,u=ymt(n),l=ymt(e),c=ymt(r),d=xei(u,l,c);if(!d.found)return{ok:!1,reason:"NOT_FOUND"};if(d.occurrences>1)return{ok:!1,reason:"AMBIGUOUS",occurrences:d.occurrences};let f,p;if(d.usedFuzzyMatch){let h=u.split(`
|
||
|
|
`),y=d.workingContent.split(`
|
||
|
|
`),g=d.workingContent.indexOf(d.workingSearch);if(f=n4r(h,y,g),p=n4r(h,y,g+d.workingSearch.length),f>=p)return{ok:!1,reason:"NOT_FOUND"};if(wDe(u.substring(f,p))!==d.workingSearch)return{ok:!1,reason:"NOT_FOUND"}}else f=u.indexOf(d.workingSearch),p=f+d.workingSearch.length;let m=u.substring(0,f)+d.workingReplace+u.substring(p);return s&&(m=m.replace(/\n/g,`\r
|
||
|
|
`)),o&&(m="\uFEFF"+m),{ok:!0,content:m}}var a4r=rs({name:"editFile",description:"Request to make a targeted change to an existing file by specifying the exact text to find and its replacement. Use this tool for precise, surgical edits to specific parts of a file.",schema:Sei,func:async({path:t,oldText:e,newText:r})=>{let n=KWe(t),o=app.vault.getAbstractFileByPath(n);if(!o||!(o instanceof _X.TFile))return{result:"failed",message:`File not found at path: ${n}. Please check the file path and try again.`};try{let i=await app.vault.read(o),a=Tei(i,e,r);if(!a.ok)return a.reason==="NOT_FOUND"?{result:"failed",message:`Could not find the specified text in ${n}. The oldText must match the file content \u2014 try including more surrounding context lines to locate the right spot.`}:{result:"failed",message:`Found ${a.occurrences} occurrences of the search text in ${n}. The text must be unique \u2014 add more surrounding context to make it unambiguous.`};let s=a.content;if(i===s)return{result:"accepted",message:`No changes made to ${n}. The replacement produced identical content. Use writeFile if the file needs a broader rewrite.`};if(ee().autoAcceptEdits)return await app.vault.modify(o,s),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."};let l=await i4r(n,s,!0);return{result:l,message:`File change result: ${l}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}catch(i){return{result:"failed",message:`Error modifying ${n}: ${i}. Please check the file path and try again.`}}}});Xe();var bmt=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},w$=class{static async callTool(e,r){if(!e)throw new Error("Tool is undefined");let n=await e.call(r);return n??(Ce(`[ToolCall] Tool "${e.name}" returned null/undefined`),null)}};function s4r(t){let e=t.trim();if(!e)return"note";let r=e.match(/^\[\[([\s\S]+?)\]\]$/),n=r?r[1]:e,[o="",i=""]=n.split("|"),a=i.trim();if(a.length>0)return a;let s=o.trim(),[u]=s.split("#"),l=(u||s).trim()||e,c=l.split("/").filter(Boolean),d=c.length>0?c[c.length-1]:l;return d.replace(/\.[^/.]+$/,"")||d||"note"}var u4r=180;function Oei(t){let e=t.trim();return e.length<=u4r?e:`${e.slice(0,u4r)}\u2026`}function Eei(t){if(!t||typeof t!="object")return null;let e=typeof t.status=="string"?t.status:null,r=typeof t.message=="string"&&t.message.trim().length>0?Oei(t.message):null,n=typeof t.notePath=="string"?t.notePath:"",i=(typeof t.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():s4r(n))||s4r(n);if(e==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${i}"`;if(e==="not_found")return r??`\u26A0\uFE0F Note "${i}" not found`;if(e==="not_unique"){let c=Array.isArray(t.candidates)?t.candidates.length:0;return r||(c>0?`\u26A0\uFE0F Multiple matches for "${i}" (${c} candidates)`:`\u26A0\uFE0F Multiple matches for "${i}"`)}if(e==="empty")return r??`\u26A0\uFE0F "${i}" contains no readable content`;if(e==="out_of_range"){if(r)return r;let c=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,d=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:null;if(d!==null&&c!==null){let f=Math.max(c-1,0);return`\u26A0\uFE0F Chunk ${d} exceeds available range (max index ${f})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:0,s=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,u=!!t.hasMore,l=[`\u2705 Read "${i||"note"}"`];return s&&s>0?l.push(`chunk ${a+1} of ${s}`):l.push(`chunk ${a+1}`),u&&l.push("more available"),l.join(" \xB7 ")}var S$=class{static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n
|
||
|
|
|
||
|
|
No matching notes found.`;let r=e.length,n=e.slice(0,10),o=n.some(s=>typeof s?.rerank_score=="number"||typeof s?.score=="number"||s?.source),i=n.map((s,u)=>o?this.formatSearchItem(s,u):this.formatBasicSearchItem(s,u)).join(`
|
||
|
|
|
||
|
|
`),a=r>10?`
|
||
|
|
|
||
|
|
... and ${r-10} more results`:"";return`\u{1F4DA} Found ${r} relevant notes
|
||
|
|
|
||
|
|
Top results:
|
||
|
|
|
||
|
|
${i}${a}`}static formatLocalSearch(e){if(typeof e=="string"){let n=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(n){let o=n[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
|
||
|
|
|
||
|
|
No matching notes found.`;let s=[],u=/<document>([\s\S]*?)<\/document>/g,l;for(;(l=u.exec(o))!==null;){let c=l[1],d=c.match(/<title>([\s\S]*?)<\/title>/),f=c.match(/<path>([\s\S]*?)<\/path>/),p=c.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),y=(p?.[1]||"").trim();s.push({title:m,path:h,mtime:y||null})}return this.formatLocalSearchDocuments(s)}}let r=this.parseSearchResults(e);return Array.isArray(r)?r.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
|
||
|
|
|
||
|
|
No matching notes found.`:this.formatLocalSearchDocuments(r):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null)return e.type==="local_search"&&Array.isArray(e.documents)?e.documents:[];if(typeof e=="string"){try{let r=JSON.parse(e);if(r&&r.type==="local_search"&&Array.isArray(r.documents))return r.documents}catch{}return[]}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 formatBasicSearchItem(e,r){let n=e.title||e.path||`Result ${r+1}`,o=[`${r+1}. ${n}`],i=e.mtime||e.modified||e.modified_at||e.updated_at;return i&&o.push(` \u{1F552} Modified: ${String(i)}`),e.path&&e.path!==n&&o.push(` \u{1F4C1} ${e.path}`),o.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(`
|
||
|
|
`)}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=String(typeof e=="object"?e.result??"":e),n=typeof e=="object"?e.diff:void 0;return r.toLowerCase().includes("accepted")&&n?`\u2705 Edit accepted
|
||
|
|
\`\`\`diff
|
||
|
|
${n}
|
||
|
|
\`\`\``:r.toLowerCase().includes("accepted")?"\u2705 Edit accepted":r.toLowerCase().includes("rejected")?"\u274C Edit rejected":typeof e=="object"&&e.message?e.message:r}static formatReadNote(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{r=null}let n=Eei(r);return n||(typeof e=="string"?e:JSON.stringify(e,null,2))}};Qe();var l4r=require("obsidian"),Pei="obsidian",Mei=["/Applications/Obsidian.app/Contents/MacOS/obsidian","/Applications/Obsidian.app/Contents/MacOS/Obsidian"],Rei=15e3,Iei=1048576;function _mt(){let t=l4r.Platform;return!!(t.isDesktopApp??t.isDesktop)}function Aei(){let t=globalThis;if(typeof t.require!="function")throw new Error("Node require is unavailable in this runtime. Obsidian CLI commands require the desktop app.");return t.require}function Nei(){let e=Aei()("child_process");if(typeof e.execFile!="function")throw new Error("Failed to resolve child_process.execFile");return e.execFile}function Dei(t){return t.replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function jei(){let e=globalThis.process?.env;return e?[e.OBSIDIAN_CLI_BINARY,e.OBSIDIAN_CLI_PATH].map(n=>n?.trim()||"").filter(Boolean):[]}function $ei(t){let e=t?.trim();if(e)return[e];let r=[...jei(),Pei,...Mei];return Array.from(new Set(r.map(n=>n.trim()).filter(Boolean)))}function Lei(t){let e=[],r=t.vault?.trim();r&&e.push(`vault=${r}`),e.push(t.command);let n=Object.entries(t.params||{});n.sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of n)if(i!=null){if(typeof i=="boolean"){i&&e.push(o);continue}e.push(`${o}=${Dei(String(i))}`)}return e}function Fei(t){return typeof t=="number"?t:null}async function kei(t,e,r,n,o,i,a){let s=Date.now();return await new Promise(u=>{t(r,n,{timeout:o,maxBuffer:i,windowsHide:!0},(l,c,d)=>{let f=Date.now()-s;if(l){u({command:e,args:n,binary:r,attemptedBinaries:[...a],ok:!1,stdout:c||"",stderr:d||"",exitCode:Fei(l.code),errorCode:l.code??null,signal:l.signal??null,durationMs:f});return}u({command:e,args:n,binary:r,attemptedBinaries:[...a],ok:!0,stdout:c||"",stderr:d||"",exitCode:0,errorCode:null,signal:null,durationMs:f})})})}async function C$(t){let e=t.command?.trim();if(!e)throw new Error("Obsidian CLI command is required");if(!_mt())throw new Error("Obsidian CLI commands are only supported in desktop Obsidian.");let r=Lei({...t,command:e}),n=t.timeoutMs??Rei,o=t.maxBufferBytes??Iei,i=Nei(),a=$ei(t.binary),s=[],u=null;for(let l of a){s.push(l);let c=await kei(i,e,l,r,n,o,s);if(u=c,c.ok||c.errorCode!=="ENOENT")return c}if(u)return u;throw new Error("Obsidian CLI execution failed before process spawn.")}async function c4r(t){return await C$({command:"daily:read",vault:t})}async function d4r(t){return await C$({command:"random:read",vault:t})}Wb();function qei(t){return"children"in t&&"path"in t}function Bei(t){return"path"in t&&!("children"in t)}function Uei(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function vmt(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=Zl();for(let u of t.children)if(Bei(u)){if(fu(u,i,a)){e&&r.push(u.name);let l=Uei(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(qei(u)){let l=vmt(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 f4r=t=>rs({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Ae.object({}),func:async()=>{let e=vmt(t,!0),r=`A JSON represents the file tree as a nested structure:
|
||
|
|
* 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
|
||
|
|
|
||
|
|
`,n=JSON.stringify(e);if(n.length>5e5){let o=vmt(t,!1);return r+JSON.stringify(o)}return r+n}});var vX=require("obsidian");Xe();Qe();Dt();ra();var $B=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath());e instanceof vX.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",F("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());r instanceof vX.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",F("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){ie("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,r){if(!ee().enableRecentConversations){Ce("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){Ce("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,r).catch(o=>{ie("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,r){if(!ee().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!r)return{error:"No chat model available, skipping save"};try{return await this.ensureMemoryFolderExists(),await this.updateSavedMemoryFile(this.getSavedMemoriesFilePath(),e,r)}catch(o){return{error:"Error saving memory: "+o.message}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=ee(),r="";return e.enableRecentConversations&&this.recentConversationsContent&&(r+=`<recent_conversations>
|
||
|
|
${this.recentConversationsContent}
|
||
|
|
</recent_conversations>
|
||
|
|
|
||
|
|
The current time is ${this.getTimestamp()}.
|
||
|
|
<recent_conversations> are the recent conversations between you and the user.
|
||
|
|
You can use it to provide more context for your responses.
|
||
|
|
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(r+=`<saved_memories>
|
||
|
|
${this.savedMemoriesContent}
|
||
|
|
</saved_memories>
|
||
|
|
|
||
|
|
<saved_memories> are important memories that the user explicitly asked you to remember.
|
||
|
|
Use these memories to provide more personalized and contextually relevant responses.`),r.length>0?r:null}catch(e){return ie("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0");return`${r}-${n}-${o} ${i}:${a}`}async createConversationSection(e,r){let{title:n,summary:o}=await this.extractTitleAndSummary(e,r),i=this.getTimestamp(),a=`## ${n}
|
||
|
|
`;return a+=`**Time:** ${i}
|
||
|
|
`,a+=`**Summary:** ${o}
|
||
|
|
`,a}async updateMemory(e,r){if(this.isUpdatingMemory){F("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!r){ie("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){F("[UserMemoryManager] No messages available, skipping memory update");return}let n=await this.createConversationSection(e,r);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),n)}catch(n){ie("[UserMemoryManager] Error analyzing chat messages for user memory:",n)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let r=ee().memoryFolderName;await ql(r)}getRecentConversationFilePath(){return`${ee().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${ee().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,r,n){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof vX.TFile?await this.app.vault.read(o):"";if(!n)return{error:"No chat model available, skipping memory update"};let a=`You maintain a user's long-term personal memory list as concise bullet points.
|
||
|
|
|
||
|
|
You task is to update the user's memory list with the new statement.
|
||
|
|
Rules:
|
||
|
|
- Keep only stable, evergreen facts or preferences that will help future conversations.
|
||
|
|
- Remove duplicates and near-duplicates by merging them into one concise statement.
|
||
|
|
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
|
||
|
|
- Prefer short, specific, and unambiguous phrasing.
|
||
|
|
- Preserve the language used in the input memories.
|
||
|
|
- Output only the memory content with each as a bullet point.
|
||
|
|
|
||
|
|
|
||
|
|
# OUTPUT FORMAT
|
||
|
|
Return the updated memory list with each as a bullet point.
|
||
|
|
- memory item 1
|
||
|
|
- memory item 2
|
||
|
|
- memory item 3
|
||
|
|
...
|
||
|
|
`,s=`<current_memories>
|
||
|
|
${i.trim()}
|
||
|
|
</current_memories>
|
||
|
|
|
||
|
|
<new_statement>
|
||
|
|
${r.trim()}
|
||
|
|
</new_statement>
|
||
|
|
`,u=[new v_(a),new Au(s)],l=null;try{l=(await n.invoke(u)).text??""}catch(c){return{error:"LLM call failed while updating saved memories: "+c.message}}return l==null||l.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof vX.TFile?await this.app.vault.modify(o,l):await this.app.vault.create(e,l),{content:l})}async addToRecentConversationsFile(e,r){let n=this.app.vault.getAbstractFileByPath(e);if(n instanceof vX.TFile){let o=await this.app.vault.read(n),i;if(o.trim()==="")i=`${r.trim()}
|
||
|
|
`;else{let a=this.parseExistingConversations(o);a.push(r);let u=ee().maxRecentConversations;a.length>u&&a.splice(0,a.length-u),i=`${a.map(c=>c.trim()).join(`
|
||
|
|
|
||
|
|
`)}
|
||
|
|
`}await this.app.vault.modify(n,i)}else{let o=`${r.trim()}
|
||
|
|
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let r=e.split(`
|
||
|
|
`),n=[],o=[];for(let i of r)i.trim().startsWith("## ")?(o.length>0&&n.push(o.join(`
|
||
|
|
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&n.push(o.join(`
|
||
|
|
`).trim()),n}extractJsonFromResponse(e){let r=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(r)return r[1].trim();let n=e.match(/\{[\s\S]*\}/);return n?n[0]:e}async extractTitleAndSummary(e,r){let n=e.map(s=>`${s.sender}: ${s.message}`).join(`
|
||
|
|
|
||
|
|
`),o=`Your task is to analyze a conversation and generate both a title and a summary.
|
||
|
|
|
||
|
|
# OUTPUT FORMAT
|
||
|
|
You must return your response in the following JSON format:
|
||
|
|
{
|
||
|
|
"title": "Brief 2-8 word title capturing the main user intent",
|
||
|
|
"summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
|
||
|
|
}
|
||
|
|
|
||
|
|
# RULES
|
||
|
|
* Use the same language as the conversation`,i=`<conversation_text>
|
||
|
|
${n}
|
||
|
|
</conversation_text>
|
||
|
|
|
||
|
|
Generate a title and summary for this conversation:`,a=[new v_(o),new Au(i)];try{let u=(await r.invoke(a)).text,l=this.extractJsonFromResponse(u);try{let c=JSON.parse(l);return{title:c.title||"Untitled Conversation",summary:c.summary||"No summary available"}}catch(c){return ie("[UserMemoryManager] Failed to parse LLM response as JSON:",c),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(s){return ie("[UserMemoryManager] Failed to extract title and summary:",s),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};Xe();LW();var zei=Ae.object({statement:Ae.string().min(1).describe("The user statement for explicitly updating saved memories")}),CDe=rs({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:zei,func:async({statement:t})=>{try{let e=new $B(app),r=U0.getInstance().getChatModel(),n=await e.updateSavedMemory(t,r);return n.error?{success:!1,message:n.error}:{success:!0,message:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${n.content}`}}catch(e){return ie("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${e.message}`}}}});var fle=require("obsidian");Xe();var wmt=200;function xDe(t){return t.replace(/\\/g,"/").toLowerCase()}function Vei(t){return t.replace(/\.[^/.]+$/,"")}function Hei(t,e){if(e.length===0)return!1;let n=xDe(t).split("/").filter(Boolean);if(n.length<e.length)return!1;let o=n.slice(-e.length);for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)return!1;let s=o[i];if(i===o.length-1){let u=Vei(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Smt(t){return/\.[^/]+$/.test(t)}async function Wei(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof fle.TFile?_:null},r=t.trim(),n=r.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),i=(n?n[1]:r).trim(),[a]=i.split("|"),[s]=a.split("#"),u=s.trim(),l=Array.from(new Set([r,i,u].map(b=>b.trim()).filter(Boolean)));for(let b of l){let _=e(b);if(_)return{type:"resolved",file:_};if(!Smt(b))for(let w of[".md",".canvas"]){let T=e(`${b}${w}`);if(T)return{type:"resolved",file:T}}}let c=app.metadataCache,d=u.trim();if(c&&d){let b=new Set([d]);if(!Smt(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof fle.TFile)return{type:"resolved",file:w}}}if(!d)return{type:"not_found"};let f=app.vault.getMarkdownFiles?.()??[];if(f.length===0)return{type:"not_found"};let p=xDe(d),m=new Set([p]);if(!Smt(d))for(let b of[".md",".canvas"])m.add(xDe(`${d}${b}`));for(let b of f){let _=xDe(b.path);if(m.has(_))return{type:"resolved",file:b}}let h=d.split("/").pop();if(h){let b=h.toLowerCase(),_=f.filter(w=>w.basename.toLowerCase()===b);if(_.length===1)return{type:"resolved",file:_[0]};if(_.length>1)return{type:"not_unique",matches:_}}let y=p.split("/").filter(Boolean);if(y.length===0)return{type:"not_found"};let g=f.filter(b=>Hei(b.path,y));return g.length===1?{type:"resolved",file:g[0]}:g.length>1?{type:"not_unique",matches:g}:{type:"not_found"}}async function Jei(t){try{return await app.vault.read(t)}catch(e){return Ce(`readNote: failed to read ${t.path}`,e),""}}function Kei(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof fle.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function Gei(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof fle.TFile&&o.set(i.path,i),!/\.[^./]+$/.test(n)){let a=n.split("/").pop()??n,s=r.get(a)??[];for(let u of s)o.set(u.path,u)}return Array.from(o.values())}function Xei(t,e){if(!t)return[];let r=/\[\[([^\]]+)\]\]/g,n=new Map,o=null,i;for(;(i=r.exec(t))!==null;){if(i.index>0&&t[i.index-1]==="!")continue;let a=i[1]?.trim();if(!a)continue;let[s,u]=a.split("|"),[l,c]=s.split("#"),d=l?.trim();if(!d)continue;let f=`${d}|${u??""}|${c??""}`;if(n.has(f))continue;o||(o=Kei());let p=Gei(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0,candi
|
||
|
|
`).trimEnd(),heading:d})}return i}var Yei=Ae.object({notePath:Ae.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:Ae.preprocess(t=>{if(typeof t=="string"){let e=t.trim();if(e.length===0)return;let r=Number(e);return Number.isFinite(r)?r:t}return t},Ae.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),p4r=rs({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:Yei,func:async({notePath:t,chunkIndex:e=0})=>{let r=t.trim();if(r.startsWith("/"))return{notePath:r,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};let n=await Wei(r);if(n.type==="not_found")return Ce(`readNote: note not found or not a file (${r})`),{notePath:r,status:"not_found",message:`Note "${r}" was not found or is not a readable file.`};if(n.type==="not_unique")return Ce(`readNote: ambiguous note path "${r}" matched multiple files`,n.matches.map(f=>f.path)),{notePath:r,status:"not_unique",message:`Multiple notes match "${r}". Provide a more specific path.`,candidates:n.matches.map(f=>({path:f.path,title:f.basename}))};let o=n.file,i=o.path,a=await Jei(o),s=Zei(o,a),u=s.length;if(u===0)return{notePath:i,status:"empty",message:`No readable content was found in "${i}".`};if(e>=u)return{notePath:i,status:"out_of_range",message:`Chunk index ${e} exceeds available chunks (last index ${u-1}).`,totalChunks:u};let l=s[e];F(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=l.chunkIndex<u-1,d=Xei(l.content,o);return{notePath:i,noteTitle:o.basename,heading:l.heading,chunkId:l.id,chunkIndex:l.chunkIndex,totalChunks:u,hasMore:c,nextChunkIndex:c?l.chunkIndex+1:null,content:l.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}});function TDe(t,e,r,n){let o=t.trim();return o.length>0?o:r==="ENOENT"?`CLI binary not found. Tried: ${n.length>0?n.join(", "):"unknown"}. Ensure Obsidian CLI is installed or set OBSIDIAN_CLI_BINARY/OBSIDIAN_CLI_PATH.`:r!==null?`Obsidian CLI failed with error code ${String(r)}`:e!==null?`Obsidian CLI failed with exit code ${e}`:"Obsidian CLI command failed for an unknown reason"}function BW(t){throw new Error(TDe(t.stderr,t.exitCode,t.errorCode,t.attemptedBinaries))}var Xms=rs({name:"obsidianDailyRead",description:"Read the current daily note via Obsidian CLI and return the note content as plain text.",schema:Ae.object({vault:Ae.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await c4r(t);if(!e.ok)throw new Error(`Failed to read daily note via Obsidian CLI: ${TDe(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_daily_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}}),m4r=rs({name:"obsidianRandomRead",description:"Read a random note via Obsidian CLI and return the note content as plain text.",schema:Ae.object({vault:Ae.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await d4r(t);if(!e.ok)throw new Error(`Failed to read random note via Obsidian CLI: ${TDe(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_random_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}});function wX(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>e!=="command"&&e!=="vault"&&r!==void 0))}var Qei=Ae.object({command:Ae.enum(["daily","daily:read","daily:path"]).describe("daily \u2014 create today's daily note (applies configured template). daily:read \u2014 read today's daily note content. daily:path \u2014 get the vault-relative file path."),vault:Ae.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),h4r=rs({name:"obsidianDailyNote",descript
|
||
|
|
`:`Semantic search index refreshed with ${r} documents.
|
||
|
|
`;return{success:!0,message:n?o+"Miyo will handle chunking and indexing for the registered folder.":o+`Semantic search index has been refreshed with ${r} documents.`,documentCount:r}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e.message}`}}else return{success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."}}}),uti=Ae.object({query:Ae.string().min(1).describe("The search query to search the internet"),chatHistory:Ae.array(Ae.object({role:Ae.enum(["user","assistant"]),content:Ae.string()})).describe("Previous conversation turns for context (usually empty array)")}),PDe=rs({name:"webSearch",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",schema:uti,func:async({query:t,chatHistory:e})=>{try{let r=await fEe(t,e),n,o;if(Wy()&&Kbr()){let a=await Gbr(r);n=a.content,o=a.citations}else{let a=await Xl.getInstance().webSearch(r);n=a.response.choices[0].message.content,o=a.response.citations||[]}return[{type:"web_search",content:n,citations:o,instruction:Fzr()}]}catch(r){return console.error(`Error processing web search query ${t}:`,r),{error:`Web search failed: ${r}`}}}});var Rmt=5e5,lti=500,w4r=50,cti=Ae.object({includeInline:Ae.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:Ae.number().int().min(1).max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");function dti(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function S4r(t){let e={};if(!t)return e;for(let[r,n]of Object.entries(t)){let o=r?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let a=`#${i}`;if(a==="#")continue;let s=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;e[a]=(e[a]||0)+s}return e}function fti(t,e,r){let n=t,o=S4r(n.getFrontmatterTags?.()),i=e?S4r(n.getTags?.()):{},a=new Set([...Object.keys(o),...e?Object.keys(i):[]]),s=[],u=0;for(let c of a){let d=o[c]??0,f=e?Math.max(0,i[c]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(u+=m,s.push({tag:c,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}s.sort((c,d)=>d.occurrences===c.occurrences?c.tag.localeCompare(d.tag):d.occurrences-c.occurrences);let l=s.slice(0,r);return{totalUniqueTags:s.length,returnedTagCount:l.length,totalOccurrences:u,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:l.length<s.length,tags:l}}function pti(t){let e=t,r=JSON.stringify(e);if(r.length<=Rmt)return e;let n=e.tags.length;for(;r.length>Rmt&&n>w4r;)n=Math.max(w4r,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>Rmt?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function C4r(t){return`A JSON object lists the vault tags and their occurrence counts:
|
||
|
|
* totalUniqueTags: number of unique tags indexed across the vault
|
||
|
|
* returnedTagCount: number of tag entries included in this response
|
||
|
|
* totalOccurrences: total tag occurrences across included sources
|
||
|
|
* includedSources: sources represented in the counts (frontmatter, inline)
|
||
|
|
* truncated: whether the list was shortened due to limits
|
||
|
|
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
|
||
|
|
${JSON.stringify(t)}`}var x4r=()=>rs({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:cti,func:async t=>{let e=dti(),r=t?.includeInline??!0,n=t?.maxEntries??lti;if(!e)return C4r({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:r?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let o=fti(e,r,n),i=pti(o);return C4r(i)}});var P4r=$(T4r(),1),ple=$(FB(),1);var ns;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(ns||(ns={}));var mm;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(mm||(mm={}));var Jw;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(Jw||(Jw={}));function O4r(t,e){e=e.add(1,"day"),UW(t,e),SX(t,e)}function rT(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function MDe(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",ns.AM):t.assign("meridiem",ns.PM)}function UW(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function SX(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var jmt=$(FB(),1);var mti={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>E4r(t,Jw.MARCH,mm.SUNDAY,2),dstEnd:t=>E4r(t,Jw.OCTOBER,mm.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>kB(t,Jw.MARCH,mm.SUNDAY,2,2),dstEnd:t=>kB(t,Jw.NOVEMBER,mm.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>kB(t,Jw.MARCH,mm.SUNDAY,2,2),dstEnd:t=>kB(t,Jw.NOVEMBER,mm.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>kB(t,Jw.MARCH,mm.SUNDAY,2,2),dstEnd:t=>kB(t,Jw.NOVEMBER,mm.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>kB(t,Jw.MARCH,mm.SUNDAY,2,2),dstEnd:t=>kB(t,Jw.NOVEMBER,mm.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEK
|
||
|
|
tags: ${JSON.stringify(Array.from(this._tags).sort())},
|
||
|
|
knownValues: ${JSON.stringify(this.knownValues)},
|
||
|
|
impliedValues: ${JSON.stringify(this.impliedValues)}},
|
||
|
|
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,ple.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,ple.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?(MDe(o,n),rT(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(SX(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}},x$=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 os(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 $mt(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function hti(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function ty(t){return`(?:${hti(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var M4r=$(FB(),1);function IDe(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function BB(t,e,r){let n=(0,M4r.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 kmt={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},qmt={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},z0={...qmt,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},Lmt={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},Fmt={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},I4r={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},mle={s:"second",sec:"second",second:"second",seconds:"second",m:"mi
|
||
|
|
|
||
|
|
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"
|
||
|
|
|
||
|
|
SUPPORTED FORMATS:
|
||
|
|
- Simple: "+8", "-5", "+5:30"
|
||
|
|
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
|
||
|
|
|
||
|
|
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)
|
||
|
|
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),func:async({timezoneOffset:t})=>Gni(t)}),IVr={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,sept:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};function Xni(t,e){let r=t.match(/^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i);if(!r)return;let[,,n,o]=r,i=parseInt(n);if(i<=0)return;let a=o.replace(/s$/,""),s=e.startOf("day");return{start:s.minus({[a+"s"]:i}),end:s}}function Zni(t,e){switch(t){case"yesterday":return{start:e.minus({days:1}).startOf("day"),end:e.minus({days:1}).endOf("day")};case"last week":return{start:e.minus({weeks:1}).startOf("week"),end:e.minus({weeks:1}).endOf("week")};case"this week":return{start:e.startOf("week"),end:e.endOf("week")};case"next week":return{start:e.plus({weeks:1}).startOf("week"),end:e.plus({weeks:1}).endOf("week")};case"last month":return{start:e.minus({months:1}).startOf("month"),end:e.minus({months:1}).endOf("month")};case"this month":return{start:e.startOf("month"),end:e.endOf("month")};case"next month":return{start:e.plus({months:1}).startOf("month"),end:e.plus({months:1}).endOf("month")};case"last year":return{start:e.minus({years:1}).startOf("year"),end:e.minus({years:1}).endOf("year")};case"this year":return{start:e.startOf("year"),end:e.endOf("year")};case"next year":return{start:e.plus({years:1}).startOf("year"),end:e.plus({years:1}).endOf("year")};case"last quarter":return{start:e.minus({quarters:1}).startOf("quarter"),end:e.minus({quarters:1}).endOf("quarter")};case"this quarter":return{start:e.startOf("quarter"),end:e.endOf("quarter")};case"next quarter":return{start:e.plus({quarters:1}).startOf("quarter"),end:e.plus({quarters:1}).endOf("quarter")}}}function Yni(t,e){let r=t.match(/(?:the\s+)?week\s+of\s+(.+)/i);if(!r)return;let n=r[1],o=Jmt(n,e.toJSDate(),{forwardDate:!1});if(o.length===0)return;let i=$n.fromJSDate(o[0].start.date()).startOf("week"),a=i.endOf("week");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function Qni(t,e){let r=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)$/i);if(!r)return;let n=IVr[r[1]],o=e.year;n>e.month&&o--;let i=$n.fromObject({year:o,month:n,day:1}),a=i.endOf("month");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function eoi(t,e){let r=t.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);if(!r)return;let n=parseInt(r[1]),o=$n.fromObject({year:n,month:1,day:1}),i=$n.fromObject({year:n,month:12,day:31});return o>e&&(o=o.minus({years:1}),i=i.minus({years:1})),{start:o,end:i}}function toi(t,e){let r=t.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/),n=t.match(/^(?:q|Q)(\d{1})$/),o,i;if(r)o=parseInt(r[1]||r[4]),i=parseInt(r[2]||r[3]);else if(n){o=parseInt(n[1]),i=e.year;let l=Math.floor((e.month-1)/3)+1;o>l&&i--}else return;if(o<1||o>4)return;let a=(o-1)*3+1,s=$n.fromObject({year:i,month:a,day:1}).startOf("day"),u=s.plus({months:3}).minus({days:1}).endOf("day");return s>e&&(s=s.minus({years:1}),u=u.minus({years:1})),{start:s,end:u}}function roi(t,e){let r=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i);if(!r)return;let n=IVr[r[1].toLowerCase()],o=parseInt(r[2]),i=$n.fromObject({year:o,month:n,day:1}).startOf("day"),a=i.endOf("month");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function noi(t){let e=$n.now(),r=t.toLowerCase().replace("@vault","").trim(),n=Xni(r,e)||Zni(r,e)||Yni(r,e)||Qni(r,e)||roi(r,e)||toi(r,e)||eoi(r,e);if(n)return{startTime:n.start.toMillis(),endTime:n.end.toMillis()};let o=Jmt(t,e.toJSDate(),{forwardDate:!1});if(o.length>0){let i=$n.fromJSDate(o[0].start.date()).startOf("day"),a=o[0].end?$n.fromJSDate(o[0].end.date()).endOf("day"):i.endOf("day");return i>e&&(i.minus({years:1}),a.minus({years:1})),{startTime:i.toMillis(),endTime:a.toMillis()}}consol
|
||
|
|
|
||
|
|
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"
|
||
|
|
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{let e=noi(t);return e||{error:`Unable to parse time expression: ${t}`}}});function ioi(t){let e=t.toString().length===10?t*1e3:t,r=$n.fromMillis(e);return ooi(r)}var NVr=rs({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:Ae.object({epoch:Ae.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>ioi(t)});async function aoi(t,e,r){let n=Aht(e),o=Aht(r);try{let i=$n.now().setZone(n),a=_2r(t,i.toJSDate());if(!a)throw new Error(`Could not parse time: ${t}`);let s=$n.fromJSDate(a,{zone:n}),u=s.setZone(o);if(!u.isValid)throw new Error("Invalid timezone conversion");let l=u.toJSDate(),c=u.offset;return{epoch:Math.floor(l.getTime()),isoString:l.toISOString(),userLocaleString:u.toLocaleString($n.DATETIME_FULL),localDateString:u.toISODate()||"",timezoneOffset:c,timezone:u.offsetNameShort||o,originalTime:s.toLocaleString($n.TIME_SIMPLE)+" "+s.offsetNameShort,convertedTime:u.toLocaleString($n.TIME_SIMPLE)+" "+u.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var DVr=rs({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:Ae.object({time:Ae.string().describe(`Time to convert. Supports various formats:
|
||
|
|
- 12-hour: "6pm", "3:30 PM", "11:45 am"
|
||
|
|
- 24-hour: "18:00", "15:30", "23:45"
|
||
|
|
- Relative: "noon", "midnight"`),fromOffset:Ae.string().describe(`Source UTC offset. Must be numeric, not timezone name.
|
||
|
|
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:Ae.string().describe(`Target UTC offset. Must be numeric, not timezone name.
|
||
|
|
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"
|
||
|
|
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:r})=>aoi(t,e,r)});aA();id();Qe();Dt();var jVr=5e4,$Vr=rs({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:Ae.object({_userMessageContent:Ae.string().optional().describe("Internal: user message content injected by the system")}),func:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>jVr)return{success:!1,message:`Input too long: Maximum allowed length is ${jVr} characters`};let r=CNt(e);if(r.length===0)return{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=Wy()&&ee().supadataApiKey?await rEe(i):await Xl.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"}}}));return{success:n.some(i=>i.success),results:n,total_urls:r.length}}});var soi=[{tool:EDe,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
|
||
|
|
- 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
|
||
|
|
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
|
||
|
|
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain 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
|
||
|
|
|
||
|
|
Evaluating search results and re-searching:
|
||
|
|
- Results include a relevance quality summary: high (score \u22650.7), medium (0.3-0.7), low (<0.3)
|
||
|
|
- If most results are low relevance or miss key concepts from the user's question:
|
||
|
|
1. Try searching again with synonyms or related terms
|
||
|
|
2. Use more specific phrasing if query was too broad
|
||
|
|
3. Use more general phrasing if query was too narrow
|
||
|
|
- Example: "machine learning algorithms" returned low results \u2192 try "ML models", "neural networks", or "AI techniques"
|
||
|
|
|
||
|
|
Examples:
|
||
|
|
- Query "piano learning practice" \u2192 query: "piano learning practice", salientTerms: ["piano", "learning", "practice"]
|
||
|
|
- Query "#projectx status update" \u2192 query: "#projectx status update", salientTerms: ["#projectx", "status", "update"]
|
||
|
|
- Query "\u94A2\u7434\u5B66\u4E60" (Chinese) \u2192 query: "\u94A2\u7434\u5B66\u4E60", salientTerms: ["\u94A2\u7434", "\u5B66\u4E60"] (preserve original language)
|
||
|
|
|
||
|
|
For time-based searches (e.g., "what did I do last week"):
|
||
|
|
1. First call getTimeRangeMs with timeExpression: "last week"
|
||
|
|
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)
|
||
|
|
|
||
|
|
For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
|
||
|
|
1. First call getTimeRangeMs with timeExpression: "yesterday"
|
||
|
|
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]
|
||
|
|
|
||
|
|
For broad searches:
|
||
|
|
- If the user wants a comprehensive list, use getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:PDe,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
|
||
|
|
- ONLY use when the user's query contains explicit web-search intent like:
|
||
|
|
* "web search", "internet search", "online search"
|
||
|
|
* "Google", "search online", "look up online", "search the web"
|
||
|
|
- Always provide an empty chatHistory array
|
||
|
|
|
||
|
|
Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:RVr,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):
|
||
|
|
|
||
|
|
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
|
||
|
|
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
|
||
|
|
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
|
||
|
|
|
||
|
|
Examples:
|
||
|
|
- "what time is it" (local time) \u2192 call with no parameters
|
||
|
|
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
|
||
|
|
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:NVr,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:AVr,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
|
||
|
|
- 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
|
||
|
|
|
||
|
|
Example: For "last week" \u2192 timeExpression: "last week"`}},{tool:DVr,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
|
||
|
|
|
||
|
|
Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:p4r,metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
|
||
|
|
- Decide based on the user's request: only call this tool when the question requires reading note content.
|
||
|
|
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
|
||
|
|
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
|
||
|
|
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
|
||
|
|
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
|
||
|
|
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
|
||
|
|
- Stop calling readNote as soon as you have the required information.
|
||
|
|
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
|
||
|
|
|
||
|
|
Examples:
|
||
|
|
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
|
||
|
|
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:SDe,metadata:{id:"writeFile",displayName:"Write to File",description:"Create or rewrite files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeFile:
|
||
|
|
- 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 writeFile for any intent of updating or creating files
|
||
|
|
- Do not call writeFile tool again if the result is not accepted
|
||
|
|
- Do not call writeFile tool if no change needs to be made
|
||
|
|
- Always create new notes in root folder or folders the user explicitly specifies
|
||
|
|
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
|
||
|
|
Examples:
|
||
|
|
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
|
||
|
|
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:a4r,metadata:{id:"editFile",displayName:"Edit File",description:"Make a targeted, single-match edit to an existing file",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For editFile:
|
||
|
|
- Use for targeted edits; use writeFile for major rewrites or new files
|
||
|
|
- oldText must uniquely identify the location \u2014 include surrounding context lines if needed
|
||
|
|
- The tool automatically handles minor whitespace/quote differences (fuzzy matching)
|
||
|
|
- Call once per edit; for multiple edits call the tool multiple times
|
||
|
|
|
||
|
|
Example: Add "Bob Johnson" to attendees in notes/meeting.md:
|
||
|
|
path: "notes/meeting.md"
|
||
|
|
oldText: "## Attendees\\n- John Smith\\n- Jane Doe"
|
||
|
|
newText: "## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson"`}},{tool:$Vr,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
|
||
|
|
- Use when user provides YouTube URLs
|
||
|
|
- No parameters needed - the tool will process URLs from the conversation`}}];function uoi(t){Uc.getInstance().register({tool:f4r(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
|
||
|
|
- Use to browse the vault's file structure including paths of notes and folders
|
||
|
|
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
|
||
|
|
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
|
||
|
|
- No parameters needed
|
||
|
|
|
||
|
|
Example queries that should use getFileTree:
|
||
|
|
- "Create a new note in the projects folder" \u2192 call getFileTree to get the exact folder path
|
||
|
|
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
|
||
|
|
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}function loi(){Uc.getInstance().register({tool:x4r(),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
|
||
|
|
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
|
||
|
|
- Omit parameters to include both frontmatter and inline tags.
|
||
|
|
- Set includeInline to false when you only need frontmatter-defined tags.
|
||
|
|
- Use maxEntries to limit output for very large vaults.
|
||
|
|
|
||
|
|
Examples:
|
||
|
|
- Default (all tags): call with no parameters
|
||
|
|
- Frontmatter only: includeInline: false`}})}function coi(){Uc.getInstance().register({tool:CDe,metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
|
||
|
|
- Use this tool to update the memory when the user explicitly asks to update the memory
|
||
|
|
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
|
||
|
|
|
||
|
|
Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}function doi(){let t=Uc.getInstance();t.register({tool:h4r,metadata:{id:"obsidianDailyNote",displayName:"Daily Note",description:"Create or read today's daily note, or get its path",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianDailyNote:
|
||
|
|
- Use for daily note operations: creating, reading content, or getting the file path.
|
||
|
|
- Use readNote for reading specific notes by path. Use obsidianDailyNote only for today's daily note.
|
||
|
|
- daily \u2014 create today's daily note. Applies the user's configured daily note template automatically. Use this when the user asks to create or set up today's daily note.
|
||
|
|
- daily:read \u2014 read today's daily note content.
|
||
|
|
- daily:path \u2014 get the vault-relative file path (useful for follow-up readNote calls).
|
||
|
|
- For past or future daily notes (e.g. "yesterday's daily note"): NEVER ask the user for the date \u2014 use the time tools. Workflow: (1) call getCurrentTime to resolve the date, (2) call daily:path to discover the date format and folder, (3) call obsidianTemplates with command=templates to list available template names, then call template:read with the name that matches (e.g. "Daily Note Template"), (4) use writeFile to create the note at the resolved path with the template content, replacing variables like {{date}} with the target date. If templates returns an error or no daily template is found, ask the user for their template path and use readNote to read it.
|
||
|
|
- To add content to a daily note, use writeFile or editFile.
|
||
|
|
- Use \\n for newlines and \\t for tabs in content strings.
|
||
|
|
- For arbitrary file writes beyond daily notes, use writeFile or editFile instead.
|
||
|
|
- If the user names a specific vault, pass it using the vault parameter.`}}),t.register({tool:m4r,metadata:{id:"obsidianRandomRead",displayName:"Random Note",description:"Read a random note using the official Obsidian CLI",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianRandomRead:
|
||
|
|
- Use when the user explicitly asks for a random note or random note content.
|
||
|
|
- If the user names a specific vault, pass it using the vault parameter.
|
||
|
|
- Do not use when the user asks for a specific note; use readNote/getFileTree for specific targets.`}}),t.register({tool:g4r,metadata:{id:"obsidianProperties",displayName:"Properties",description:"Read frontmatter properties from notes or list all property names in the vault",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianProperties:
|
||
|
|
- Use to inspect frontmatter properties across the vault or within a specific note.
|
||
|
|
- properties (no file/path): list all property names used vault-wide. Add counts=true for occurrence counts. Add sort=count to sort by frequency.
|
||
|
|
- properties with file= or path=: list that note's key-value property pairs.
|
||
|
|
- property:read: read a single property value from a specific note. Requires name parameter.
|
||
|
|
- file= resolves like a wikilink (name only, no path or extension). path= uses exact vault-relative path.
|
||
|
|
- Do not use for full note content \u2014 use readNote for that.
|
||
|
|
- To modify properties, use writeFile or editFile to update the frontmatter YAML.`}}),t.register({tool:y4r,metadata:{id:"obsidianTasks",displayName:"Tasks",description:"List tasks across the vault with filters for status, file, and daily note",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTasks:
|
||
|
|
- ALWAYS use this tool when the user asks about tasks, todos, or checkboxes. Do NOT use localSearch for task queries.
|
||
|
|
- Use to list and filter tasks across the vault.
|
||
|
|
- todo=true: show only incomplete tasks. done=true: show only completed tasks.
|
||
|
|
- status="x": filter by specific status character (e.g., "/" for in-progress, "x" for done, " " for open).
|
||
|
|
- daily=true: show tasks from today's daily note only.
|
||
|
|
- verbose=true: group tasks by file with line numbers.
|
||
|
|
- total=true: return only the task count.
|
||
|
|
- file= resolves like a wikilink (name only). path= uses exact vault-relative path.
|
||
|
|
- For time-based task queries (e.g. "tasks from last month"): use verbose=true to get tasks grouped by file, then filter results by file dates or daily note filenames to match the time range.`}}),t.register({tool:b4r,metadata:{id:"obsidianLinks",displayName:"Links",description:"Query the vault link graph: backlinks, outgoing links, orphans, unresolved",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianLinks:
|
||
|
|
- Use to explore the vault's link graph.
|
||
|
|
- backlinks: list notes that link TO a given file. Use file= or path= to target a note. Add counts=true for link counts.
|
||
|
|
- links: list outgoing links FROM a given file. Use file= or path= to target a note.
|
||
|
|
- orphans: list all notes with no incoming links. Use total=true for just the count. Add all=true to include non-markdown files.
|
||
|
|
- unresolved: list wikilinks that don't resolve to any existing file. Use counts=true for occurrence counts, verbose=true to see source files.
|
||
|
|
- file= resolves like a wikilink (name only). path= uses exact vault-relative path. Without either, targets the active file.`}}),t.register({tool:_4r,metadata:{id:"obsidianTemplates",displayName:"Templates",description:"List available templates or read template content",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTemplates:
|
||
|
|
- Use 'templates' to list all available templates when you need to find the right template for a task.
|
||
|
|
- Use 'template:read' with a template name to get its content with variables resolved. Requires name parameter.
|
||
|
|
- This is useful for creating daily notes from templates \u2014 read the template first, then use writeFile to populate the note.`}}),t.register({tool:v4r,metadata:{id:"obsidianBases",displayName:"Bases",description:"List Base files, views, query data, or create new items in Obsidian Bases",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianBases:
|
||
|
|
- Use to explore and manage structured data in Obsidian Base (.base) database files.
|
||
|
|
- bases: list all Base files in the vault. Use total=true for just the count.
|
||
|
|
- base:views: list the views defined in a Base file. Requires file= or path=.
|
||
|
|
- base:query: query data from a specific Base view. Requires file= or path=, optionally view= and format= (e.g., format=csv).
|
||
|
|
- base:create: create a new item (row) in a Base. Requires file= or path=. Optional: view= (target view), name= (file name for the item), content= (initial note content).
|
||
|
|
- The created item appears as a new note that matches the Base's filter criteria.
|
||
|
|
- Use base:query first to understand the Base's structure and existing data before creating items.
|
||
|
|
- If the Base filters by a specific tag or folder, ensure the new item will match those filters.
|
||
|
|
|
||
|
|
Base file YAML reference (for creating new .base files with writeFile):
|
||
|
|
- filters: MUST be either a single string OR an object with and/or/not keys. NEVER use a bare YAML list.
|
||
|
|
- Single filter: filters: 'file.hasTag("book")'
|
||
|
|
- Multiple filters: filters: { and: ['file.hasTag("book")', 'status == "reading"'] }
|
||
|
|
- Negation: filters: { not: ['file.hasTag("archived")'] }
|
||
|
|
- Bare lists like "filters: - 'expr'" are INVALID and will cause parse errors.
|
||
|
|
- formulas: computed properties. Functions: date(), now(), today(), if(cond, true, false), duration(). Duration fields: .days, .hours, .minutes. Example: days_left: 'if(due, (date(due) - today()).days, "")'
|
||
|
|
- properties: display config per property (displayName, width, hidden).
|
||
|
|
- views: table (default), cards, list, or map. Each view can have its own filters, order (property display list), groupBy, summaries.
|
||
|
|
- Property types: note properties (from frontmatter), file properties (file.name, file.mtime, file.ctime, file.tags, file.links, file.backlinks), formula properties (formula.my_formula).
|
||
|
|
- YAML quoting: single-quote formulas containing double quotes: 'if(done, "Yes", "No")'. Quote strings with special chars (:, {, }, [, ]).
|
||
|
|
- Embed in notes with ![[MyBase.base]] or ![[MyBase.base#View Name]].
|
||
|
|
- VALIDATION: After creating or editing a .base file, ALWAYS call obsidianBases with base:views to verify it parses correctly. If it returns an error, fix the YAML with writeFile and re-validate. Do not stop until validation passes.`}})}function HX(t){let e=Uc.getInstance(),r=ee(),n=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,a=r.enableSavedMemory;(e.getAllTools().length===0||n!==o||i!==a)&&(e.clear(),e.registerAll(soi),t&&(uoi(t),loi()),r.enableSavedMemory&&coi(),_mt()&&doi())}Dt();Dt();var rje=class{constructor(e,r){this.toolManager=e;this.writeFileTool=r;this.buffer=""}findCompleteBlock(e){let r=/<writeFile>[\s\S]*?<\/writeFile>/,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.writeFileTool,{path:u,content:l}),d=S$.format("writeFile",c);yield{...e,content:`
|
||
|
|
${d}
|
||
|
|
`}}catch(c){yield{...e,content:`
|
||
|
|
Error: ${c?.message||c}
|
||
|
|
`}}this.buffer=this.buffer.substring(i),n=this.findCompleteBlock(this.buffer)}}};Xe();function LVr(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,r=0,n=0,o=0;for(let i of t){let a=i.rerank_score??i.score??0;o+=a,a>=.7?e++:a>=.3?r++:n++}return{high:e,medium:r,low:n,total:t.length,averageScore:o/t.length}}function FVr(t){let e=[];return t.high>0&&e.push(`${t.high} high`),t.medium>0&&e.push(`${t.medium} medium`),t.low>0&&e.push(`${t.low} low`),e.length===0?"[Relevance: no results]":`[Relevance: ${e.join(", ")}]`}function Nht(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,o)=>{let i=n.title||"Untitled",a=n.path||"",s=n.__sourceId||n.collection_name||n.source_id||o+1,u=null;if(n.mtime){let l=new Date(n.mtime);isNaN(l.getTime())||(u=l.toISOString())}return`<document>
|
||
|
|
<id>${s}</id>
|
||
|
|
<title>${i}</title>${a&&a!==i?`
|
||
|
|
<path>${a}</path>`:""}${u?`
|
||
|
|
<modified>${u}</modified>`:""}
|
||
|
|
<content>
|
||
|
|
${n.content||""}
|
||
|
|
</content>
|
||
|
|
</document>`}).filter(n=>n.length>0).join(`
|
||
|
|
|
||
|
|
`)}function kVr(t){try{let e=JSON.parse(t);return Array.isArray(e)?Nht(e):"Invalid search results format."}catch(e){return Ce("Failed to format localSearch result string:",e),"Error processing search results."}}function qVr(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})):[]}function nje(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function foi(t){if(!t)return"";let e=[];try{if(Array.isArray(t.lexicalMatches)&&t.lexicalMatches.length>0){let r=new Set,n=new Set;for(let a of t.lexicalMatches)a?.field&&r.add(String(a.field)),a?.query&&n.add(String(a.query));let o=Array.from(r).join("/"),i=Array.from(n).slice(0,3).join(", ");e.push(`Lexical(${o}): ${i}${n.size>3?", ...":""}`)}if(typeof t.semanticScore=="number"&&t.semanticScore>0&&e.push(`Semantic: ${(t.semanticScore*100).toFixed(1)}%`),t.folderBoost&&typeof t.folderBoost.boostFactor=="number"){let r=t.folderBoost,n=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${n})`)}if(t.graphConnections&&typeof t.graphConnections=="object"){let r=t.graphConnections,n=[];r.backlinks>0&&n.push(`${r.backlinks} backlinks`),r.coCitations>0&&n.push(`${r.coCitations} co-cites`),r.sharedTags>0&&n.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${n.length?` (${n.join(", ")})`:""}`):n.length&&e.push(`Graph (${n.join(", ")})`)}if(t.graphBoost&&typeof t.graphBoost.boostFactor=="number"&&!t.graphConnections){let r=t.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof t.baseScore=="number"&&typeof t.finalScore=="number"&&t.baseScore!==t.finalScore&&e.push(`Score: ${t.baseScore.toFixed(4)}\u2192${t.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function BVr(t,e,r=1){let n=r,o=[];if(t.length>0){let i=t.map(a=>{let s=a.__sourceId||n++,u=a.title||"Untitled",l=a.path||"",c=a.matchType||a.source||"filter",d=nje(a.mtime);return`<document>
|
||
|
|
<id>${s}</id>
|
||
|
|
<title>${u}</title>
|
||
|
|
<path>${l}</path>
|
||
|
|
<matchType>${c}</matchType>${d?`
|
||
|
|
<modified>${d}</modified>`:""}
|
||
|
|
<content>
|
||
|
|
${a.content||""}
|
||
|
|
</content>
|
||
|
|
</document>`}).join(`
|
||
|
|
|
||
|
|
`);o.push(`<filterResults>
|
||
|
|
${i}
|
||
|
|
</filterResults>`)}if(e.length>0){let i=e.map(a=>{let s=a.__sourceId||n++,u=a.title||"Untitled",l=a.path||"",c=nje(a.mtime);return`<document>
|
||
|
|
<id>${s}</id>
|
||
|
|
<title>${u}</title>${l&&l!==u?`
|
||
|
|
<path>${l}</path>`:""}${c?`
|
||
|
|
<modified>${c}</modified>`:""}
|
||
|
|
<content>
|
||
|
|
${a.content||""}
|
||
|
|
</content>
|
||
|
|
</document>`}).join(`
|
||
|
|
|
||
|
|
`);o.push(`<searchResults>
|
||
|
|
${i}
|
||
|
|
</searchResults>`)}return o.length===0?"No relevant documents found.":o.join(`
|
||
|
|
|
||
|
|
`)}var poi=new Set(["time-filtered","tag-match"]);function UVr(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>e.source!=null&&poi.has(e.source))}function zVr(t){return Array.isArray(t)?t.some(e=>e.source==="time-filtered"):!1}function Dht(t,e=300){if(!Array.isArray(t)||t.length===0)return"";let r=t.map(n=>{let o=n.title||"Untitled",i=n.path||"",a=nje(n.mtime),u=hX(n.content||"").slice(0,e),l=i?`
|
||
|
|
<path>${i}</path>`:"",c=a?`
|
||
|
|
<modified>${a}</modified>`:"",d=u?`
|
||
|
|
<snippet>${u}</snippet>`:"";return`<file>
|
||
|
|
<title>${o}</title>${l}${c}${d}
|
||
|
|
</file>`}).join(`
|
||
|
|
`);return`<additionalMatches count="${t.length}" note="These results contain titles and metadata only. To read the full content of a note, call the readNote tool with its path.">
|
||
|
|
${r}
|
||
|
|
</additionalMatches>`}function VVr(t){if(!Array.isArray(t)||t.length===0){F("Search Results: (none)");return}let e=0,r=t.map(u=>{let l=nje(u.mtime),c=typeof u.rerank_score=="number"?u.rerank_score:u.score||0,d=(Number.isFinite(c)?c:0).toFixed(4),f=u.chunkId||u.path||"",p=foi(u.explanation),m=u.includeInContext!==!1;return m&&e++,{path:f,in:m?"Y":"",mtime:l,score:d,explanation:p}}),n=r.length;F(`Search Results (debug table): ${n} rows; in-context ${e}/${n}`),sNt(r,["path","in","mtime","score","explanation"]);let o=u=>String(u||"").replace(/\|/g,"\\|"),i="| PATH | IN | MTIME | SCORE | EXPLANATION |",a="| --- | :-: | --- | ---: | --- |",s=r.map(u=>`| ${o(u.path)} | ${u.in} | ${u.mtime||""} | ${u.score} | ${o(u.explanation)} |`);xge(["",`Results: ${n} rows; in-context ${e}/${n}`,"",i,a,...s,""])}function HVr(t,e){return[t,e].map(n=>n?.trim()).filter(n=>!!n).join(`
|
||
|
|
|
||
|
|
`)}function WVr(t,e){let r=t?`
|
||
|
|
${t}
|
||
|
|
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${r}</localSearch>`}function jht(t,e){let r=t.trim();return r?`${r}
|
||
|
|
|
||
|
|
${e}`:e}function JVr(t,e){let r=e.trim();return!r||t.includes(r)?t:jht(t,`[User query]:
|
||
|
|
${r}`)}function KVr(t,e){let r=e?.trim();if(!r)return t;let o=t.lastIndexOf("[User query]:");if(o===-1){let s=t.trimEnd(),u=s.length>0?`
|
||
|
|
|
||
|
|
`:"";return`${s}${u}${r}`}let i=t.slice(0,o).trimEnd(),a=t.slice(o).trimStart();return`${i}
|
||
|
|
|
||
|
|
${r}
|
||
|
|
|
||
|
|
${a}`}function GVr(t){let e=[],r=0;for(;r<t.length;){let n=t.indexOf("![",r);if(n===-1)break;let o=goi(t,n+2);if(o===null){r=n+2;continue}let i=o+1;for(;i<t.length&&oje(t[i]);)i++;if(t[i]!=="("){r=i;continue}let a=yoi(t,i);if(a===null){r=i+1;continue}let s=moi(t.slice(i+1,a));s&&e.push(s),r=a+1}return e}function moi(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let n=boi(e,0);if(n===null)return null;let o=e.slice(1,n).trim();return o.length>0?o:null}let r=hoi(e).trim();return r.length>0?r:null}function hoi(t){let e=t.trimEnd();if(e.length===0)return"";let r=e[e.length-1];if(r==='"'||r==="'"){let o=_oi(e,r,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&oje(i[i.length-1]))return i.trimEnd()}}if(r===")"){let n=voi(e);if(n!==null){let o=e.slice(0,n);if(o.length>0&&oje(o[o.length-1]))return o.trimEnd()}}return e}function goi(t,e){let r=e,n=0;for(;r<t.length;){let o=t[r];if(o==="\\"){r+=2;continue}if(o==="["){n++,r++;continue}if(o==="]"){if(n===0)return r;n--,r++;continue}r++}return null}function yoi(t,e){let r=e+1,n=1,o=!0,i=!1;for(;r<t.length;){let a=t[r];if(i){if(a==="\\"){r+=2;continue}if(a===">"){i=!1,o=!1,r++;continue}r++;continue}if(o){if(oje(a)){r++;continue}if(a==="<"){i=!0,r++;continue}o=!1}if(a==="\\"){r+=2;continue}if(a==="("){n++,r++;continue}if(a===")"){if(n--,n===0)return r;r++;continue}r++}return null}function boi(t,e){for(let r=e+1;r<t.length;r++){let n=t[r];if(n==="\\"){r++;continue}if(n===">")return r}return null}function _oi(t,e,r){for(let n=r-1;n>=0;n--)if(t[n]===e&&!XVr(t,n))return n;return null}function voi(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let r=t.length-1;r>=0;r--){let n=t[r];if(!((n===")"||n==="(")&&XVr(t,r))){if(n===")"){e++;continue}if(n==="("&&(e--,e===0))return r}}return null}function XVr(t,e){let r=0;for(let n=e-1;n>=0&&t[n]==="\\";n--)r++;return r%2===1}function oje(t){return t===" "||t===" "||t===`
|
||
|
|
`||t==="\r"}function Mc(t){return typeof t!="string"?"":t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ZVr(t){return typeof t!="string"?"":t.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&")}ra();na();var QA=class extends PD{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let r=Uc.getInstance();return r.getAllTools().length===0&&HX(this.chainManager.app?.vault),r.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(r,n){let o=this.getAvailableToolsForPlanning();if(typeof n.bindTools!="function")return Ce("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(r)};let i=n.bindTools(o),s=[{role:ute(n),content:`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.
|
||
|
|
|
||
|
|
Guidelines:
|
||
|
|
- Use tools when the user's request requires external information or computation
|
||
|
|
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
|
||
|
|
- For file structure queries, use getFileTree to explore the vault
|
||
|
|
- If no tools are needed, respond with your analysis
|
||
|
|
|
||
|
|
After analyzing, extract key search terms from the user's message that would be useful for searching notes:
|
||
|
|
- Extract meaningful nouns, topics, and specific concepts
|
||
|
|
- Preserve the EXACT words and language from the user's message (works for any language)
|
||
|
|
- Exclude time expressions (those are handled by tools)
|
||
|
|
|
||
|
|
Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]`},{role:"user",content:r}];F("[CopilotPlus] Requesting tool planning with native tool calling...");let u;{let p=await Ib(()=>i.stream(s)),m;for await(let h of p)m=m?m.concat(h):h;if(!m)throw new Error("[CopilotPlus] Received empty response from planning model");u=new uo({content:m.content,tool_calls:m.tool_calls,additional_kwargs:m.additional_kwargs})}let l=u.tool_calls||[],c=typeof u.content=="string"?u.content:String(u.content);F("[CopilotPlus] Native tool calls:",l.length);let{salientTerms:d}=this.extractPlanningFieldsFromResponse(c,r),f=[];for(let p of l){let m=o.find(h=>h.name===p.name);m?(f.push({tool:m,args:p.args}),F(`[CopilotPlus] Tool call: ${p.name}`,p.args)):Ce(`[CopilotPlus] Tool '${p.name}' not found in available tools`)}return{toolCalls:f,salientTerms:d}}extractPlanningFieldsFromResponse(r,n){let o,i=r.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let a=i[1].split(",").map(s=>s.trim()).filter(s=>s.length>0);o=a.length>0?a:this.extractSalientTermsFromQuery(n)}else o=this.extractSalientTermsFromQuery(n);return{salientTerms:o}}extractSalientTermsFromQuery(r){return r.split(/[\s\p{P}]+/u).filter(n=>n.length>=3).slice(0,10)}async processAtCommands(r,n,o){let i=r.toLowerCase(),a=this.removeAtCommands(r),s=[...n];if(i.includes("@vault")&&(s.some(l=>l.tool.name==="localSearch")||s.push({tool:EDe,args:{query:a,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!s.some(l=>l.tool.name==="webSearch")){let c=await Vg.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=Mge(c);s.push({tool:PDe,args:{query:a,chatHistory:d}})}return i.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:CDe,args:{statement:a}})),s}removeAtCommands(r){return r.split(" ").filter(n=>!gX.includes(n.toLowerCase())).join(" ").trim()}async processImageUrls(r){let n=[],o=await uH.processUrlBatch(r,n,this.chainManager.app.vault);return uH.showFailedImagesNotice(n),o}async processChatInputImages(r){let n=[],o=await uH.processChatImageBatch(r,n,this.chainManager.app.vault);return uH.showFailedImagesNotice(n),o}async extractImagesFromContextBlock(r,n){let i=new RegExp(`<${n.tagName}>([\\s\\S]*?)<\\/${n.tagName}>`).exec(r);if(!i)return[];let a=i[1],u=/<content>([\s\S]*?)<\/content>/.exec(a),l=u?ZVr(u[1]):"";if(!l)return[];let d=new RegExp(`<${n.identifierTag}>(.*?)<\\/${n.identifierTag}>`).exec(a),f=d?d[1]:void 0;F(`[CopilotPlus] Extracting images from ${n.displayName}:`,f||`no ${n.identifierTag}`);let p=n.useForResolution?f:void 0;return this.extractEmbeddedImages(l,p)}async extractEmbeddedImages(r,n){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],a=[...r.matchAll(o)];for(let u of a){let l=u[1];if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):(Ce(`Could not resolve embedded image: ${l} from source: ${n}`),i.push(l))}else i.push(l)}let s=GVr(r);for(let u of s){if(!u)continue;if(u.match(/^https?:\/\//)){i.push(u);continue}let l=u.replace(/^\.\//,"").replace(/^\//,"");if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):i.push(l)}else i.push(l)}return i}async buildMessageContent(r,n){let o=[],i=[],a=ee(),s=[];if(a.passMarkdownImages){let d=n.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&s.push({urls:h,type:"embedded"})}}}for(let d of s){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let u=n.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let l=r;o.length>0&&(l=`${r}
|
||
|
|
|
||
|
|
Note:
|
||
|
|
${o.join(`
|
||
|
|
`)}
|
||
|
|
`);let c=[{type:"text",text:l}];return i.length>0&&c.push(...i),c}hasCapability(r,n){let o=r.modelName||r.model||"";return this.chainManager.chatModelManager.findModelByName(o)?.capabilities?.includes(n)??!1}isMultimodalModel(r){return this.hasCapability(r,"vision")}appendComposerInstructionsIfNeeded(r,n){if(!n.message||!n.message.includes("@composer"))return r;let o=`<OUTPUT_FORMAT>
|
||
|
|
${INt}
|
||
|
|
</OUTPUT_FORMAT>`;return`${r}
|
||
|
|
|
||
|
|
${o}`}async streamMultimodalResponse(r,n,o,i,a,s,u){let l=this.chainManager.memoryManager.getMemory(),c=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(c),f=[],p=n.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");F("[CopilotPlus] Using envelope-based context construction");let m=dA.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(w=>w.role==="system");h&&f.push({role:ute(c),content:h.content}),await mq(l,f);let y=m.find(w=>w.role==="user");if(y){let w,T=o.length>0,O=P=>{let R="[User query]:";if(P.includes(R))return P;let I=P.trimEnd(),A=[];I.length>0&&A.push(I);let B=s.trim()||n.originalMessage?.trim()||"";return B.length>0?A.push(`${R}
|
||
|
|
${B}`):A.push(R),A.join(`
|
||
|
|
|
||
|
|
`)};if(T){let P=this.formatAllToolOutputs(o),R=O(y.content);w=jht(P,R);let I=$zr(ee().enableInlineCitations);I&&(w=KVr(w,I))}else w=O(y.content);if(r.includes("<OUTPUT_FORMAT>")&&!w.includes("<OUTPUT_FORMAT>")){let P=r.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);P&&(w+=`
|
||
|
|
|
||
|
|
`+P[0])}let E=d?await this.buildMessageContent(w,n):w;f.push({role:"user",content:E})}F("Final request to AI",{messages:f.length});let g=c?.modelName;hq({messages:f,modelName:g,contextEnvelope:n.contextEnvelope});let b=new rje(w$,SDe),_=await Ib(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let w of _){if(i.signal.aborted){F("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let T of b.processChunk(w))a.processChunk(T)}}async run(r,n,o,i,a){let{updateLoadingMessage:s}=a,u=this.chainManager.chatModelManager.getChatModel(),c=!this.hasCapability(u,"reasoning"),d=new iv(o,c),f=[];if(!await m0({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let _=d.close().content;return this.handleResponse(_,r,n,i,o,void 0)}try{F("==== Step 1: Planning tools ====");let _,w=r.contextEnvelope;if(!w)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let O=w.layers.find(k=>k.id==="L5_USER")?.text||r.originalMessage||"";try{let k=this.chainManager.chatModelManager.getChatModel(),q=await this.planToolCalls(O,k),Z,V=q.toolCalls.find(X=>X.tool.name==="getTimeRangeMs");if(V){let X=await w$.callTool(V.tool,V.args),W=re=>re?.startTime?.epoch!==void 0&&re?.endTime?.epoch!==void 0?{startTime:re.startTime.epoch,endTime:re.endTime.epoch}:re;if(typeof X=="string")try{let re=JSON.parse(X);re.error||(Z=W(re))}catch{Ce("[CopilotPlus] Failed to parse getTimeRangeMs result:",X)}else X&&!X.error&&(Z=W(X));F("[CopilotPlus] Executed getTimeRangeMs, result:",Z)}let Y=q.toolCalls.filter(X=>X.tool.name==="getFileTree"&&ZJ()?(F("Skipping getFileTree in project mode"),!1):X.tool.name==="getTimeRangeMs"&&Z?(F("Skipping getTimeRangeMs - already executed during planning"),!1):!0);_=await this.processAtCommands(O,Y,{salientTerms:q.salientTerms,timeRange:Z})}catch(k){return this.handleResponse(pNt(k),r,n,i,o)}let E=r.contextEnvelope?.layers.find(k=>k.id==="L5_USER")?.text,P=this.removeAtCommands(E||r.originalMessage||r.message),{toolOutputs:R,sources:I}=await this.executeToolCalls(_,s);f=I;let A=R.filter(k=>k.output!=null),B=this.appendComposerInstructionsIfNeeded(P,r);F("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(B,r,A,n,d,P,s)}catch(_){s?.(iw.DEFAULT),_.name==="AbortError"||n.signal.aborted?F("CopilotPlus stream aborted by user",{reason:n.signal.reason}):await this.handleError(_,d.processErrorChunk.bind(d))}if(n.signal.aborted&&n.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,y={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},g=ee(),b=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(_=>({title:_.title,path:_.path}));return h=uDe(h,b,g.enableInlineCitations),await this.handleResponse(h,r,n,i,o,f,void 0,y),h}async executeToolCalls(r,n){let o=[],i=[],a=r.some(s=>s.tool.name==="localSearch");for(let s of r){if(s.tool.name==="getFileTree"&&a){F("Skipping getFileTree since localSearch is already active");continue}F(`Step 2: Calling tool: ${s.tool.name}`),s.tool.name==="localSearch"?n?.(iw.READING_FILES):s.tool.name==="webSearch"?n?.(iw.SEARCHING_WEB):s.tool.name==="getFileTree"&&n?.(iw.READING_FILE_TREE);let u=await w$.callTool(s.tool,s.args);if(s.tool.name==="localSearch"){let c={result:typeof u=="string"?u:JSON.stringify(u),success:u!=null},d=this.getTimeExpression(r),f=this.processLocalSearchResult(c,d);i.push(...f.sources),o.push({tool:s.tool.name,output:f.formattedForLLM})}else o.push({tool:s.tool.name,output:u})}return{toolOutputs:o,sources:LB(i)}}getTimeExpression(r){let n=r.find(o=>o.tool.name==="getTimeRangeMs");return n?n.args.timeExpression:""}prepareLocalSearchResult(r,n){let o=ee(),i=r.filter(R=>R.includeInContext!==!1),a=LVr(i),s=FVr(a),u=UVr(i),l=zVr(i),c,d;if(l){let R=[...i].sort((I,A)=>(A.mtime||0)-(I.mtime||0));c=R.slice(0,o.maxSourceChunks),d=R.slice(o.maxSourceChunks)}else u?(c=[],d=i):i.length>o.maxSourceChunks?(c=
|
||
|
|
|
||
|
|
${Dht(d)}`):u&&F(`Tag-only search: ${d.length} notes (metadata-only)`);let _=m.slice(0,Math.min(20,m.length)).map(R=>({title:R.title||R.path||"Untitled",path:R.path||R.title||""})),w=lDe(_);this.lastCitationSources=m.slice(0,Math.min(20,m.length)).map(R=>({title:R.title||R.path||"Untitled",path:R.path||void 0}));let T=Dzr(w,o.enableInlineCitations).trim(),E=HVr("Answer the question based only on the following context:",b),P=T?`${s}
|
||
|
|
|
||
|
|
${E}
|
||
|
|
|
||
|
|
${T}`:`${s}
|
||
|
|
|
||
|
|
${E}`;return WVr(P,n)}processLocalSearchResult(r,n){let o=[],i,a;if(!r.success)return i=`<localSearch>
|
||
|
|
Search failed.
|
||
|
|
</localSearch>`,a=`Search failed: ${r.result}`,{formattedForLLM:i,formattedForDisplay:a,sources:o};try{let s=JSON.parse(r.result),u=s&&typeof s=="object"&&s.type==="local_search"&&Array.isArray(s.documents)?s.documents:null;if(!Array.isArray(u))return i=`<localSearch>
|
||
|
|
Invalid search results format.
|
||
|
|
</localSearch>`,a="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:a,sources:o};VVr(u),o=qVr(u),i=this.prepareLocalSearchResult(u,n||""),a=S$.format("localSearch",i)}catch(s){Ce("Failed to parse localSearch results:",s);let u=kVr(r.result);i=n?`<localSearch timeRange="${n}">
|
||
|
|
${u}
|
||
|
|
</localSearch>`:`<localSearch>
|
||
|
|
${u}
|
||
|
|
</localSearch>`,a=S$.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:a,sources:o}}async getSystemPrompt(){return _$(this.chainManager.userMemoryManager)}formatAllToolOutputs(r){return r.length===0?"":`# Additional context:
|
||
|
|
|
||
|
|
`+r.map(o=>{let i=o.output;return typeof i!="string"&&(i=JSON.stringify(i)),`<${o.tool}>
|
||
|
|
${i}
|
||
|
|
</${o.tool}>`}).join(`
|
||
|
|
|
||
|
|
`)}};var _ce=class extends QA{};gr();Xe();id();Qe();Dt();ra();Xe();function qht(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
|
||
|
|
|
||
|
|
`)}var GW=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let r=[];for(let o of e)o.customPromptInstructions&&r.push(o.customPromptInstructions);let n=this.buildCopilotCommandInstructions(e);return n&&r.push(n),r.length>0?r.join(`
|
||
|
|
|
||
|
|
`):""}buildCopilotCommandInstructions(e){let r=[];for(let n of e)if(!(!n.copilotCommands||n.copilotCommands.length===0))for(let o of n.copilotCommands)r.push(`- ${o}: call the tool named ${n.id}`);return r.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...r,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
|
||
|
|
`)}enhanceSystemPrompt(e,r,n,o){let i=this.buildSystemPromptSections(e,r,n,o);return qht(i)}buildSystemPromptSections(e,r,n,o){let i=o||[],a=this.buildToolSpecificInstructions(i).trim(),u=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode
|
||
|
|
|
||
|
|
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
|
||
|
|
|
||
|
|
Tools are provided via native function calling - use them when needed to complete tasks.
|
||
|
|
`}],l=r.trim();return l.length>0&&u.push({id:"tool-descriptions",label:"Tool descriptions (native tool calling via bindTools)",source:"Native tool calling - schemas provided via bindTools()",content:`Available tools:
|
||
|
|
${l}`}),u.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# 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
|
||
|
|
|
||
|
|
## File-related Queries
|
||
|
|
|
||
|
|
### Handle ambiguity in folder/note paths
|
||
|
|
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
|
||
|
|
you MUST first call getFileTree to find the folder or notes best matching the user's query.
|
||
|
|
If multiple results or no result, you should ask the user to provide a more specific path.
|
||
|
|
`}),a.length>0&&u.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:a}),u.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## Answer Source Priority (CRITICAL)
|
||
|
|
You are the user's personal knowledge assistant. Always ground your answers in real sources rather than your own training data. Follow this priority chain:
|
||
|
|
|
||
|
|
1. **Explicit context first.** If the user has attached notes, documents, URLs, YouTube transcripts, tweets, or any other content to the conversation, use that content as your primary source. The user added it for a reason.
|
||
|
|
2. **Vault second.** For any question that could plausibly be answered by the user's notes, search the vault (localSearch). The user's own writing, meeting notes, journal entries, and saved references are highly valuable.
|
||
|
|
3. **Web third.** If the vault has no relevant results, or the question is about external/current information the vault is unlikely to contain, search the web.
|
||
|
|
4. **Your own knowledge last.** Only fall back on your training data when all of the above have been exhausted or are clearly inapplicable (e.g., explaining a general concept, writing code, or creative tasks that don't need source material).
|
||
|
|
|
||
|
|
When in doubt, search the vault. It is always better to check and find nothing than to skip the search and miss relevant notes.
|
||
|
|
|
||
|
|
## General Guidelines
|
||
|
|
- 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.
|
||
|
|
|
||
|
|
## Citation Integrity (CRITICAL)
|
||
|
|
- ONLY cite sources from tools you ACTUALLY called and received results from
|
||
|
|
- NEVER fabricate or hallucinate search results, web searches, or any tool outputs
|
||
|
|
- If you did not call a tool, do not claim you did or cite results from it
|
||
|
|
- Each citation must correspond to a real document or result returned by a tool in this conversation`}),u}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},$ht=class extends GW{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),a=n||[],s=a.includes("writeFile")||a.includes("editFile"),u=[];this.isGPT5Model()?u.push(`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`):u.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user's request requires them. Do not just describe what you plan to do - actually call the tools."),s&&u.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \u{1F6A8}
|
||
|
|
|
||
|
|
When user asks you to edit or modify a file, you MUST:
|
||
|
|
1. Determine if it's a small edit (use editFile) or major rewrite (use writeFile)
|
||
|
|
2. Call the tool immediately - do not just describe what you plan to do
|
||
|
|
|
||
|
|
For editFile, pass the exact text to find and its replacement:
|
||
|
|
- path: vault-relative file path
|
||
|
|
- oldText: exact text to find (include surrounding context lines to make it unique)
|
||
|
|
- newText: replacement text (empty string to delete)
|
||
|
|
|
||
|
|
\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
|
||
|
|
\u2705 CORRECT: Actually call editFile or writeFile with proper parameters`),u.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let l=u.join(`
|
||
|
|
|
||
|
|
`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:l}),i}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: Call the localSearch tool now.`:i?`${e}
|
||
|
|
|
||
|
|
\u{1F6A8} GPT REMINDER: Use editFile for small edits (oldText/newText parameters) or writeFile for full rewrites.`:e}needsSpecialHandling(){return!0}},Lht=class extends GW{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")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);if(!this.isThinkingModel())return i;let a=[`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
|
||
|
|
- Call tools AFTER your thinking is complete
|
||
|
|
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
|
||
|
|
|
||
|
|
CORRECT FLOW FOR THINKING MODELS:
|
||
|
|
1. Think through the problem (this happens automatically)
|
||
|
|
2. Use tools to gather information
|
||
|
|
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.push(`\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
|
||
|
|
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 PATTERN:
|
||
|
|
I'll search your vault for piano practice information.
|
||
|
|
[Call localSearch tool]
|
||
|
|
[RESPONSE ENDS HERE - NO MORE TEXT]
|
||
|
|
|
||
|
|
\u274C WRONG PATTERN (DO NOT DO THIS):
|
||
|
|
[Call 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.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:a.join(`
|
||
|
|
|
||
|
|
`)}),i}needsSpecialHandling(){return this.isThinkingModel()}},Fht=class extends GW{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),u=[`\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: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return u.push(`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
|
||
|
|
|
||
|
|
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
|
||
|
|
|
||
|
|
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
|
||
|
|
1. Call the FIRST tool
|
||
|
|
2. STOP and wait for the result
|
||
|
|
3. In the NEXT response, use the result from step 1 in the SECOND tool call
|
||
|
|
|
||
|
|
\u274C WRONG (DO NOT DO THIS):
|
||
|
|
User: "Recap my last week"
|
||
|
|
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
|
||
|
|
- This is WRONG because you're hallucinating the timeRange values!
|
||
|
|
|
||
|
|
\u2705 CORRECT (DO THIS):
|
||
|
|
User: "Recap my last week"
|
||
|
|
- FIRST: Call getTimeRangeMs with timeExpression "last week"
|
||
|
|
- WAIT for result
|
||
|
|
- SECOND: Call localSearch using the actual timeRange from the result
|
||
|
|
|
||
|
|
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
|
||
|
|
|
||
|
|
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:u.join(`
|
||
|
|
|
||
|
|
`)}),i}enhanceUserMessage(e,r){return r?`${e}
|
||
|
|
|
||
|
|
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},kht=class extends GW{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}
|
||
|
|
|
||
|
|
You are a Copilot Plus model. You MUST follow these rules strictly:
|
||
|
|
|
||
|
|
## Tool Call Integrity
|
||
|
|
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
|
||
|
|
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
|
||
|
|
- NEVER claim to have searched notes unless you called localSearch AND received results
|
||
|
|
- If you want to search the web, you MUST call the webSearch tool first - do not make up results
|
||
|
|
|
||
|
|
## Citation Rules
|
||
|
|
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
|
||
|
|
- Do NOT invent sources like "General web search results for X" unless webSearch was actually called
|
||
|
|
- If you only called localSearch, your citations can ONLY reference notes from that search
|
||
|
|
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools
|
||
|
|
|
||
|
|
## Before Writing Citations
|
||
|
|
Ask yourself: "Did I actually call this tool and receive this result?"
|
||
|
|
- If YES: You may cite it
|
||
|
|
- If NO: Do NOT cite it or claim you did
|
||
|
|
|
||
|
|
REMEMBER: It is better to say "I only searched your notes, not the web" than to fabricate web search results.
|
||
|
|
|
||
|
|
## Formatting Guidelines
|
||
|
|
- AVOID using markdown tables - they often render poorly in chat interfaces
|
||
|
|
- Instead of tables, use bullet points, numbered lists, or simple formatted text
|
||
|
|
- Only use tables when the user explicitly requests tabular format`}),i}needsSpecialHandling(){return!0}},vce=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(F(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new $ht(r);return n.isGPT5Model()?F("Using GPTModelAdapter with GPT-5 specific enhancements"):F("Using GPTModelAdapter"),n}return r.includes("claude")?(F("Using ClaudeModelAdapter"),new Lht(r)):r.includes("gemini")||r.includes("google/gemini")?(F("Using GeminiModelAdapter"),new Fht(r)):r.includes("copilot-plus")?(F("Using CopilotPlusModelAdapter"),new kht(r)):(F("Using BaseModelAdapter (default)"),new GW(r))}};function YVr(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))}function woi(t){let{systemSections:e,rawHistory:r,adapterName:n,originalUserMessage:o,enhancedUserMessage:i}=t,a=[...e];if(r&&r.length>0){let u=kat(r);if(u.length>0){let c=n_r(u).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
|
||
|
|
${d.content}`);a.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:c.join(`
|
||
|
|
|
||
|
|
`)})}}a.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let s=i===o?" (unchanged)":"";return a.push({id:"user-enhanced-message",label:`User message after ${n}.enhanceUserMessage${s}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${n}.enhanceUserMessage`,content:i}),a}function Soi(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
|
||
|
|
${e.content}`).join(`
|
||
|
|
|
||
|
|
`)}function QVr(t){let e=woi(t),r=Soi(e),n=qht(t.systemSections);return{sections:e,annotatedPrompt:r,systemPrompt:n}}async function Coi(t){let{chainManager:e,adapter:r,basePrompt:n,toolDescriptions:o,toolNames:i,toolMetadata:a,userMessage:s}=t,u=r.buildSystemPromptSections(n,o,i,a),c=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(c.history)?c.history:[],f=s.originalMessage||s.message,p=YVr(s.message),m=r.enhanceUserMessage(s.message,p);return QVr({systemSections:u,rawHistory:d,adapterName:r.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function xoi(t){return _$(t.userMemoryManager)}async function eHr(t){let{chainManager:e,adapter:r,availableTools:n,toolDescriptions:o,userMessage:i}=t,a=Uc.getInstance(),s=n.map(c=>c.name),u=n.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0),l=await xoi(e);return Coi({chainManager:e,adapter:r,basePrompt:l,toolDescriptions:o,toolNames:s,toolMetadata:u,userMessage:i})}function tHr(){return{status:"idle",startTime:null,elapsedSeconds:0,steps:[]}}function Bht(t){if(t.status==="idle")return"";let e=JSON.stringify(t.steps.map(r=>r.summary));return`<!--AGENT_REASONING:${t.status}:${t.elapsedSeconds}:${e}-->`}function wce(t){let e=t.match(/<!--AGENT_REASONING:(\w+):(\d+):(.+?)-->/);if(!e)return null;let[r,n,o,i]=e,a=[];try{a=JSON.parse(i)}catch{a=[]}return{hasReasoning:!0,status:n,elapsedSeconds:parseInt(o,10),steps:a,contentAfter:t.replace(r,"").trim()}}function rHr(t,e,r,n){if(!e.success)return`${Uht(t,n)} failed`;switch(t){case"localSearch":{if(r&&r.count>0){let o=r.titles.slice(0,3),i=r.count-o.length,a=`Found ${r.count} note${r.count!==1?"s":""}: ${o.join(", ")}`;return i>0&&(a+=` +${i} more`),a}return"No matching notes found"}case"webSearch":return"Retrieved web search results";case"getTimeRangeMs":return"Calculated time range";case"readFile":return"Read file content";case"readNote":{let o=n?.notePath;return o?`Read "${o.split("/").pop()?.replace(/\.md$/i,"")||o}"`:"Read note content"}case"createNote":return"Created new note";case"appendToNote":return"Appended to note";case"editNote":return"Edited note";case"deleteNote":return"Deleted note";case"youtubeTranscript":case"youtubeTranscription":return"Fetched video transcript";case"fetchUrl":return"Fetched URL content";case"getFileTree":return"Retrieved vault file tree";case"getTagList":return"Retrieved vault tags";case"getCurrentTime":return"Got current time";case"getTimeInfoByEpoch":return"Converted timestamp";case"convertTimeBetweenTimezones":return"Converted timezone";case"obsidianDailyNote":{let o=n?.command,i=n?.vault,a=i&&i.trim().length>0?` from "${i}"`:"";return o==="daily:path"?`Got daily note path${a}`:`Loaded today's daily note${a}`}case"obsidianRandomRead":{let o=n?.vault;return o&&o.trim().length>0?`Loaded a random note from "${o}"`:"Loaded a random note"}case"obsidianProperties":{if(n?.command==="property:read"){let i=n?.name;return i?`Read property "${i}"`:"Read property"}return"Listed vault properties"}case"obsidianTasks":return"Listed vault tasks";case"obsidianLinks":{let o=n?.command;return o==="backlinks"?"Listed backlinks":o==="links"?"Listed outgoing links":o==="orphans"?"Listed orphaned notes":o==="unresolved"?"Listed unresolved links":"Queried link graph"}case"obsidianTemplates":{if(n?.command==="template:read"){let i=n?.name;return i?`Read template "${i}"`:"Read template"}return"Listed templates"}case"obsidianBases":{let o=n?.command;return o==="base:views"?"Listed base views":o==="base:query"?"Queried base data":"Listed bases"}case"indexVault":return"Indexed vault";case"updateMemory":return"Updated memory";case"writeFile":case"editFile":{let o=n?.path,i=o?o.split("/").pop()||o:"file",a=e.result||"";return a.includes('"rejected"')||a.includes("rejected")?`Edit rejected for "${i}"`:a.includes('"failed"')||a.includes("Error")?`Edit failed for "${i}"`:t==="writeFile"?`Wrote to "${i}"`:`Edited "${i}"`}default:return"Done"}}function Uht(t,e,r){switch(t){case"localSearch":{if(r&&r.recallTerms&&r.recallTerms.length>0){let o=r.recallTerms.filter(i=>typeof
|
||
|
|
`)[0];return Toi(e,100)}function Ooi(t,e){let r=new Set(t.toLowerCase().split(/\s+/).filter(Boolean)),n=new Set(e.toLowerCase().split(/\s+/).filter(Boolean));if(r.size===0&&n.size===0)return 1;if(r.size===0||n.size===0)return 0;let o=0;for(let u of r)n.has(u)&&o++;let i=r.size+n.size-o,a=o/i,s=o/Math.min(r.size,n.size);return Math.max(a,s)}function zht(t,e,r=.6){for(let n of e)if(Ooi(t,n)>=r)return n;return null}var Eoi=/^(user|assistant|system)\s*$/;function oHr(t){return t&&t.split(`
|
||
|
|
`).filter(e=>!Eoi.test(e)).join(`
|
||
|
|
`)}var iHr=`## Agent Behavior
|
||
|
|
- You have a limited number of tool calls. Use them wisely.
|
||
|
|
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
|
||
|
|
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
|
||
|
|
- If you have enough information to answer, respond directly without calling any more tools.`,Sce=class extends QA{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=tHr();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let r=ee(),n=Uc.getInstance();n.getAllTools().length===0&&HX(this.chainManager.app?.vault);let o=new Set(r.autonomousAgentEnabledToolIds||[]);return n.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(r,n){this.reasoningState={status:"reasoning",startTime:Date.now(),elapsedSeconds:0,steps:[]},this.accumulatedContent="",this.allReasoningSteps=[],this.abortHandledByTimer=!1;let o=["Understanding your question","Analyzing your request","Processing your query","Thinking about this","Considering your question","Working on this","Pondering the possibilities","Diving into your request","Let me think about this","Exploring your question","Getting my thoughts together","Examining the details","Looking into this","Mulling this over","On it","Firing up the neurons","Connecting the dots","Brewing some ideas","Spinning up the gears","Warming up the engines","Crunching the details","Putting on my thinking cap","Consulting my notes","Gathering my thoughts","Rolling up my sleeves"],i=o[Math.floor(Math.random()*o.length)];this.addReasoningStep(i),this.reasoningTimerInterval=setInterval(()=>{if(n?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let a=this.buildReasoningBlockMarkup(),s="The response was interrupted.",u=a?a+`
|
||
|
|
|
||
|
|
`+s:s;r(u);return}if(this.reasoningState.startTime&&this.reasoningState.status==="reasoning"){this.reasoningState.elapsedSeconds=Math.floor((Date.now()-this.reasoningState.startTime)/1e3);let a=this.buildReasoningBlockMarkup(),s=a?a+(this.accumulatedContent?`
|
||
|
|
|
||
|
|
`+this.accumulatedContent:""):this.accumulatedContent;r(s)}},100)}addReasoningStep(r,n,o=!1){let i={timestamp:Date.now(),summary:r,toolName:n};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let r={...this.reasoningState,steps:this.allReasoningSteps};return Bht(r)}return Bht(this.reasoningState)}static async generateSystemPrompt(r,n,o){let i=await _$(o),a=Uc.getInstance(),u=r.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0).filter(c=>c.customPromptInstructions).map(c=>`For ${c.displayName}: ${c.customPromptInstructions}`).join(`
|
||
|
|
`),l=[i];return u&&l.push(`## Tool Guidelines
|
||
|
|
${u}`),l.push(iHr),l.join(`
|
||
|
|
|
||
|
|
`)}async buildToolPromptDebugReport(r){let n=this.getAvailableTools(),o=vce.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=n.map(a=>`${a.name}: ${a.description}`).join(`
|
||
|
|
`);return eHr({chainManager:this.chainManager,adapter:o,availableTools:n,toolDescriptions:i,userMessage:r})}applyCiCOrderingToLocalSearchResult(r,n){return JVr(r,n)}async run(r,n,o,i,a){this.llmFormattedMessages=[],this.lastDisplayedContent="";let s=await m0({isAutonomousAgent:!0}),u=this.chainManager.chatModelManager.getChatModel(),l=vce.createAdapter(u),c=new iv(o,!0);if(!s){await this.handleError(new Error("Invalid license key"),c.processErrorChunk.bind(c));let m=c.close().content;return this.handleResponse(m,r,n,i,o,void 0)}let d=u?.modelName;if(!r.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");F("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(r,u,a.updateLoadingMessage);try{this.startReasoningTimer(o,n);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,chatModel:u,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:n,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:l});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=LB(m.sources);return p.messages.length>0&&hq({messages:[...p.messages],modelName:d,contextEnvelope:r.contextEnvelope}),await this.handleResponse(m.finalResponse,r,n,i,o,h.length>0?h:void 0,this.llmFormattedMessages.join(`
|
||
|
|
|
||
|
|
`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||n.signal.aborted)return F("Autonomous agent stream aborted by user",{reason:n.signal.reason}),"";ie("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new QA(this.chainManager).run(r,n,o,i,a)}catch(h){ie("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&c.processChunk({content:this.lastDisplayedContent});let y=Wr(m),g=`
|
||
|
|
|
||
|
|
Fallback to regular Plus mode also failed: `+Wr(h);await this.handleError(new Error(y+g),c.processErrorChunk.bind(c));let b=c.close().content;return this.handleResponse(b,r,n,i,o,void 0,b)}}}async prepareAgentConversation(r,n,o){let i=[],a=this.getAvailableTools(),s=n.modelName||n.model||"unknown";if(typeof n.bindTools!="function")throw new Error(`Model ${s} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let u=n.bindTools(a),l={availableTools:a,boundModel:u,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},c=r.contextEnvelope,d=dA.convert(c,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(E=>E.role==="system"),m=Uc.getInstance(),y=a.map(E=>m.getToolMetadata(E.name)).filter(E=>E!==void 0).filter(E=>E.customPromptInstructions).map(E=>`For ${E.displayName}: ${E.customPromptInstructions}`).join(`
|
||
|
|
`),g=[p?.content||"",y?`
|
||
|
|
## Tool Guidelines
|
||
|
|
${y}`:"",iHr].filter(Boolean).join(`
|
||
|
|
|
||
|
|
`);g&&i.push(new v_({content:g}));let w=c.layers.find(E=>E.id==="L5_USER")?.text||""||r.originalMessage||r.message,T=[];await mq(f,T);for(let E of T)E.role==="user"?i.push(new Au(E.content)):i.push(new uo(E.content));let O=d.find(E=>E.role==="user");if(O){let P=this.isMultimodalModel(n)?await this.buildMessageContent(O.content,r):O.content;i.push(new Au(P))}return{messages:i,collectedSources:[],originalUserPrompt:w,loopDeps:l}}async runReActLoop(r){let{boundModel:n,tools:o,messages:i,originalPrompt:a,abortController:s,updateCurrentAiMessage:u,processLocalSearchResult:l,applyCiCOrderingToLocalSearchResult:c}=r,d=ee().autonomousAgentMaxIterations,f=[],p=Date.now(),m=[],h=0,y=0,g;for(;y<d&&!s.signal.aborted;){let E=Date.now()-p;if(E>=o3e){Ce(`Agent loop timed out after ${Math.round(E/1e3)}s`);break}y++;let{content:P,aiMessage:R,streamingResult:I}=await this.streamModelResponse(n,i,s,u);g={wasTruncated:I.wasTruncated,tokenUsage:I.tokenUsage??void 0};let A=P?.trim();F(`[Agent] Iteration ${y} model output:`,A?A.slice(0,200):"(empty)");let B=R.tool_calls||[];if(F(`[Agent] Iteration ${y}: ${B.length} tool call(s)`),B.length===0){F(`[Agent] Iteration ${y}: Final response (no tool calls)`),this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(R);let X=P;if(!X||X.trim()===""){let J=R.tool_call_chunks??[];Ce(`[Agent] Empty response detected (iteration ${y}). Content length: ${P?.length??0}, tool_call_chunks from model: ${J.length}, parsed tool_calls: ${B.length}. This may indicate tool calls were dropped or the model produced only thinking tokens.`),X="The model did not produce a response. Please try again or switch to a different model."}let W=this.buildReasoningBlockMarkup(),re=20,ue=5,le="";for(let J=0;J<X.length&&!s.signal.aborted;J+=re){le+=X.slice(J,J+re);let ne=W?W+`
|
||
|
|
|
||
|
|
`+le:le;u(ne),J+re<X.length&&await new Promise(D=>setTimeout(D,ue))}let L=W?W+`
|
||
|
|
|
||
|
|
`+X:X;return u(L),{finalResponse:L,sources:f,responseMetadata:g}}let k=oHr(P),q=new uo({content:k,tool_calls:R.tool_calls});if(i.push(q),y>1&&k&&k.trim().length>0){let X=nHr(k);X&&this.addReasoningStep(X)}let Z=[],V=[],Y=[];for(let X of B){if(X.name==="localSearch"){let W=X.args?.query;if(W){let re=zht(W,m)??zht(W,V);if(re){F(`[Agent] Dedup: "${W}" (similar to: "${re}")`),i.push(cEe(X.id||cae(),X.name,`You already searched for a similar query: "${re}". Synthesize your answer from existing results.`));continue}V.push(W),Y.push(W)}else Y.push(null)}else Y.push(null);Z.push(X)}for(let X=0;X<Z.length;X++){let W=Z[X];if(s.signal.aborted)break;let re={name:W.name,args:W.args},ue=Uht(W.name,re.args);this.addReasoningStep(ue,W.name),Tmt(re,y);let le=await Cmt(re,o,a),L;if(W.name==="localSearch"&&le.success){let D=l(le);f.push(...D.sources),L={titles:D.sources.map(N=>N.title),count:D.sources.length},le.result=c(D.formattedForLLM,a||"")}if(Omt(W.name,le),W.name==="localSearch"&&le.success){let D=Y[X];D&&m.push(D)}let J=rHr(W.name,le,L,re.args);(!le.success||L)&&this.addReasoningStep(J,W.name);let ne=cEe(W.id||cae(),W.name,le.result);i.push(ne)}if(Z.length===0&&B.length>0){if(h++,F(`[Agent] All ${B.length} tool call(s) skipped as duplicates (${h} consecutive)`),h>=2){F("[Agent] Model stuck in search loop, forcing synthesis without tools"),this.addReasoningStep("Synthesizing answer from search results"),i.push(new Au(`You have already searched and found relevant results. Do not call any tools. Answer the following question now based ONLY on the search results above:
|
||
|
|
|
||
|
|
`+a));let X=await this.streamModelResponse(r.chatModel,i,s,u);g={wasTruncated:X.streamingResult.wasTruncated,tokenUsage:X.streamingResult.tokenUsage??void 0},this.stopReasoningTimer(),this.reasoningState.status="complete";let W=this.buildReasoningBlockMarkup(),re=X.content||"Unable to synthesize a response from the search results.",ue=W?W+`
|
||
|
|
|
||
|
|
`+re:re;return u(ue),{finalResponse:ue,sources:f,responseMetadata:g}}}else h=0}this.stopReasoningTimer(),this.reasoningState.status="complete";let b=this.buildReasoningBlockMarkup();if(s.signal.aborted){if(F("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:g};let E="The response was interrupted.";return{finalResponse:b?b+`
|
||
|
|
|
||
|
|
`+E:E,sources:f,responseMetadata:g}}let _=Date.now()-p,w=_>=o3e;w?Ce(`Agent loop timed out after ${Math.round(_/1e3)}s`):Ce(`Agent reached max iterations (${d})`);let T=w?"I've reached the time limit for reasoning. Here's what I found so far based on the search results.":"I've reached the maximum number of tool calls. Here's what I found so far based on the search results.";return{finalResponse:b?b+`
|
||
|
|
|
||
|
|
`+T:T,sources:f,responseMetadata:g}}async streamModelResponse(r,n,o,i){let a=new Map,s=new iv(()=>{},!0),u="";try{let l=await Ib(()=>r.stream(n,{signal:o.signal}));for await(let y of l){if(o.signal.aborted)break;if(y.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw Ce("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let b=y.tool_call_chunks;if(b&&Array.isArray(b))for(let w of b)a_r(a,w);let _=typeof y.content=="string"?y.content:"";_&&(u+=_),s.processChunk(y)}let c=s.close(),d=c.content,f=u.trim(),p=d.trim();f&&!p&&F(`[Agent] Model produced content that was entirely stripped (likely think blocks): ${f.slice(0,300)}`);let m=dEe(a),h=new uo({content:d,tool_calls:m.map(y=>({id:y.id,name:y.name,args:y.args,type:"tool_call"}))});return{content:d,aiMessage:h,streamingResult:c}}catch(l){if(ie(`Stream error: ${l.message}`),l.name==="AbortError"||o.signal.aborted){let c=s.close();return{content:c.content,aiMessage:new uo({content:c.content}),streamingResult:c}}throw l}}};Xe();Qe();Dt();OS();TS();var eWr=require("obsidian");LW();var WX=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],ije=new Map;for(let t of WX)ije.set(t.tag,t);function XW(t){return ije.get(t)?.sourceType??"unknown"}function aje(t){return ije.get(t)?.recoverable??!1}function JX(t,e){let r=ije.get(e);if(!r?.sourceExtractor)return"";let n=r.sourceExtractor;return new RegExp(`<${n}>([^<]+)</${n}>`).exec(t)?.[1]??""}function Cce(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}var Xw={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function ZW(t,e=500,r=20){let n=t.split(/(?=^#{1,6}\s+)/m).filter(s=>s.trim());if(n.length<=1)return Vht(t,e*4);let o=n.slice(0,r),i=n.length>r,a=o.map(s=>{let u=s.trim().split(`
|
||
|
|
`),l=u[0],c=u.slice(1).join(`
|
||
|
|
`).trim();return c.length<=e?s.trim():`${l}
|
||
|
|
${Vht(c,e)}`}).join(`
|
||
|
|
|
||
|
|
`);return i?`${a}
|
||
|
|
|
||
|
|
[... ${n.length-r} more sections omitted ...]`:a}function Vht(t,e){if(t.length<=e)return t;let r=t.slice(0,e),n=/[.!?]\s+/g,o=-1,i;for(;(i=n.exec(r))!==null;)i.index>e*.5&&(o=i.index+1);if(o>0)return r.slice(0,o)+" ...";let a=r.lastIndexOf(`
|
||
|
|
|
||
|
|
`);if(a>e*.5)return r.slice(0,a)+`
|
||
|
|
|
||
|
|
...`;let s=r.lastIndexOf(" ");return s>e*.8?r.slice(0,s)+" ...":r+"..."}function sje(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function Poi(){return["localSearch","note_context","active_note","retrieved_document","url_content","youtube_video_context"].map(e=>({pattern:new RegExp(`<${e}[^>]*>[\\s\\S]*?</${e}>`,"g"),tag:e}))}var Moi=Poi(),KX="Tool 'readNote' result: ";function Roi(t,e){if(t[e]!=="{")return null;let r=0,n=!1,o=!1;for(let i=e;i<t.length;i++){let a=t[i];if(o){o=!1;continue}if(a==="\\"&&n){o=!0;continue}if(a==='"'){n=!n;continue}if(!n){if(a==="{")r++;else if(a==="}"&&(r--,r===0))return{json:t.slice(e,i+1),endPos:i+1}}}return null}function YW(t,e={}){return Array.isArray(t)?t.map(r=>r.type==="text"&&typeof r.text=="string"?{...r,text:aHr(r.text,e)}:r):typeof t=="string"?aHr(t,e):t}function aHr(t,e={}){let r=e.verbatimThreshold??Xw.verbatimThreshold,n=t;for(let{pattern:o,tag:i}of Moi)o.lastIndex=0,n=n.replace(o,a=>a.length<r?a:Aoi(a,i,e));return n=Ioi(n,r,e),n}function Ioi(t,e,r){let n="",o=0;for(;o<t.length;){let i=t.indexOf(KX,o);if(i===-1){n+=t.slice(o);break}n+=t.slice(o,i);let a=i+KX.length,s=Roi(t,a);if(!s){n+=KX,o=a;continue}try{let u=JSON.parse(s.json);if(u.content&&u.content.length>e){let l=Doi(u,r);n+=`${KX}${JSON.stringify(l)}`}else n+=KX+s.json}catch{n+=KX+s.json}o=s.endPos}return n}function Aoi(t,e,r={}){if(!aje(e))return t;if(e==="localSearch")return Noi(t,r);let n=JX(t,e),o=Cce(t),i=XW(e),a=r.previewCharsPerSection??Xw.previewCharsPerSection,s=r.maxSections??Xw.maxSections,u=ZW(o,a,s);return`<prior_context source="${sje(n)}" type="${i}">
|
||
|
|
${u}
|
||
|
|
</prior_context>`}function Noi(t,e={}){let r=e.previewCharsPerSection??Xw.previewCharsPerSection,n=/<document>([\s\S]*?)<\/document>/g,o=[],i;for(;(i=n.exec(t))!==null;){let s=i[1],u=/<path>([^<]+)<\/path>/.exec(s),l=/<title>([^<]+)<\/title>/.exec(s),c=/<content>([\s\S]*?)<\/content>/.exec(s),d=u?.[1]??"",f=l?.[1]??d.split("/").pop()??"Untitled",p=c?.[1]??"",m=p.length>r?p.slice(0,r)+"...":p;o.push({path:d,title:f,preview:m.trim()})}if(o.length===0){let s=Cce(t);return`<prior_context source="localSearch" type="note">
|
||
|
|
${ZW(s,r,e.maxSections??Xw.maxSections)}
|
||
|
|
</prior_context>`}let a=o.map((s,u)=>`${u+1}. [[${s.title}]] (${s.path})
|
||
|
|
${s.preview}`).join(`
|
||
|
|
|
||
|
|
`);return`<prior_context source="localSearch" type="note">
|
||
|
|
[${o.length} search results - use localSearch to re-query]
|
||
|
|
|
||
|
|
${a}
|
||
|
|
</prior_context>`}function Doi(t,e={}){let{content:r,notePath:n,noteTitle:o,...i}=t;if(!r||typeof r!="string")return t;let a=e.previewCharsPerSection??Xw.previewCharsPerSection,s=e.maxSections??Xw.maxSections,u=ZW(r,a,s);return{...i,notePath:n,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
|
||
|
|
|
||
|
|
${u}`,_wasCompacted:!0}}Qe();hge();TS();var joi=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.
|
||
|
|
|
||
|
|
EXAMPLE
|
||
|
|
Current summary:
|
||
|
|
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.
|
||
|
|
|
||
|
|
New lines of conversation:
|
||
|
|
Human: Why do you think artificial intelligence is a force for good?
|
||
|
|
AI: Because artificial intelligence will help humans reach their full potential.
|
||
|
|
|
||
|
|
New summary:
|
||
|
|
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
|
||
|
|
END OF EXAMPLE
|
||
|
|
|
||
|
|
Current summary:
|
||
|
|
{summary}
|
||
|
|
|
||
|
|
New lines of conversation:
|
||
|
|
{new_lines}
|
||
|
|
|
||
|
|
New summary:`,sHr=new Ku({inputVariables:["summary","new_lines"],template:joi}),$oi=`You are an assistant to a human, powered by a large language model trained by OpenAI.
|
||
|
|
|
||
|
|
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
|
||
|
|
|
||
|
|
You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.
|
||
|
|
|
||
|
|
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
|
||
|
|
|
||
|
|
Context:
|
||
|
|
{entities}
|
||
|
|
|
||
|
|
Current conversation:
|
||
|
|
{history}
|
||
|
|
Last line:
|
||
|
|
Human: {input}
|
||
|
|
You:`,uHr=new Ku({inputVariables:["entities","history","input"],template:$oi}),Loi=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
|
||
|
|
|
||
|
|
The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.
|
||
|
|
|
||
|
|
Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).
|
||
|
|
|
||
|
|
EXAMPLE
|
||
|
|
Conversation history:
|
||
|
|
Person #1: my name is Jacob. how's it going today?
|
||
|
|
AI: "It's going great! How about you?"
|
||
|
|
Person #1: good! busy working on Langchain. lots to do.
|
||
|
|
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
|
||
|
|
Last line:
|
||
|
|
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
|
||
|
|
Output: Jacob,Langchain
|
||
|
|
END OF EXAMPLE
|
||
|
|
|
||
|
|
EXAMPLE
|
||
|
|
Conversation history:
|
||
|
|
Person #1: how's it going today?
|
||
|
|
AI: "It's going great! How about you?"
|
||
|
|
Person #1: good! busy working on Langchain. lots to do.
|
||
|
|
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
|
||
|
|
Last line:
|
||
|
|
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
|
||
|
|
Output: Langchain, Person #2
|
||
|
|
END OF EXAMPLE
|
||
|
|
|
||
|
|
Conversation history (for reference only):
|
||
|
|
{history}
|
||
|
|
Last line of conversation (for extraction):
|
||
|
|
Human: {input}
|
||
|
|
|
||
|
|
Output:`,lHr=new Ku({inputVariables:["history","input"],template:Loi}),Foi=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
|
||
|
|
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.
|
||
|
|
|
||
|
|
If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.
|
||
|
|
|
||
|
|
Full conversation history (for context):
|
||
|
|
{history}
|
||
|
|
|
||
|
|
Entity to summarize:
|
||
|
|
{entity}
|
||
|
|
|
||
|
|
Existing summary of {entity}:
|
||
|
|
{summary}
|
||
|
|
|
||
|
|
Last line of conversation:
|
||
|
|
Human: {input}
|
||
|
|
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,cHr=new Ku({inputVariables:["entity","summary","history","input"],template:Foi});hge();zo();DL();mS();LL();ra();var koi=class extends b_{addUserMessage(t){return this.addMessage(new Au(t))}addAIMessage(t){return this.addMessage(new uo(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},uje=class extends koi{constructor(e){super(...arguments);x(this,"lc_namespace",["langchain","stores","message","in_memory"]);x(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};zo();var GX=class{},dHr=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},XX=(t,e)=>{let r=dHr(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},lje=(t,e)=>{let r=dHr(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};function Hht(t,e){let r=Object.keys(t).filter(n=>!e.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var qoi={};OJ(qoi,{BaseChatMemory:()=>t_});var t_=class extends GX{constructor(e){super();x(this,"chatHistory");x(this,"returnMessages",!1);x(this,"inputKey");x(this,"outputKey");this.chatHistory=e?.chatHistory??new uje,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(XX(e,this.inputKey)),await this.chatHistory.addAIMessage(lje(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};QW();ra();var Mce=class extends t_{constructor(e){let{returnMessages:r,inputKey:n,outputKey:o,chatHistory:i,humanPrefix:a,aiPrefix:s,llm:u,prompt:l,summaryChatMessageClass:c}=e;super({returnMessages:r,inputKey:n,outputKey:o,chatHistory:i});x(this,"memoryKey","history");x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"llm");x(this,"prompt",sHr);x(this,"summaryChatMessageClass",v_);this.memoryKey=e?.memoryKey??this.memoryKey,this.humanPrefix=a??this.humanPrefix,this.aiPrefix=s??this.aiPrefix,this.llm=u,this.prompt=l??this.prompt,this.summaryChatMessageClass=c??this.summaryChatMessageClass}async predictNewSummary(e,r){let n=Ll(e,this.humanPrefix,this.aiPrefix);return await new Qh({llm:this.llm,prompt:this.prompt}).predict({summary:r,new_lines:n})}},WHr=class extends Mce{constructor(e){super(e);x(this,"buffer","")}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){return this.returnMessages?{[this.memoryKey]:[new this.summaryChatMessageClass(this.buffer)]}:{[this.memoryKey]:this.buffer}}async saveContext(e,r){await super.saveContext(e,r);let n=await this.chatHistory.getMessages();this.buffer=await this.predictNewSummary(n.slice(-2),this.buffer)}async clear(){await super.clear(),this.buffer=""}};ra();var JHr=class extends Mce{constructor(e){super(e);x(this,"movingSummaryBuffer","");x(this,"maxTokenLimit",2e3);this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(r=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...r]);let n;return this.returnMessages?n=r:n=Ll(r,this.humanPrefix,this.aiPrefix),{[this.memoryKey]:n}}async saveContext(e,r){await super.saveContext(e,r),await this.prune()}async prune(){let e=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(e=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...e]);let r=await this.llm.getNumTokens(Ll(e,this.humanPrefix,this.aiPrefix));if(r>this.maxTokenLimit){let n=[];for(;r>this.maxTokenLimit;){let o=e.shift();o&&(n.push(o),r=await this.llm.getNumTokens(Ll(e,this.humanPrefix,this.ai
|
||
|
|
`);await this.vectorStoreRetriever.addDocuments([new Yl({pageContent:o,metadata:n})])}};QW();DL();var GHr=class extends b_{};var XHr=class extends GHr{constructor(){super();x(this,"lc_namespace",["langchain","stores","entity","in_memory"]);x(this,"store");this.store=Object.create(null)}async get(e,r){return e in this.store?this.store[e]:r}async set(e,r){this.store[e]=r}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}};ra();var ZHr=class extends t_{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});x(this,"entityExtractionChain");x(this,"entitySummarizationChain");x(this,"entityStore");x(this,"entityCache",[]);x(this,"k",3);x(this,"chatHistoryKey","history");x(this,"llm");x(this,"entitiesKey","entities");x(this,"humanPrefix");x(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new Qh({llm:this.llm,prompt:e.entityExtractionPrompt??lHr}),this.entitySummarizationChain=new Qh({llm:this.llm,prompt:e.entitySummarizationPrompt??cHr}),this.entityStore=e.entityStore??new XHr,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let r=this.inputKey??Hht(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=Ll(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[r]}),a=i.trim()==="NONE"?[]:i.split(",").map(l=>l.trim()),s={};for(let l of a)s[l]=await this.entityStore.get(l,"No current information known.");this.entityCache=[...a];let u=this.returnMessages?n.slice(-this.k*2):o;return{[this.chatHistoryKey]:u,[this.entitiesKey]:s}}async saveContext(e,r){await super.saveContext(e,r);let n=this.inputKey??Hht(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=Ll(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),a=e[n];for(let s of this.entityCache){let u=await this.entityStore.get(s,"No current information known."),l=await this.entitySummarizationChain.predict({summary:u,entity:s,history:i,input:a});l.trim()!=="UNCHANGED"&&await this.entityStore.set(s,l.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}};var YHr=class extends t_{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let r of this.memories){let n=e.filter(o=>r.memoryKeys.includes(o));if(n.length>0)throw new Error(`The same variables ${[...n]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...r.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}async loadMemoryVariables(e){let r={};for(let n of this.memories){let o=await n.loadMemoryVariables(e);r={...r,...o}}return r}async saveContext(e,r){for(let n of this.memories)await n.saveContext(e,r)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let r of this.memories)e.push(...r.memoryKeys);return e}};ra();var QHr=class extends t_{constructor(e){super(e);x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"maxTokenLimit",2e3);x(this,"llm");this.llm=e.llm,this.humanPrefix=e?.humanPrefix??this.humanPrefix,
|
||
|
|
|
||
|
|
Answer the question with as detailed as possible based only on the following context:
|
||
|
|
{context}
|
||
|
|
|
||
|
|
Question: {question}
|
||
|
|
`;this.qaPrompt=Eb.fromMessages([$C.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 Ace=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=Rce.getInstance(),this.chatModelManager=U0.getInstance(),this.promptManager=Ice.getInstance(),this.userMemoryManager=new $B(e),this.initialize(),ml(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.pendingModelError)throw this.pendingModelError;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 NJ(e)}}validateChainInitialization(){(!this.chain||!mNt(this.chain))&&(F("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n,o=UC(),i=Gu();if(!(o==="project"&&!i))try{if(n=o==="project"?i?.projectModelKey:j_(),!n)throw new NJ("No model key found. Please select a model in settings.");if(r){let a=PS(n,ee().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",n),a=aO[0],n=a.name+"|"+a.provider),o==="project"&&!a.projectEnabled){let u=ee().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,n=u.name+"|"+u.provider,new eWr.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,...i?.modelConfigs};await this.chatModelManager.setChatModel(s),this.pendingModelError=null}this.setChain(o,e),F(`Setting model to ${n}`)}catch(a){this.pendingModelError=a instanceof Error?a:new Error(String(a)),ie(`createChainWithNewModel failed: ${a}`),F(`modelKey: ${n||j_()}`)}}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=dte.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),S4("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=ee(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(PEe(),Yat))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(pX(),umt))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=dte.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:b$()},this.storeRetrieverDocuments.bind(this),ee().debug),S4("vault_qa"),ee().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=dte.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),S4("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=dte.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),S4("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=UC(),r=ee();switch(e){case"llm_chain":return new dae(this);case"vault_qa":return new nle(this);case"copilot_plus"
|
||
|
|
`,s||e.originalMessage||e.message),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(a||ste(u)){let c=Eb.fromMessages([new QN("history"),rw.fromTemplate("{input}")]);ste(u)&&(c=Eb.fromMessages([[Zs,b$()||""],c])),this.createChainWithNewModel({prompt:c},!1)}return await this.getChainRunner().run(e,r,n,o,i)}};na();Xe();Qe();Dt();var yje=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){f1t({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=ED(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Wr(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){jo.set(vte,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){mO("processingFiles",r=>r.filter(n=>n!==e)),mO("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){mO("processingFiles",o=>o.filter(i=>i!==e)),mO("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){F(`[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(`
|
||
|
|
`).filter(s=>s.trim());n.push(...a)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
|
||
|
|
`).filter(s=>s.trim());n.push(...a)}if(n.length>0){let a=[...new Set([...n])];mO("total",s=>a),F(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){F(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
|
||
|
|
`).filter(u=>u.trim()).filter(u=>r.webContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&F(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
|
||
|
|
`).filter(u=>u.trim()).filter(u=>r.youtubeContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&F(`[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&&F(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){mO("total",r=>r.includes(e)?r:[...r,e]),mO("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){mO("total",o=>o.includes(e)?o:[...o,e]),mO("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 Vg=class t{constructor(e,r){this.projectUsageTimestampsManager=new MJ;this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new Ace(e),this.projectContextCache=Iw.getInstance(),this.fileParserManager=new pq(Xl.getInstance(),this.app.vault,!0,null),this.loadTracker=yje.getInstance(this.app),s1t(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),u1t(async()=>{if(ZJ())return;let n=ee(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(UC()==="vault_qa"||UC()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),XJ(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){ml(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&&this.hasMeaningfulProjectConfigChange(a,i)&&(await this.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&await Promise.all([this.loadProjectContext(i,!0),this.getCurrentChainManager().createChainWithNewModel()]))}})}hasMeaningfulProjectConfigChange(e,r){let n={...e,UsageTimestamps:0},o={...r,UsageTimestamps:0};return JSON.stringify(n)!==JSON.stringify(o)}static getInstance(e,r){return t.instance||(t.instance=new t(e,r)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}touchProjectUsageTimestamps(e){this.projectUsageTimestampsManager.touch(e.id);let r=ee().projectList||[],n=r.find(i=>i.id===e.id);if(!n)return;let o=this.projectUsageTimestampsManager.shouldPersist(e.id,n.UsageTimestamps);o!==null&&(Re("projectList",r.map(i=>i.id===e.id?{...i,UsageTimestamps:o}:i)),this.projectUsageTimestampsManager.markPersisted(e.id,o))}getProjectUsageTimestampsManager(){return this.projectUsageTimestampsManager}async switchProject(e){try{if(this.loadTracker.clearAllLoadStates(),fO(!0),F("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 pq(Xl.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),this.touchProjectUsageTimestamps(e),F(`Switched to project: ${e.name}`)}catch(r){throw ie(`Failed to switch project: ${r}`),r}finally{fO(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,r=!1){r&&(this.loadTracker.clearAllLoadStates(),fO(!0));try{if(!e.contextSource)return Ce(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;F(`[loadProjectContext] Starting for project: ${e.name}`);let n=await this.projectContextCache.getOrInitializeCache(e),o=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,o),this.loadTracker.markAllCachedItemsAsSuccess(e,n,o);let[i]=await Promise.all([this.processMarkdownFiles(e,n,o),this.processWebUrls(e,n),thi
|
||
|
|
`).filter(m=>m.trim()),p=l.split(`
|
||
|
|
`).filter(m=>m.trim());await this.projectContextCache.removeWebUrls(r,f.filter(m=>!p.includes(m)))}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
|
||
|
|
`).filter(m=>m.trim()),p=d.split(`
|
||
|
|
`).filter(m=>m.trim());await this.projectContextCache.removeYoutubeUrls(r,f.filter(m=>!p.includes(m)))}}catch(n){ie(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Du)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ee().projectList.find(o=>o.id===e);if(!r)return Ce(`[getProjectContext] Project not found for ID: ${e}`),null;F(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?F(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):F(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r,!0);if(!o)return ie(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else F(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
|
||
|
|
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
|
||
|
|
${Object.values(e.webContexts).join(`
|
||
|
|
|
||
|
|
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
|
||
|
|
${Object.values(e.youtubeContexts).join(`
|
||
|
|
|
||
|
|
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([s,u])=>{let l=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=await this.projectContextCache.getOrReuseFileContext(r,s)||"[Content not available]";return`[[${c}]]
|
||
|
|
path: ${s}
|
||
|
|
type: ${d}
|
||
|
|
modified: ${new Date(u.timestamp).toISOString()}
|
||
|
|
|
||
|
|
${f}`}),a=await Promise.all(i);a.length>0&&n.push(`## Other Files
|
||
|
|
${a.join(`
|
||
|
|
|
||
|
|
`)}`)}}return`
|
||
|
|
# Project Context
|
||
|
|
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
|
||
|
|
|
||
|
|
<ProjectContext>
|
||
|
|
${n.join(`
|
||
|
|
|
||
|
|
`)}
|
||
|
|
</ProjectContext>
|
||
|
|
`}formatProjectContext(e){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
|
||
|
|
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
|
||
|
|
${Object.values(e.webContexts).join(`
|
||
|
|
|
||
|
|
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
|
||
|
|
${Object.values(e.youtubeContexts).join(`
|
||
|
|
|
||
|
|
`)}`),Object.keys(e.fileContexts).length>0){let n="";for(let[o,i]of Object.entries(e.fileContexts)){let a=o.split("/"),s=a[a.length-1],u=s.split(".").pop()||"";n+=`[[${s}]]
|
||
|
|
path: ${o}
|
||
|
|
type: ${u}
|
||
|
|
modified: ${new Date(i.timestamp).toISOString()}
|
||
|
|
|
||
|
|
`}n&&r.push(`## Other Files
|
||
|
|
${n}`)}return`
|
||
|
|
# Project Context
|
||
|
|
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
|
||
|
|
|
||
|
|
<ProjectContext>
|
||
|
|
${r.join(`
|
||
|
|
|
||
|
|
`)}
|
||
|
|
</ProjectContext>
|
||
|
|
`}async processMarkdownFiles(e,r,n){if(F(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){F(`[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,F(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else F(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return F(`[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");F(`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"}
|
||
|
|
modified: ${s?new Date(s.mtime).toISOString():"unknown"}`,i=u,F(`Completed processing markdown file: ${o.path}`)}catch(s){ie(`Error processing file ${o.path}: ${s}`),i=`[Error: ${Wr(s)}]`}return`${a}
|
||
|
|
|
||
|
|
${i}`}));return F("All markdown files processed for project context"),n.join(`
|
||
|
|
|
||
|
|
`)}async processWebUrls(e,r){F(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(F(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
|
||
|
|
`).filter(c=>c.trim());F(`[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&&F(`[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){F(`[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&&F(`[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&&Ce(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),F(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){F(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(F(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
|
||
|
|
`).filter(c=>c.trim());F(`[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&&F(`[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){F(`[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&&F(`[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&&Ce(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),F(`[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=QG.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()=>Xl.getInstance().youtube4llm(e));return r.response.transcript?`
|
||
|
|
|
||
|
|
YouTube transcript from ${e}:
|
||
|
|
${r.response.transcript}`:""}catch(r){return ie(`Failed to process YouTube URL ${e}: ${r}`),new e3.Notice(`Failed to process YouTube URL ${e}: ${Wr(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(F(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new pq(Xl.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()=>{let s=await this.projectContextCache.getOrReuseFileContext(e,a);s?(await fq(i,s,this.app.vault),o++):(F(`[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),ED(s))throw s}}o>0&&F(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){Ce("[retryFailedItem] No current project, aborting retry");return}let r=ee().projectList.find(n=>n.id===this.currentProjectId);if(!r){ie(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(F(`[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:Ce(`[retryFailedItem] Unknown item type: ${e.type}`);return}F(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new e3.Notice(`Retry successful: ${e.path}`)}catch(r){ie(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new e3.Notice(`Retry failed: ${Wr(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){Ce(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}F(`[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){Ce(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}F(`[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 e3.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()=>{}),F(`[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 e3.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)),F(`[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}=Zl({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>fu(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}};na();h4();Xe();var DWr=require("obsidian");xn();var bje=$(K());zr();var ni=bje.forwardRef(({className:t,type:e,...r},n)=>bje.createElement("input",{type:e,className:Se("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !t
|
||
|
|
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
|
||
|
|
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
|
||
|
|
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
|
||
|
|
|
||
|
|
IMPORTANT: If no YouTube video context is found, remind the user to:
|
||
|
|
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
|
||
|
|
2. Then use this command again
|
||
|
|
|
||
|
|
Generate the note with this exact structure:
|
||
|
|
|
||
|
|
---
|
||
|
|
title: "<video title>"
|
||
|
|
description: "<first 200 chars of description>"
|
||
|
|
channel: "<channel name>"
|
||
|
|
url: "<video url>"
|
||
|
|
duration: "<duration>"
|
||
|
|
published: <upload date in YYYY-MM-DD format>
|
||
|
|
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
|
||
|
|
genre:
|
||
|
|
- "<genre>"
|
||
|
|
watched:
|
||
|
|
---
|
||
|
|

|
||
|
|
|
||
|
|
> [!summary]- Description
|
||
|
|
> <full video description, preserve line breaks>
|
||
|
|
|
||
|
|
## Summary
|
||
|
|
|
||
|
|
<Brief 2-3 paragraph summary of the video content>
|
||
|
|
|
||
|
|
## Key Takeaways
|
||
|
|
|
||
|
|
<List 5-8 key takeaways as bullet points>
|
||
|
|
|
||
|
|
## Mindmap
|
||
|
|
|
||
|
|
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
|
||
|
|
- Root node format: root(Topic Name) - use round brackets, NO double brackets
|
||
|
|
- Child nodes: just plain text, no brackets needed
|
||
|
|
- Do NOT use quotes, parentheses, brackets, or any special characters in text
|
||
|
|
- Do NOT use icons or emojis
|
||
|
|
- Keep all node text short and simple - max 3-4 words per node
|
||
|
|
- Use only letters, numbers, and spaces
|
||
|
|
|
||
|
|
Example of CORRECT syntax:
|
||
|
|
\`\`\`mermaid
|
||
|
|
mindmap
|
||
|
|
root(Video Main Topic)
|
||
|
|
First Theme
|
||
|
|
Detail one
|
||
|
|
Detail two
|
||
|
|
Second Theme
|
||
|
|
Detail three
|
||
|
|
Third Theme
|
||
|
|
\`\`\`
|
||
|
|
|
||
|
|
## Notable Quotes
|
||
|
|
|
||
|
|
<List 5-10 notable quotes from the transcript. Format each as:>
|
||
|
|
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)
|
||
|
|
|
||
|
|
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",content:`
|
||
|
|
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.
|
||
|
|
|
||
|
|
IMPORTANT: If no web page context is found, remind the user to:
|
||
|
|
1. Open a web page in Web Viewer (or use @ to select a web tab)
|
||
|
|
2. Or open a note clipped by Obsidian Web Clipper
|
||
|
|
3. Then use this command again
|
||
|
|
|
||
|
|
Generate the note with this exact structure:
|
||
|
|
|
||
|
|
---
|
||
|
|
title: "<page title>"
|
||
|
|
source: "<page url>"
|
||
|
|
description: "<brief description>"
|
||
|
|
tags:
|
||
|
|
- "clippings"
|
||
|
|
---
|
||
|
|
|
||
|
|
## Summary
|
||
|
|
|
||
|
|
<Brief 2-3 paragraph summary of the page content>
|
||
|
|
|
||
|
|
## Key Takeaways
|
||
|
|
|
||
|
|
<List 5-8 key takeaways as bullet points>
|
||
|
|
|
||
|
|
## Mindmap
|
||
|
|
|
||
|
|
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
|
||
|
|
- Root node format: root(Topic Name) - use round brackets, NO double brackets
|
||
|
|
- Child nodes: just plain text, no brackets needed
|
||
|
|
- Do NOT use quotes, parentheses, brackets, or any special characters in text
|
||
|
|
- Keep all node text short and simple - max 3-4 words per node
|
||
|
|
|
||
|
|
\`\`\`mermaid
|
||
|
|
mindmap
|
||
|
|
root(Main Topic)
|
||
|
|
Theme One
|
||
|
|
Detail
|
||
|
|
Theme Two
|
||
|
|
Detail
|
||
|
|
\`\`\`
|
||
|
|
|
||
|
|
## Notable Quotes
|
||
|
|
|
||
|
|
<List 3-5 notable quotes from the content, if any>
|
||
|
|
|
||
|
|
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}];Xe();var eZ=require("obsidian");Qe();LC();LC();var r3=QL(),n3=yc([]),ogt=new Set;function o3(t){ogt.add(t)}function i3(t){ogt.delete(t)}function Dce(t){return ogt.has(t)}function jce(t){let e=r3.get(n3);r3.set(n3,e.filter(r=>r.title!==t))}function a3(t,e){let r=r3.get(n3),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],r3.set(n3,n)}function Pje(t){r3.set(n3,t)}function Mje(){return I_(n3,{store:r3})}function Sv(){return r3.get(n3)}fte();Dt();t1();gr();function Rje(t,e,r){let n=t.trim();return n?t!==n?"Command name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function tZ(t){return encodeURIComponent(t.toLowerCase())}function tU(){return(0,eZ.normalizePath)(ee().customPromptsFolder)}function rZ(t){return`${tU()}/${t}.md`}function nZ(t){if(!(t instanceof eZ.TFile)||t.extension!=="md")return!1;let e=tU();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function AWr(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[nN]!=null}async function $ce(t){let e=await app.vault.read(t),r=jJ(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[I$]??rN.showInContextMenu,i=n?.frontmatter?.[A$]??rN.showInSlashMenu,a=n?.frontmatter?.[D$]??rN.lastUsedMs,s=n?.frontmatter?.[nN]??rN.order,u=n?.frontmatter?.[N$]??rN.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function Ije(){let t=app.vault.getFiles().filter(r=>nZ(r)),e=await Promise.all(t.map($ce));return Pje(e),e}function Lce(t){return iO(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function Mii(t){return iO(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function Rii(t){return iO(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function Aje(t){switch(ee().promptSortStrategy){case"timestamp":return Mii(t);case"alphabetical":return Rii(t);case"manual":return Lce(t);default:return t}}async function Fce(t,e,r=!1){let o=(await kce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${N_}}`)||r)return o;let i=o.indexOf(ngt);return i===-1?e.trim()?o+`
|
||
|
|
|
||
|
|
<`+N_+">"+e+"</"+N_+">":o:o.slice(0,i)+e+o.slice(i+ngt.length)}var Iii=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function Aii(t,e,r){let n=new Map,o=new Set,i;for(;(i=Iii.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]},u=a.toLowerCase();if(u==="activenote")if(r){let l=await $J(r,e);l&&(s.content=`<${_4}>
|
||
|
|
<path>${r.path}</path>
|
||
|
|
## ${Pge(r)}
|
||
|
|
|
||
|
|
${l}
|
||
|
|
</${_4}>`,s.files.push(r))}else new eZ.Notice("No active note found.");else{if(u==="activewebtab")continue;if(a.startsWith("#")){let l=a.slice(1).split(",").map(f=>f.trim()),c=await Oge(e,l),d=[];for(let f of c){let p=await $J(f,e);p&&(d.push(`<${_4}>
|
||
|
|
<path>${f.path}</path>
|
||
|
|
## ${Pge(f)}
|
||
|
|
|
||
|
|
${p}
|
||
|
|
</${_4}>`),s.files.push(f))}s.content=d.join(`
|
||
|
|
|
||
|
|
`)}else{let l=bNt(a),c=await ite(e,l),d=[];for(let f of c){let p=await $J(f,e);p&&(d.push(`<${_4}>
|
||
|
|
<path>${f.path}</path>
|
||
|
|
## ${Pge(f)}
|
||
|
|
|
||
|
|
${p}
|
||
|
|
</${_4}>`),s.files.push(f))}s.content=d.join(`
|
||
|
|
|
||
|
|
`)}}s.content?(n.set(a,s.content),s.files.forEach(l=>o.add(l))):u!=="activenote"&&u!=="activewebtab"&&(a.startsWith('"')||Ce(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}async function kce(t,e,r,n,o=!1){let i=ee(),a=new Set;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&n&&a.add(n),{processedPrompt:t+`
|
||
|
|
|
||
|
|
`,includedFiles:Array.from(a)};let{variablesMap:s,includedFiles:u}=await Aii(t,r,n);u.forEach(p=>a.add(p));let l=t,c="",d=null;!o&&l.includes("{}")&&(l=l.replace(/\{\}/g,`{${N_}}`),e?c+=`<${N_}>
|
||
|
|
${e}
|
||
|
|
</${N_}>`:n?(d=await $J(n,r),c+=`<${N_} type="active_note">
|
||
|
|
${d||""}
|
||
|
|
</${N_}>`,a.add(n)):c+=`<${N_}>
|
||
|
|
(No selected text or active note available)
|
||
|
|
</${N_}>`);for(let[p,m]of s.entries())p.toLowerCase()==="activenote"&&d!==null||(c?c+=`
|
||
|
|
|
||
|
|
<${mte} name="${p}">
|
||
|
|
${m}
|
||
|
|
</${mte}>`:c+=`<${mte} name="${p}">
|
||
|
|
${m}
|
||
|
|
</${mte}>`);let f=yNt(l,r);for(let p of f)if(!a.has(p)){let m=await $J(p,r);if(m){let h=await r.adapter.stat(p.path),y=h?new Date(h.ctime).toISOString():"Unknown",g=h?new Date(h.mtime).toISOString():"Unknown",b=`<${pte}>
|
||
|
|
<title>${p.basename}</title>
|
||
|
|
<path>${p.path}</path>
|
||
|
|
<ctime>${y}</ctime>
|
||
|
|
<mtime>${g}</mtime>
|
||
|
|
<content>
|
||
|
|
${m}
|
||
|
|
</content>
|
||
|
|
</${pte}>`;c&&(c+=`
|
||
|
|
|
||
|
|
`),c+=`${b}`,a.add(p)}}return{processedPrompt:c?`${l}
|
||
|
|
|
||
|
|
${c}`:`${l}
|
||
|
|
|
||
|
|
`,includedFiles:Array.from(a)}}function NWr(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 Nje(){let e=Sv().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function igt(t,e){try{o3(t.path),await app.fileManager.processFrontMatter(t,r=>{r[I$]==null&&(r[I$]=e.showInContextMenu),r[A$]==null&&(r[A$]=e.showInSlashMenu),r[nN]==null&&(r[nN]=e.order),r[N$]==null&&(r[N$]=e.modelKey),r[D$]==null&&(r[D$]=e.lastUsedMs)})}finally{i3(t.path)}}function Nii({commands:t,command:e,onConfirm:r,onCancel:n}){let i=kr().activeModels.filter(f=>f.enabled).map(f=>({label:MWr(f),value:no(f)})),[a,s]=(0,ks.useState)(e),[u,l]=(0,ks.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=Rje(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 ks.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},ks.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ks.default.createElement(uc,{htmlFor:"title"},"Name"),ks.default.createElement(ni,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&ks.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),ks.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ks.default.createElement(uc,{htmlFor:"content"},"Prompt"),ks.default.createElement(RWr,null),ks.default.createElement(n_,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&ks.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),ks.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ks.default.createElement(uc,{htmlFor:"modelKey"},"Model (Optional)"),ks.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},ks.default.createElement("select",{value:a.modelKey,onChange:f=>{let p=f.target.value;if(!p){c("modelKey","");return}if(!i.find(h=>h.value===p)){ie(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:Se("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")},ks.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>ks.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),ks.default.createElement("div",{className:Se("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")},ks.default.createElement(Ji,{className:"tw-size-4"})))),ks.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ks.default.createElement(Uu,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),ks.default.createElement(uc,{htmlFor:"showInContextMenu"},"Show in context menu")),ks.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ks.default.createElement(Uu,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),ks.default.createElement(uc,{htmlFor:"showInSlashMenu"},"Show in slash menu")),ks.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},ks.default.createElement(me,{variant:"secondary",onClick:n},"Cancel"),ks.default.createElement(me,{variant:"default",onClick:d},"Save")))}var rU=class extends DWr.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,jWr.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this
|
||
|
|
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).
|
||
|
|
`;function jje(t,e){if(!e)return t;let r=t.includes("{}"),n=/\{activenote\}/i.test(t),o=[];return r||o.push("{}"),n||o.push("{activeNote}"),o.length>0?t+`
|
||
|
|
|
||
|
|
${o.join(`
|
||
|
|
|
||
|
|
`)}`:t}na();var agt=$(K());zr();function sgt({onMouseDown:t,className:e}){return agt.createElement("div",{className:Se("tw-flex tw-h-4 tw-items-center tw-justify-center","tw-cursor-grab active:tw-cursor-grabbing","hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)]",e),onMouseDown:t},agt.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"}))}var ugt=$(K());Mr();zr();xn();function lgt({onClose:t,className:e}){return ugt.createElement(me,{className:Se("tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",e),variant:"ghost2",onClick:t,title:"Close","aria-label":"Close"},ugt.createElement(Ho,{className:"tw-size-4"}))}var $je=$(K());Mr();zr();function cgt({icon:t,label:e,className:r}){let n=t===null?null:t!==void 0?t:$je.createElement(DF,{className:"tw-size-4 tw-text-muted"});return $je.createElement("div",{className:Se("tw-flex tw-flex-none tw-items-center tw-justify-center tw-gap-2","tw-px-4 tw-py-2",r)},n,$je.createElement("span",{className:"tw-truncate tw-text-sm tw-font-medium tw-text-normal"},e))}var hm=$(K());zr();Mr();xn();var s3=$(K());function $Wr({content:t,renderMarkdown:e,className:r}){let n=s3.useRef(null),o=s3.useRef(0);return s3.useEffect(()=>{let i=n.current;if(!i)return;let a=++o.current,s=i.ownerDocument.createElement("div");i.innerHTML="",e(t,s).then(()=>{a===o.current&&(i.replaceChildren(...Array.from(s.childNodes)),s.classList.contains("markdown-rendered")&&i.classList.add("markdown-rendered"))}).catch(()=>{a===o.current&&(i.textContent=t)})},[t,e]),s3.createElement("div",{ref:n,className:r})}function dgt({state:t,editable:e=!1,value:r,onChange:n,placeholder:o="Ready to generate...",className:i,minHeight:a="180px",disableAutoGrow:s=!1,renderMarkdown:u}){let l=hm.useRef(null),[c,d]=hm.useState(!1),f=t.type==="result"&&!t.isStreaming,p=!!u&&f&&!c,m=t.type==="loading"||t.type==="result"&&t.isStreaming;hm.useEffect(()=>{m&&d(!1)},[m]),hm.useEffect(()=>{t.type==="result"&&t.isStreaming&&l.current&&(l.current.scrollTop=l.current.scrollHeight)},[t]);let h="",y=!0;if(t.type==="idle"?(h="",y=!0):t.type==="loading"?(h="loading...",y=!0):t.type==="result"&&(h=e&&r!==void 0?r:t.text,y=t.isStreaming||!e),p&&u){let b=e&&r!==void 0?r:t.text;return hm.createElement("div",{className:Se("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},hm.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1 tw-overflow-auto tw-rounded-md tw-border tw-border-solid tw-px-3 tw-py-2"},hm.createElement($Wr,{content:b,renderMarkdown:u,className:"tw-pr-6 tw-text-sm"}),e&&hm.createElement(me,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-1 tw-top-1 tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!0),title:"Edit content"},hm.createElement(NF,{className:"tw-size-3"}))))}let g=!!u&&f&&c;return s?hm.createElement("div",{className:Se("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},hm.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1"},hm.createElement("textarea",{ref:l,value:h,onChange:b=>n?.(b.target.value),placeholder:o,disabled:y,className:Se("tw-min-w-fit tw-overflow-auto tw-border-solid","tw-absolute tw-inset-0 tw-w-full tw-resize-none tw-rounded-md tw-border tw-bg-transparent tw-py-2 tw-pl-3 tw-pr-8 tw-text-base tw-shadow-sm placeholder:tw-text-muted focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 md:tw-text-sm",y&&"tw-cursor-default tw-opacity-70")}),g&&hm.createElement(me,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-2 tw-top-2 tw-z-[1] tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!1),title:"Preview rendered content"},hm.createElement(bre,{className:"tw-size-3"})))):hm.createElement("div",{className:Se("tw-flex-1 tw-px-4 tw-py-2",i)},hm.createElement(n_,{ref:l,value:h,onChange:b=>n?.(b.target.value),placeholder:o,disabled:y,className:Se("tw-min-h-[120px] tw-resize-
|
||
|
|
.`.concat(Ygt,` {
|
||
|
|
overflow: hidden `).concat(n,`;
|
||
|
|
padding-right: `).concat(s,"px ").concat(n,`;
|
||
|
|
}
|
||
|
|
body[`).concat(yZ,`] {
|
||
|
|
overflow: hidden `).concat(n,`;
|
||
|
|
overscroll-behavior: contain;
|
||
|
|
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
|
||
|
|
padding-left: `.concat(o,`px;
|
||
|
|
padding-top: `).concat(i,`px;
|
||
|
|
padding-right: `).concat(a,`px;
|
||
|
|
margin-left:0;
|
||
|
|
margin-top:0;
|
||
|
|
margin-right: `).concat(s,"px ").concat(n,`;
|
||
|
|
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
|
||
|
|
}
|
||
|
|
|
||
|
|
.`).concat(h3,` {
|
||
|
|
right: `).concat(s,"px ").concat(n,`;
|
||
|
|
}
|
||
|
|
|
||
|
|
.`).concat(g3,` {
|
||
|
|
margin-right: `).concat(s,"px ").concat(n,`;
|
||
|
|
}
|
||
|
|
|
||
|
|
.`).concat(h3," .").concat(h3,` {
|
||
|
|
right: 0 `).concat(n,`;
|
||
|
|
}
|
||
|
|
|
||
|
|
.`).concat(g3," .").concat(g3,` {
|
||
|
|
margin-right: 0 `).concat(n,`;
|
||
|
|
}
|
||
|
|
|
||
|
|
body[`).concat(yZ,`] {
|
||
|
|
`).concat(Qgt,": ").concat(s,`px;
|
||
|
|
}
|
||
|
|
`)},ZJr=function(){var t=parseInt(document.body.getAttribute(yZ)||"0",10);return isFinite(t)?t:0},kui=function(){bZ.useEffect(function(){return document.body.setAttribute(yZ,(ZJr()+1).toString()),function(){var t=ZJr()-1;t<=0?document.body.removeAttribute(yZ):document.body.setAttribute(yZ,t.toString())}},[])},uyt=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;kui();var i=bZ.useMemo(function(){return syt(o)},[o]);return bZ.createElement(Lui,{styles:Fui(i,!e,o,r?"":"!important")})};var lyt=!1;if(typeof window<"u")try{Qce=Object.defineProperty({},"passive",{get:function(){return lyt=!0,!0}}),window.addEventListener("test",Qce,Qce),window.removeEventListener("test",Qce,Qce)}catch{lyt=!1}var Qce,y3=lyt?{passive:!1}:!1;var qui=function(t){return t.tagName==="TEXTAREA"},YJr=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!qui(t)&&r[e]==="visible")},Bui=function(t){return YJr(t,"overflowY")},Uui=function(t){return YJr(t,"overflowX")},cyt=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=QJr(t,n);if(o){var i=e5r(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},zui=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},Vui=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},QJr=function(t,e){return t==="v"?Bui(e):Uui(e)},e5r=function(t,e){return t==="v"?zui(e):Vui(e)},Hui=function(t,e){return t==="h"&&e==="rtl"?-1:1},t5r=function(t,e,r,n,o){var i=Hui(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{if(!s)break;var p=e5r(t,s),m=p[0],h=p[1],y=p[2],g=h-y-i*m;(m||g)&&QJr(t,s)&&(d+=g,f+=m);var b=s.parentNode;s=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}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 O$e=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},r5r=function(t){return[t.deltaX,t.deltaY]},n5r=function(t){return t&&"current"in t?t.current:t},Wui=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Jui=function(t){return`
|
||
|
|
.block-interactivity-`.concat(t,` {pointer-events: none;}
|
||
|
|
.allow-interactivity-`).concat(t,` {pointer-events: all;}
|
||
|
|
`)},Kui=0,_Z=[];function o5r(t){var e=Rl.useRef([]),r=Rl.useRef([0,0]),n=Rl.useRef(),o=Rl.useState(Kui++)[0],i=Rl.useState(Yce)[0],a=Rl.useRef(t);Rl.useEffect(function(){a.current=t},[t]),Rl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=UJr([t.lockRef.current],(t.shards||[]).map(n5r),!0).filter(Boolean);return h.forEach(function(y){return y.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=Rl.useCallback(function(h,y){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=O$e(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-g[0],w="deltaY"in h?h.deltaY:b[1]-g[1],T,O=h.target,E=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&E==="h"&&O.type==="range")return!1;var P=cyt(E,O);if(!P)return!0;if(P?T=E:(T=E==="v"?"h":"v",P=cyt(E,O)),!P)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=T),!T)return!0;var R=n.current||T;return t5r(R,y,h,R==="h"?_:w,!0)},[]),u=Rl.useCallback(function(h){var y=h;if(!(!_Z.length||_Z[_Z.length-1]!==i)){var g="deltaY"in y?r5r(y):O$e(y),b=e.current.filter(function(T){return T.name===y.type&&(T.target===y.target||y.target===T.shadowParent)&&Wui(T.delta,g)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(n5r).filter(Boolean).filter(function(T){return T.contains(y.target)}),w=_.length>0?s(y,_[0]):!a.current.noIsolation;w&&y.cancelable&&y.preventDefault()}}},[]),l=Rl.useCallback(function(h,y,g,b){var _={name:h,delta:y,target:g,should:b,shadowParent:Gui(g)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=Rl.useCallback(function(h){r.current=O$e(h),n.current=void 0},[]),d=Rl.useCallback(function(h){l(h.type,r5r(h),h.target,s(h,t.lockRef.current))},[]),f=Rl.useCallback(function(h){l(h.type,O$e(h),h.target,s(h,t.lockRef.current))},[]);Rl.useEffect(function(){return _Z.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,y3),document.addEventListener("touchmove",u,y3),document.addEventListener("touchstart",c,y3),function(){_Z=_Z.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,y3),document.removeEventListener("touchmove",u,y3),document.removeEventListener("touchstart",c,y3)}},[]);var p=t.removeScrollBar,m=t.inert;return Rl.createElement(Rl.Fragment,null,m?Rl.createElement(i,{styles:Jui(o)}):null,p?Rl.createElement(uyt,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Gui(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var i5r=ryt(T$e,o5r);var a5r=E$e.forwardRef(function(t,e){return E$e.createElement(Zce,Ov({},t,{ref:e,sideCar:i5r}))});a5r.classNames=Zce.classNames;var V$=a5r;var Ro=$(wt(),1),dyt=["Enter"," "],Xui=["ArrowDown","PageUp","Home"],u5r=["ArrowUp","PageDown","End"],Zui=[...Xui,...u5r],Yui={ltr:[...dyt,"ArrowRight"],rtl:[...dyt,"ArrowLeft"]},Qui={ltr:["ArrowLeft"],rtl:["ArrowRight"]},nde="Menu",[tde,eli,tli]=oU(nde),[b3,fyt]=r3r(nde,[tli,tC,Xgt]),ode=tC(),l5r=Xgt(),[c5r,pU]=b3(nde),[rli,ide]=b3(nde),d5r=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=ode(e),[u,l]=Gr.useState(null),c=Gr.useRef(!1),d=_$e(i),f=n3r(o);return Gr.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Ro.jsx)(B$,{...s,children:(0,Ro.jsx)(c5r,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Ro.jsx)(rli,{scope:e,onClose:Gr.useCallb
|
||
|
|
|
||
|
|
Source: ${d.url}
|
||
|
|
|
||
|
|
${d.transcript}`;await navigator.clipboard.writeText(w),new TZ.Notice("Transcript copied to clipboard!")}catch(w){ie("Failed to copy to clipboard:",w),new TZ.Notice("Failed to copy to clipboard")}},g=async()=>{if(d)try{let w=`# YouTube Video Transcript
|
||
|
|
|
||
|
|
Source: ${d.url}
|
||
|
|
|
||
|
|
${d.transcript}`;await FJ(w,!1),t()}catch(w){ie("Failed to insert to note:",w),new TZ.Notice("Failed to insert to note")}},b=()=>{r("input"),o(""),u(""),f(null)},_=w=>{w.key==="Enter"&&!i&&l&&h()};return e==="display"&&d?Vu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Vu.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Vu.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Vu.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Vu.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Vu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Vu.createElement(me,{variant:"ghost",onClick:b},"Download Another"),Vu.createElement(me,{variant:"default",onClick:y},"Copy to Clipboard"),Vu.createElement(me,{variant:"default",onClick:g},"Insert at Cursor"),Vu.createElement(me,{variant:"secondary",onClick:t},"Close"))):Vu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Vu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Vu.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Vu.createElement(ni,{placeholder:"https://www.youtube.com/watch?v=...",value:n,onChange:w=>m(w.target.value),onKeyDown:_,disabled:i}),s&&Vu.createElement("div",{className:"tw-text-sm tw-text-error"},s)),Vu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Vu.createElement(me,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Vu.createElement(me,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}var V$e=class extends TZ.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,i8r.createRoot)(e);let r=()=>{this.close()};this.root.render(Vu.createElement(Xci,{onClose:r}))}onClose(){this.root.unmount()}};id();u0();Wb();Dt();var Io=require("obsidian");y_();gr();na();function rg(t,e,r){t.addCommand({id:e,name:Fge[e],icon:kge[e],callback:r})}function U8r(t,e,r){t.addCommand({id:e,name:Fge[e],icon:kge[e],editorCallback:r})}function z8r(t,e,r){t.addCommand({id:e,name:Fge[e],icon:kge[e],checkCallback:r})}function obt(t,e,r){U8r(t,ur.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let o=await n.getSelection(),i=o.split(" ").length,a=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new Io.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),rg(t,ur.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await cat(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Io.Notice(`Total tokens in your vault: ${o}`)}catch(n){ie("Error counting tokens: ",n),new Io.Notice("An error occurred while counting tokens.")}}),rg(t,ur.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),rg(t,ur.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),rg(t,ur.NEW_CHAT,()=>{r9(),t.newChat()}),z8r(t,ur.TRIGGER_QUICK_COMMAND,n=>{let o=t.app.workspace.getActiveViewOfType(Io.MarkdownView);if(n)return!!(!cte()&&o&&o.editor);if(cte())return new Io.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new Io.Notice("No active editor found."),!1;let a=o.editor.getSelection();if(!a.trim())return new Io.Notice("Please select some text first. Selected text is required for quick commands."),!1;let s={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};return new mU(t.app,{selectedText:a,command:s,systemPrompt:Dje,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(l,c)=>jje(l,c)}}).open(),!0}),rg(t,ur.CLEAR_LOCAL_COPILOT_INDEX,async()=>{let{getSettings:n}=await Promise.resolve().then(()=>(Qe(),r1)),o=n();if(kh(o)){new Io.Notice("Miyo folders are managed in Miyo. Remove the folder there
|
||
|
|
|
||
|
|
Are you sure you want to proceed?`;if(await new Promise(u=>{new nu(t.app,()=>u(!0),a,"Clear Semantic Index","Clear Index","Cancel",()=>u(!1)).open()}))try{await(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().clearIndex(),new Io.Notice("Cleared local Copilot semantic index.")}catch(u){ie("Error clearing semantic index:",u),new Io.Notice("Failed to clear semantic index.")}}),rg(t,ur.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Qe(),r1));if(kh(n())){new Io.Notice("Miyo manages file cleanup automatically. Run Index (refresh) vault to trigger a scan if needed.");return}let i=await(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().garbageCollectVectorStore();new Io.Notice(`Garbage collection completed. Removed ${i} stale documents.`)}catch(n){ie("Error during garbage collection:",n),new Io.Notice("Failed to garbage collect semantic index.")}}),rg(t,ur.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Qe(),r1)),o=n();if(o.enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});kh(o)?new Io.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Io.Notice(`Semantic search index refreshed with ${a} documents.`)}else new Io.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ie("Error building index:",n),new Io.Notice("An error occurred while building the index.")}}),rg(t,ur.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{if(await new Promise(o=>{new nu(t.app,()=>o(!0),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault","Continue","Cancel",()=>o(!1)).open()}))try{let{getSettings:o}=await Promise.resolve().then(()=>(Qe(),r1)),i=o();if(i.enableSemanticSearchV3){let s=await(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});kh(i)?new Io.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Io.Notice(`Semantic search index rebuilt with ${s} documents.`)}else new Io.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(o){ie("Error rebuilding index:",o),new Io.Notice("An error occurred while rebuilding the index.")}}),rg(t,ur.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),rg(t,ur.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=await Promise.resolve().then(()=>(Wb(),wbr)),{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 T=await t.app.vault.cachedRead(w);!T||T.trim().length===0?c.add(w.path):p.has(w.path)||d.add(w.path)}let m=["# 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(`
|
||
|
|
`),h=`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,y="copilot",g=`${y}/${h}`;await ql(y);let b=t.app.vault.getAbstractFileByPath(g);b?await t.app.vault.modify(b,m):await t.app.vault.create(g,m);let _=t.app.vault.getAbstractFileByPath(g);_&&(await t.app.workspace.getLeaf().openFile(_),new Io.Notice(`Listed ${p.size} indexed files`))}catch(n){ie("Error listing indexed files:",n),new Io.Notice("Failed to list indexed files.")}}),rg(t,ur.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new Io.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(El(),Bc))).default,{DBOperations:i}=await Promise.resolve().then(()=>(KOe(),xbr)),a=await o.getInstance().getDb(),s=await i.getDocsByPath(a,n.path);if(!s||s.length===0){new Io.Notice(`No embedding data found for: ${n.path}`);return}let u=s.map(h=>h.document),l=[`# Embedding Debug: ${n.basename}`,"",`**Path:** ${n.path}`,`**Chunks:** ${u.length}`,`**Embedding Model:** ${u[0]?.embeddingModel||"unknown"}`,"",...u.flatMap((h,y)=>{let g=h.embedding||[],b=g.slice(0,10).map(_=>_.toFixed(6)).join(", ");return[`## Chunk ${y+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${g.length}`,`- **Vector Preview:** [${b}${g.length>10?", ...":""}]`,`- **Tags:** ${(h.tags||[]).join(", ")||"none"}`,`- **Characters:** ${h.nchars||0}`,""]})].join(`
|
||
|
|
`),c=`Copilot-Embedding-Debug-${n.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${c}`;await ql(d);let p=t.app.vault.getAbstractFileByPath(f);p?await t.app.vault.modify(p,l):await t.app.vault.create(f,l);let m=t.app.vault.getAbstractFileByPath(f);m&&(await t.app.workspace.getLeaf().openFile(m),new Io.Notice(`Embedding debug info for ${u.length} chunk(s)`))}catch(n){ie("Error inspecting embeddings:",n),new Io.Notice("Failed to inspect embeddings. Is the index loaded?")}}),rg(t,ur.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await Iw.getInstance().clearAllCache(),await ZG.getInstance().clear(),new Io.Notice("All Copilot caches cleared successfully")}catch(n){ie("Error clearing Copilot caches:",n),new Io.Notice("Failed to clear Copilot caches")}}),rg(t,ur.OPEN_LOG_FILE,async()=>{try{await uEe(),await Em.openLogFile()}catch(n){ie("Error creating Copilot log file:",n),new Io.Notice("Failed to create Copilot log file.")}}),rg(t,ur.CLEAR_LOG_FILE,async()=>{try{await Em.clear(),new Io.Notice("Copilot log cleared.")}catch(n){ie("Error clearing Copilot log file:",n),new Io.Notice("Failed to clear Copilot log file.")}}),U8r(t,ur.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new Io.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new Io.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new Io.Notice("Could not determine selection range");return}let s=a.anchor.line+1,u=a.head.line+1,l={id:gu(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)};pO([l]),t.activateView()}),rg(t,ur.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:n}=await import("obsidian");if(!n.isDesktopApp){new Io.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(T3(),B8r));try{let i=o(t.app),a=i.getActiveLeaf()??i.getLastActiveLeaf();if(!a){new Io.Notice("No active Web Tab found");return}let s=await i.getSelectedMarkdown(a);if(!s.trim()){new Io.Notice("No text selected in Web Tab");return}let u=i.getPageInfo(a),l={id:gu(),content:s,sourceType:"web",title:u.title||"Untitled",url:u.url,faviconUrl:u.faviconUrl||void 0};pO([l]),t.activateView()}catch(i){ie("Error adding web selection to context:",i),new Io.Notice("Failed to get web selection")}}),rg(t,ur.ADD_CUSTOM_COMMAND,async()=>{let n=Sv(),o={...rN};new rU(t.app,n,o,async a=>{await Zm.getInstance().createCommand(a)}).open()}),rg(t,ur.APPLY_CUSTOM_COMMAND,()=>{new U$e(t.app).open()}),rg(t,ur.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await m0()){new Io.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new V$e(t.app).open()}),z8r(t,ur.TRIGGER_QUICK_ASK,n=>{let o=t.app.workspace.getActiveViewOfType(Io.MarkdownView);if(n)return!!(!cte()&&o&&o.editor);if(cte())return new Io.Notice("Quick Ask is not available in source mode."),!1;if(!o||!o.editor)return new Io.Notice("No active editor found."),!1;let i=o.editor.cm;return i?(t.quickAskController.show(o,i),!0):(new Io.Notice("Could not access CodeMirror editor."),!1)})}na();var DZ={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},jZ="copilot-system-prompt-created",$Z="copilot-system-prompt-modified",LZ="copilot-system-prompt-last-used",ibt="copilot-system-prompt-default";var gU=require("obsidian");Qe();Dt();Xe();function gde(t,e,r){let n=t.trim();return n?t!==n?"Prompt name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function iC(){return(0,gU.normalizePath)(ee().userSystemPromptsFolder)}function aC(t){return(0,gU.normalizePath)(`${iC()}/${t}.md`)}function Mdi(t,e){let r=e?(0,gU.normalizePath)(e):iC();return(0,gU.normalizePath)(`${r}/${t}.md`)}function FZ(t){if(!(t instanceof gU.TFile)||t.extension!=="md")return!1;let e=iC();if(!t.path.starts
|
||
|
|
`).replace(/\r/g,`
|
||
|
|
`)}async function J8r(t,e,r){let n=iC(),o=`${n}/unsupported`;await ql(o);let i="Migrated System Prompt (Failed Verification)",a=i,s=1;for(;t.getAbstractFileByPath(`${o}/${a}.md`);)s++,a=`${i} ${s}`;let u=`${o}/${a}.md`,l=`> Migration failed: ${r}
|
||
|
|
>
|
||
|
|
> To fix: Review the content below, then move this file to ${n}
|
||
|
|
|
||
|
|
${e}`;return await t.create(u,l),u}async function Adi(t,e,r){try{let n=await t.read(e),o=jJ(n,{trimStart:!1}),i=cbt(o).replace(/^\n+/,""),a=cbt(r).replace(/^\n+/,"");return i!==a?(Ce(`Migration verification failed: content mismatch. Expected ${a.length} chars, got ${i.length} chars`),!1):!0}catch(n){return ie("Migration verification failed: unable to read back file",n),!1}}async function dbt(t){let r=ee().userSystemPrompt;if(!r||r.trim().length===0){F("No legacy userSystemPrompt to migrate");return}try{F("Migrating legacy userSystemPrompt from settings to file system");let n=iC();await ql(n);let o=Idi(W8r,t),i=aC(o);o!==W8r&&F(`Default name already exists, using unique name: "${o}"`);let a=Date.now(),s=cbt(r),u={title:o,content:s,createdMs:a,modifiedMs:a,lastUsedMs:0};await t.create(i,s);let l=t.getAbstractFileByPath(i);if(!(l instanceof K8r.TFile))throw new Error("File not found after creation");if(await E3(l,u),await Adi(t,l,r)){Re("defaultSystemPromptTitle",o);try{await kZ()}catch(d){Ce("Failed to reload prompts after migration:",d)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field"),new nu(app,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${n}.
|
||
|
|
|
||
|
|
You can now:
|
||
|
|
\u2022 Edit your system prompt directly in the file
|
||
|
|
\u2022 Create multiple system prompts
|
||
|
|
\u2022 Manage prompts through the settings UI
|
||
|
|
|
||
|
|
Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{let d=await J8r(t,r,"content verification mismatch");try{await kZ()}catch(f){Ce("Failed to reload prompts after failed migration:",f)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported)"),new nu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Issue
|
||
|
|
|
||
|
|
Your system prompt was migrated but verification failed. Your data has been saved to:
|
||
|
|
|
||
|
|
${d}
|
||
|
|
|
||
|
|
To recover:
|
||
|
|
1. Open the file and review the content
|
||
|
|
2. Move it to ${n}
|
||
|
|
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(n){ie("Failed to migrate legacy userSystemPrompt:",n);try{let o=await J8r(t,r,n.message||String(n));Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),new nu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Failed
|
||
|
|
|
||
|
|
An error occurred during migration. Your data has been saved to:
|
||
|
|
|
||
|
|
${o}
|
||
|
|
|
||
|
|
To recover:
|
||
|
|
1. Open the file and review the content
|
||
|
|
2. Move it to ${iC()}
|
||
|
|
3. The prompt will be available immediately`,"Migration Failed","OK","").open()}catch(o){ie("Failed to save to unsupported folder:",o),Ce("Preserving userSystemPrompt in settings for manual recovery"),new nu(app,()=>{},`Failed to migrate system prompt: ${n.message}
|
||
|
|
|
||
|
|
Unable to save to file system. Your system prompt is still in settings and will continue to work.
|
||
|
|
|
||
|
|
Please check:
|
||
|
|
- Folder permissions for ${iC()}
|
||
|
|
- Available disk space
|
||
|
|
- Vault is accessible
|
||
|
|
|
||
|
|
You can retry by reloading the plugin.`,"Migration Failed - Data Preserved","OK","").open()}}}rd();rd();na();function nLe(){let[t]=aw(),[e]=Gge(),[r]=YJ();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"})()}Xe();na();rd();xn();gr();Xe();u0();id();Qe();Mr();var ny=require("obsidian"),hr=$(K());var Or=$(K());Mr();xn();var UZ=$(K());xn();Mr();var zZ=({value:t,onChange:e,placeholder:r="Search..."})=>UZ.default.createElement("div",{className:"tw-relative"},UZ.default.createElement(ni,{type:"text",placeholder:r,value:t,onChange:n=>e(n.target.value),className:"tw-pr-10"}),t&&UZ.default.createElement(me,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},UZ.default.createElement(wO,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),UZ.default.createElement(B4,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}));var Sde=$(K());var lc=$(K(),1);var O$s=!!(typeof window<"u"&&window.document&&window.document.createElement);function VZ(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var X8r=$(K(),1);function G8r(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fbt(...t){return e=>{let r=!1,n=t.map(o=>{let i=G8r(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():G8r(t[o],null)}}}}function vde(...t){return X8r.useCallback(fbt(...t),t)}var J$=$(K(),1),Z8r=$(wt(),1);function Y8r(t,e=[]){let r=[];function n(i,a){let s=J$.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=J$.useMemo(()=>m,Object.values(m));return(0,Z8r.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=J$.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>J$.createContext(a));return function(s){let u=s?.[t]||i;return J$.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,Ndi(o,...e)]}function Ndi(...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 J$.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var pbt=$(K(),1);var Q8r=$(K(),1),M3=globalThis?.document?Q8r.useLayoutEffect:()=>{};var Ddi=pbt[" useId ".trim().toString()]||(()=>{}),jdi=0;function eGr(t){let[e,r]=pbt.useState(Ddi());return M3(()=>{t||r(n=>n??String(jdi++))},[t]),t||(e?`radix-${e}`:"")}var Rv=$(K(),1);var tGr=$(K(),1);function $di(t,e){return tGr.useReducer((r,n)=>e[r][n]??r,t)}var iLe=t=>{let{present:e,children:r}=t,n=Ldi(e),o=typeof r=="function"?r({present:n.isPresent}):Rv.Children.only(r),i=vde(n.ref,Fdi(o));return typeof r=="function"||n.isPresent?Rv.cloneElement(o,{ref:i}):null};iLe.displayName="Presence";function Ldi(t){let[e,r]=Rv.useState(),n=Rv.useRef(null),o=Rv.useRef(t),i=Rv.useRef("none"),a=t?"mounted":"unmounted",[s,u]=$di(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Rv.useEffect(()=>{let l=oLe(n.current);i.current=s==="mounted"?l:"none"},[s]),M3(()=>{let l=n.current,c=o.current;if(c!==t){let f=i.current,p=oLe(l);t?u("MOUNT"):p==="none"||l?.display==="none"?u("UNMOUNT"):u(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,u]),M3(()=>{if(e){let l,c=e.ownerDocument.defaultView??window,d=p=>{let h=oLe(n.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(u("ANIMATION_END"),!o.current)){let y=e.style.animation
|
||
|
|
|
||
|
|
`,Cmi=U3?"\xA0":hFe,MXr="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",RXr="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",xmi=new RegExp("^[^"+RXr+"]*["+MXr+"]"),Tmi=new RegExp("^[^"+MXr+"]*["+RXr+"]"),lb={bold:1,capitalize:1024,code:16,highlight:mFe,italic:2,lowercase:256,strikethrough:$de,subscript:32,superscript:64,underline:Lde,uppercase:512},Omi={directionless:1,unmergeable:2},$7r={center:D_t,end:F_t,justify:$_t,left:N_t,right:j_t,start:L_t},Emi={[D_t]:"center",[F_t]:"end",[$_t]:"justify",[N_t]:"left",[j_t]:"right",[L_t]:"start"},Pmi={normal:0,segmented:2,token:1},Mmi={[hmi]:"normal",[ymi]:"segmented",[gmi]:"token"},Rmi="$",L7r="$config";function IXr(t,e,r,n,o,i){let a=t.getFirstChild();for(;a!==null;){let s=a.__key;a.__parent===e&&(tt(a)&&IXr(a,s,r,n,o,i),r.has(s)||i.delete(s),o.push(s)),a=a.getNextSibling()}}var Imi=100,a_t=!1,k_t=0;function Ami(t){k_t=t.timeStamp}function Jbt(t,e,r){let n=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||n&&t.previousSibling===o)||n&&SFe(t,r)!==void 0}function Nmi(t,e,r){let n=hN(fC(r)),o=null,i=null;n!==null&&n.anchorNode===t&&(o=n.anchorOffset,i=n.focusOffset);let a=t.nodeValue;a!==null&&ivt(e,a,o,i,!1)}function Dmi(t,e,r){if(mn(t)){let n=t.anchor.getNode();if(n.is(r)&&t.format!==n.getFormat())return!1}return gN(e)&&r.isAttached()}function jmi(t,e,r,n){for(let o=t;o&&!eYr(o);o=Kde(o)){let i=SFe(o,e);if(i!==void 0){let a=yh(i,r);if(a)return Hu(a)||!c_(o)?void 0:[o,a]}else if(o===n)return[n,FZr(r)]}}function AXr(t,e,r){a_t=!0;let n=performance.now()-k_t>Imi;try{tS(t,()=>{let o=qs()||function(f){return f.getEditorState().read(()=>{let p=qs();return p!==null?p.clone():null})}(t),i=new Map,a=t.getRootElement(),s=t._editorState,u=t._blockCursorElement,l=!1,c="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,y=jmi(h,t,s,a);if(!y)continue;let[g,b]=y;if(m==="characterData")n&&Ar(b)&&gN(h)&&Dmi(o,h,b)&&Nmi(h,b,t);else if(m==="childList"){l=!0;let _=p.addedNodes;for(let O=0;O<_.length;O++){let E=_[O],P=$Zr(E),R=E.parentNode;if(R!=null&&E!==u&&P===null&&!Jbt(E,R,t)){if(U3){let I=(c_(E)?E.innerText:null)||E.nodeValue;I&&(c+=I)}R.removeChild(E)}}let w=p.removedNodes,T=w.length;if(T>0){let O=0;for(let E=0;E<T;E++){let P=w[E];(Jbt(P,h,t)||u===P)&&(h.appendChild(P),O++)}T!==O&&i.set(g,b)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=r.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let y=0;y<m.length;y++){let g=m[y],b=g.parentNode;b==null||g.nodeName!=="BR"||Jbt(g,h,t)||b.removeChild(g)}}r.takeRecords()}o!==null&&(l&&$v(o),U3&&VZr(t)&&o.insertRawText(c))})}finally{a_t=!1}}function NXr(t){let e=t._observer;e!==null&&AXr(t,e.takeRecords(),e)}function DXr(t){(function(e){k_t===0&&fC(e).addEventListener("textInput",Ami,!0)})(t),t._observer=new MutationObserver((e,r)=>{AXr(t,e,r)})}var s_t=class{constructor(e,r){this.key=e,this.parse=r.parse.bind(r),this.unparse=(r.unparse||kmi).bind(r),this.isEqual=(r.isEqual||Object.is).bind(r),this.defaultValue=this.parse(void 0)}};function $mi(t,e){return new s_t(t,e)}function YLe(t,e,r="latest"){let n=(r==="latest"?t.getLatest():t).__state;return n?n.getValue(e):e.defaultValue}function Lmi(t,e,r){let n=YLe(t,r,"direct"),o=YLe(e,r,"direct");return r.isEqual(n,o)?null:[n,o]}function Fmi(t,e,r){let n;if(ig(),typeof r=="function"){let i=t.getLatest(),a=YLe(i,e);if(n=r(a),e.isEqual(a,n))return i}else n=r;let o=t.getWritable();return q_t(o).updateFromKnown(e,n),o}function jXr(t){let e=new Map,r=new Set;for(let n=typeof t=="function"?t:t.replace;n.prototype&&n.prototype.getType!==void 0;n=Object.getPrototypeOf(n)){let{ownNodeConfig:o}=dvt(n);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let a;"stateConfig"in i?(a=i.stateConfig,i.flat&&r.add(a.key)):a=i,e.set(a.key,a)}}return{flatKeys:r,sharedConfigMap:e}}var u_t=class t{constructor(e,r,n=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=r,this.unknownState=n,this.knownState=o;let{sharedConfigMap:a}=this.sharedNodeState,s=i!==void 0?i:function(u,l,c){let
|
||
|
|
`)r.preventDefault(),wr(n,Mde,!1);else if(u===uL)r.preventDefault(),wr(n,h_t,void 0);else if(u==null&&r.dataTransfer){let p=r.dataTransfer.getData("text/plain");r.preventDefault(),a.insertRawText(p)}else u!=null&&fZr(a,i,u,r.timeStamp,!0)?(r.preventDefault(),wr(n,nY,u)):tY=u;cZr=r.timeStamp}})}(t,e)]);var Rde=0,lZr=null,cZr=0,tY=null,oFe=new WeakMap,v_t=!1,w_t=!1,Ide=!1,Ode=!1,Gbt=!1,Xbt="",q3=null,dZr=[0,"",0,"root",0];function fZr(t,e,r,n,o){let i=t.anchor,a=t.focus,s=i.getNode(),u=dc(),l=hN(fC(u)),c=l!==null?l.anchorNode:null,d=i.key,f=u.getElementByKey(d),p=r.length;return d!==a.key||!Ar(s)||(!o&&(!GLe||cZr<n+50)||s.isDirty()&&p<2||kZr(r))&&i.offset!==a.offset&&!s.isComposing()||rL(s)||s.isDirty()&&p>1||(o||!GLe)&&f!==null&&!s.isComposing()&&c!==J3(f)||l!==null&&e!==null&&(!e.collapsed||e.startContainer!==l.anchorNode||e.startOffset!==l.anchorOffset)||s.getFormat()!==t.format||s.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let y=m.anchor.offset,g=h.getParentOrThrow(),b=AU(h);return y===0?!h.canInsertTextBefore()||!g.canInsertTextBefore()&&!h.isComposing()||b||function(_){let w=_.getPreviousSibling();return(Ar(w)||tt(w)&&w.isInline())&&!w.canInsertTextAfter()}(h):y===h.getTextContentSize()&&(!h.canInsertTextAfter()||!g.canInsertTextAfter()&&!h.isComposing()||b)}(t,s)}function J7r(t,e){return gN(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function K7r(t,e,r){let{anchorNode:n,anchorOffset:o,focusNode:i,focusOffset:a}=t;v_t&&(v_t=!1,J7r(n,o)&&J7r(i,a)&&!q3)||tS(e,()=>{if(!r)return void $v(null);if(!Wde(e,n,i))return;let s=qs();if(q3&&mn(s)&&s.isCollapsed()){let u=s.anchor,l=q3.anchor;(u.key===l.key&&u.offset===l.offset+1||u.offset===1&&l.getNode().is(u.getNode().getPreviousSibling()))&&(s=q3.clone(),$v(s))}if(q3=null,mn(s)){let u=s.anchor,l=u.getNode();if(s.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(s.dirty=!0);let c=fC(e).event,d=c?c.timeStamp:performance.now(),[f,p,m,h,y]=dZr,g=jv(),b=e.isComposing()===!1&&g.getTextContent()==="";if(d<y+200&&u.offset===m&&u.key===h)WLe(s,f,p);else if(u.type==="text")Ar(l)||it(141),pZr(s,l);else if(u.type==="element"&&!b){tt(l)||it(259);let _=u.getNode();_.isEmpty()?function(w,T){let O=T.getTextFormat(),E=T.getTextStyle();WLe(w,O,E)}(s,_):WLe(s,0,"")}}else{let c=u.key,d=s.focus.key,f=s.getNodes(),p=f.length,m=s.isBackward(),h=m?a:o,y=m?o:a,g=m?d:c,b=m?c:d,_=PXr,w=!1;for(let T=0;T<p;T++){let O=f[T],E=O.getTextContentSize();if(Ar(O)&&E!==0&&!(T===0&&O.__key===g&&h===E||T===p-1&&O.__key===b&&y===0)&&(w=!0,_&=O.getFormat(),_===0))break}s.format=w?_:0}}wr(e,B_t,void 0)})}function WLe(t,e,r){t.format===e&&t.style===r||(t.format=e,t.style=r,t.dirty=!0)}function pZr(t,e){WLe(t,e.getFormat(),e.getStyle())}function mZr(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function qLe(t,e){let r=t._compositionKey;if(ag(null),r!==null&&e!=null){if(e===""){let n=yh(r),o=J3(t.getElementByKey(r));return void(o!==null&&o.nodeValue!==null&&Ar(n)&&ivt(n,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
|
||
|
|
`){let n=qs();if(mn(n)){let o=n.focus;return n.anchor.set(o.key,o.offset,o.type),void wr(t,nFe,null)}}}ovt(!0,t,e)}function hZr(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var oY=new Map;function gZr(t){let e=GZr(t.target);if(e===null)return;let r=rvt(e.anchorNode);if(r===null)return;w_t&&(w_t=!1,tS(r,()=>{let u=G3(),l=e.anchorNode;(c_(l)||gN(l))&&$v(_Fe(u,e,r,t))}));let n=nvt(r),o=n[n.length-1],i=o._key,a=oY.get(i),s=a||o;s!==r&&K7r(e,s,!1),K7r(e,r,!0),r!==o?oY.set(i,r):a&&oY.delete(i)}function G7r(t){t._lexicalHandled=!0}function X7r(t){return t._lexicalHandled===!0}var Ymi=()=>{};function Qmi(t){let e=t.ownerDocument,r=oFe.get(e);if(r===void 0)return void Ymi();let n=r-1;n>=0||it(164),oFe.set(e,n),n===0&&e.removeEventListener("selectionchange",gZr);let o=Jde(t);wFe(o)?(function(a){if(a._parentEditor!==null){let s=nvt(a),u=s[s.length-1]._key;oY.get(u)===a&&oY.delete(u)}else oY.delete(a._key)}(o),t.__lexicalEditor=null):o&&it(198);let i=hZr(t);for(let a=0;a<i.length;a++)i[a]();t.__lexicalEventHandles=[]}function S_t(t,e,r){ig();let n=t.__key,o=t.getParent();if(o===null)return;let i=function(s){let u=qs();if(!mn(u)||!tt(s))return u;let{anchor:l,focus:c}=u,d=l.getNode(),f=c.getNode();return fFe(d,s)&&l.set(s.__key,0,"element"),fFe(f,s)&&c.set(s.__key,0,"element"),u}(t),a=!1;if(mn(i)&&e){let s=i.anchor,u=i.focus;s.key===n&&(sFe(s,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0),u.key===n&&(sFe(u,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0)}else bFe(i)&&e&&t.isSelected()&&t.selectPrevious();if(mn(i)&&e&&!a){let s=t.getIndexWithinParent();NU(t),aFe(i,o,s,-1)}else NU(t);r||xT(o)||o.canBeEmpty()||!o.isEmpty()||S_t(o,e),e&&i&&Nv(o)&&o.isEmpty()&&o.selectEnd()}function ehi(t){return t}var jU=class{static getType(){let{ownNodeType:e}=dvt(this);return e===void 0&&it(64,this.name),e}static clone(e){it(65,this.name)}$config(){return{}}config(e,r){let n=r.extends||Object.getPrototypeOf(this.constructor);return Object.assign(r,{extends:n,type:e}),{[e]:r}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),jZr(this,e)}getType(){return this.__type}isInline(){it(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let r=yh(e);if(r===null)break;e=r.__parent}return!1}isSelected(e){let r=e||qs();if(r==null)return!1;let n=r.getNodes().some(o=>o.__key===this.__key);if(Ar(this))return n;if(mn(r)&&r.anchor.type==="element"&&r.focus.type==="element"){if(r.isCollapsed())return!1;let o=this.getParent();if(Hu(this)&&this.isInline()&&o){let i=r.isBackward()?r.focus:r.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return n}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let r=e.getFirstChild(),n=0;for(;r!==null;){if(this.is(r))return n;n++,r=r.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:yh(e)}getParentOrThrow(){let e=this.getParent();return e===null&&it(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let r=e.getParent();if(xT(r))return tt(e)||e===this&&Hu(e)||it(194),e;e=r}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&it(67,this.__key),e}getParents(){let e=[],r=this.getParent();for(;r!==null;)e.push(r),r=r.getParent();return e}getParentKeys(){let e=[],r=this.getParent();for(;r!==null;)e.push(r.__key),r=r.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:yh(e)}getPreviousSiblings(){let e=[],r=this.getParent();if(r===null)return e;let n=r.getFirstChild();for(;n!==null&&!n.is(this);)e.push(n),n=n.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?nu
|
||
|
|
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(r){let n=r.parentElement;if(n!==null&&P_t(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&BLe(o)){let i=n.lastChild;if(i===r||i.previousSibling===r&&BLe(i))return!0}}return!1}(e)||function(r){let n=r.parentElement;if(n!==null&&P_t(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&BLe(o))return!1;let i=n.lastChild;if(i===r||i.previousSibling===r&&BLe(i))return!0}return!1}(e)?null:{conversion:thi,priority:0}}}static importJSON(e){return lY().updateFromJSON(e)}};function thi(t){return{node:lY()}}function lY(){return Gde(new uY)}function B3(t){return t instanceof uY}function BLe(t){return gN(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function Zbt(t,e){return 16&e?"code":e&mFe?"mark":32&e?"sub":64&e?"sup":null}function Ybt(t,e){return 1&e?"strong":2&e?"em":"span"}function yZr(t,e,r,n,o){let i=n.classList,a=iY(o,"base");a!==void 0&&i.add(...a),a=iY(o,"underlineStrikethrough");let s=!1,u=e&Lde&&e&$de;a!==void 0&&(r&Lde&&r&$de?(s=!0,u||i.add(...a)):u&&i.remove(...a));for(let l in lb){let c=lb[l];if(a=iY(o,l),a!==void 0)if(r&c){if(s&&(l==="underline"||l==="strikethrough")){e&c&&i.remove(...a);continue}e&c&&(!u||l!=="underline")&&l!=="strikethrough"||i.add(...a)}else e&c&&i.remove(...a)}}function bZr(t,e,r){let n=e.firstChild,o=r.isComposing(),i=t+(o?hFe:"");if(n==null)e.textContent=i;else{let a=n.nodeValue;if(a!==i)if(o||U3){let[s,u,l]=function(c,d){let f=c.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&c[m]===d[m];)m++;for(;h+m<f&&h+m<p&&c[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(a,i);u!==0&&n.deleteData(s,u),n.insertData(s,l)}else n.nodeValue=i}}function Z7r(t,e,r,n,o,i){bZr(o,t,e);let a=i.theme.text;a!==void 0&&yZr(0,0,n,t,a)}function ULe(t,e){let r=document.createElement(e);return r.appendChild(t),r}var H3=class t extends jU{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",r){super(r),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return Mmi[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===IU()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let r=lb[e];return!!(this.getFormat()&r)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,r){return cFe(this.getLatest().__format,e,r)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,r){let n=this.__format,o=Zbt(0,n),i=Ybt(0,n),a=o===null?i:o,s=document.createElement(a),u=s;this.hasFormat("code")&&s.setAttribute("spellcheck","false"),o!==null&&(u=document.createElement(i),s.appendChild(u)),Z7r(u,this,0,n,this.__text,e);let l=this.__style;return l!==""&&(s.style.cssText=l),s}updateDOM(e,r,n){let o=this.__text,i=e.__format,a=this.__format,s=Zbt(0,i),u=Zbt(0,a),l=Ybt(0,i),c=Ybt(0,a);if((s===null?l:s)!==(u===null?c:u))return!0;if(s===u&&l!==c){let h=r.firstChild;h==null&&it(48);let y=document.createElement(c);return Z7r(y,this,0,a,o,n),r.replaceChild(y,h),!1}let d=r;u!==null&&s!==null&&(d=r.firstChild,d==null&&it(49)),bZr(o,d,this);let f=n.theme.text;f!==void 0&&i!==a&&yZr(0,i,a,d,f);let p=e.__style,m=this.__style;return p!==m&&(r.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:ihi,priority:0}),b:()=>({conversion:nhi,priority:0}),code:()=>({conversion:eL,priority:0}),em:()=>({conversion:eL,priority:0}),i:()=>({conversion:eL,priority:0}),mark:()=>({conversion:eL,priority:0}),s:()=>({conversion:eL,priority:0}),span:()=>({conversion:rhi,priority:0}),strong:()=>({conversion:eL,priority:0}),sub
|
||
|
|
`||s===`\r
|
||
|
|
`?o.push(lY()):s===" "?o.push(yFe()):s!==""&&o.push(og(s))}return{node:o}}if(r=r.replace(/\r/g,"").replace(/[ \t\n]+/g," "),r==="")return{node:null};if(r[0]===" "){let n=e,o=!0;for(;n!==null&&(n=Q7r(n,!1))!==null;){let i=n.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(r=r.slice(1)),o=!1;break}}o&&(r=r.slice(1))}if(r[r.length-1]===" "){let n=e,o=!0;for(;n!==null&&(n=Q7r(n,!0))!==null;)if((n.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(r=r.slice(0,r.length-1))}return r===""?{node:null}:{node:og(r)}}function Q7r(t,e){let r=t;for(;;){let n;for(;(n=e?r.nextSibling:r.previousSibling)===null;){let i=r.parentElement;if(i===null)return null;r=i}if(r=n,c_(r)){let i=r.style.display;if(i===""&&!ZZr(r)||i!==""&&!i.startsWith("inline"))return null}let o=r;for(;(o=e?r.firstChild:r.lastChild)!==null;)r=o;if(gN(r))return r;if(r.nodeName==="BR")return null}}var ahi={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function eL(t){let e=ahi[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:J_t(t.style,e),node:null}}function og(t=""){return Gde(new H3(t))}function Ar(t){return t instanceof H3}function J_t(t,e){let r=t.fontWeight,n=t.textDecoration.split(" "),o=r==="700"||r==="bold",i=n.includes("line-through"),a=t.fontStyle==="italic",s=n.includes("underline"),u=t.verticalAlign;return l=>(Ar(l)&&(o&&!l.hasFormat("bold")&&l.toggleFormat("bold"),i&&!l.hasFormat("strikethrough")&&l.toggleFormat("strikethrough"),a&&!l.hasFormat("italic")&&l.toggleFormat("italic"),s&&!l.hasFormat("underline")&&l.toggleFormat("underline"),u!=="sub"||l.hasFormat("subscript")||l.toggleFormat("subscript"),u!=="super"||l.hasFormat("superscript")||l.toggleFormat("superscript"),e&&!l.hasFormat(e)&&l.toggleFormat(e)),l)}var cY=class t extends H3{static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super(" ",e),this.__detail=2}static importDOM(){return null}createDOM(e){let r=super.createDOM(e),n=iY(e.theme,"tab");return n!==void 0&&r.classList.add(...n),r}static importJSON(e){return yFe().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&it(126),super.setTextContent(" ")}spliceText(e,r,n,o){return n===""&&r===0||n===" "&&r===1||it(286),this}setDetail(e){return e!==2&&it(127),this}setMode(e){return e!=="normal"&&it(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function yFe(){return Gde(new cY)}function K_t(t){return t instanceof cY}var C_t=class{constructor(e,r,n){this._selection=null,this.key=e,this.offset=r,this.type=n}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:hvt(_T(kU(this,"next")),_T(kU(e,"next")))<0}getNode(){let e=yh(this.key);return e===null&&it(20),e}set(e,r,n,o){let i=this._selection,a=this.key;o&&this.key===e&&this.offset===r&&this.type===n||(this.key=e,this.offset=r,this.type=n,vY()||(IU()===a&&ag(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function CT(t,e,r){return new C_t(t,e,r)}function Qbt(t,e){let r=e.__key,n=t.offset,o="element";if(Ar(e)){o="text";let i=e.getTextContentSize();n>i&&(n=i)}else if(!tt(e)){let i=e.getNextSibling();if(Ar(i))r=i.__key,n=0,o="text";else{let a=e.getParent();a&&(r=a.__key,n=e.getIndexWithinParent()+1)}}t.set(r,n,o)}function eXr(t,e){if(tt(e)){let r=e.getLastDescendant();tt(r)||Ar(r)?Qbt(t,r):Qbt(t,e)}else Qbt(t,e)}var iFe=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!bFe(e))return!1;let r=this._nodes,n=e._nodes;return r.size===n.size&&Array.from(r).every(o=>n.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){re
|
||
|
|
`),c=!f.isEmpty();else if(c=!1,Ar(f)){let p=f.getTextContent();f===r?f===n?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=s<u?p.slice(s,u):p.slice(u,s)):p=a?p.slice(s):p.slice(u):f===n&&(p=a?p.slice(0,u):p.slice(0,s)),l+=p}else!Hu(f)&&!B3(f)||f===n&&this.isCollapsed()||(l+=f.getTextContent())}return l}applyDOMRange(e){let r=dc(),n=r.getEditorState()._selection,o=vZr(e.startContainer,e.startOffset,e.endContainer,e.endOffset,r,n);if(o===null)return;let[i,a]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(a.key,a.offset,a.type,!0),QLe(this)}clone(){let e=this.anchor,r=this.focus;return new t(CT(e.key,e.offset,e.type),CT(r.key,r.offset,r.type),this.format,this.style)}toggleFormat(e){this.format=cFe(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let r=lb[e];return!!(this.format&r)}insertRawText(e){let r=e.split(/(\r?\n|\t)/),n=[],o=r.length;for(let i=0;i<o;i++){let a=r[i];a===`
|
||
|
|
`||a===`\r
|
||
|
|
`?n.push(lY()):a===" "?n.push(yFe()):n.push(og(a))}this.insertNodes(n)}insertText(e){let r=this.anchor,n=this.focus,o=this.format,i=this.style,a=r,s=n;!this.isCollapsed()&&n.isBefore(r)&&(a=n,s=r),a.type==="element"&&function(y,g,b,_){let w=y.getNode(),T=w.getChildAtIndex(y.offset),O=og(),E=Nv(w)?aL().append(O):O;O.setFormat(b),O.setStyle(_),T===null?w.append(E):T.insertBefore(E),y.is(g)&&g.set(O.__key,0,"text"),y.set(O.__key,0,"text")}(a,s,o,i),s.type==="element"&&_Y(s,_T(kU(s,"next")));let u=a.offset,l=s.offset,c=this.getNodes(),d=c.length,f=c[0];Ar(f)||it(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=c[d-1];if(d===1&&s.type==="element"&&(l=p,s.set(a.key,l,"text")),this.isCollapsed()&&u===p&&(rL(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let y=f.getNextSibling();if(Ar(y)&&y.canInsertTextBefore()&&!rL(y)||(y=og(),y.setFormat(o),y.setStyle(i),m.canInsertTextAfter()?f.insertAfter(y):m.insertAfter(y)),y.select(0,0),f=y,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&u===0&&(rL(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let y=f.getPreviousSibling();if(Ar(y)&&!rL(y)||(y=og(),y.setFormat(o),m.canInsertTextBefore()?f.insertBefore(y):m.insertBefore(y)),y.select(),f=y,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&u!==p){let y=og(f.getTextContent());y.setFormat(o),f.replace(y),f=y}else if(!this.isCollapsed()&&e!==""){let y=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||tt(y)&&(!y.canInsertTextBefore()||!y.canInsertTextAfter()))return this.insertText(""),_Zr(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(AU(f)){let _=og(e);return _.select(),void f.replace(_)}let y=f.getFormat(),g=f.getStyle();if(u!==l||y===o&&g===i){if(K_t(f)){let _=og(e);return _.setFormat(o),_.setStyle(i),_.select(),void f.replace(_)}}else{if(f.getTextContent()!==""){let _=og(e);if(_.setFormat(o),_.setStyle(i),_.select(),u===0)f.insertBefore(_,!1);else{let[w]=f.splitText(u);w.insertAfter(_,!1)}return void(_.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let b=l-u;f=f.spliceText(u,b,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=y,this.style=g))}else{let y=new Set([...f.getParentKeys(),...h.getParentKeys()]),g=tt(f)?f:f.getParentOrThrow(),b=tt(h)?h:h.getParentOrThrow(),_=h;if(!g.is(b)&&b.isInline())do _=b,b=b.getParentOrThrow();while(b.isInline());if(s.type==="text"&&(l!==0||h.getTextContent()==="")||s.type==="element"&&h.getIndexWithinParent()<l)if(Ar(h)&&!AU(h)&&l!==h.getTextContentSize()){if(h.isSegmented()){let P=og(h.getTextContent());h.replace(P),h=P}Nv(s.getNode())||s.type!=="text"||(h=h.spliceText(0,l,"")),y.add(h.__key)}else{let P=h.getParentOrThrow();P.canBeEmpty()||P.getChildrenSize()!==1?h.remove():P.remove()}else y.add(h.__key);let w=b.getChildren(),T=new Set(c),O=g.is(b),E=g.isInline()&&f.getNextSibling()===null?g:f;for(let P=w.length-1;P>=0;P--){let R=w[P];if(R.is(f)||tt(R)&&R.isParentOf(f))break;R.isAttached()&&(!T.has(R)||R.is(_)?O||E.insertAfter(R,!1):R.remove())}if(!O){let P=b,R=null;for(;P!==null;){let I=P.getChildren(),A=I.length;(A===0||I[A-1].is(R))&&(y.delete(P.__key),R=P),P=P.getParent()}}if(AU(f))if(u===p)f.select();else{let P=og(e);P.select(),f.replace(P)}else f=f.spliceText(u,p-u,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let P=1;P<d;P++){let R=c[P],I=R.__key;y.has(I)||R.remove()}}}removeText(){let e=qs()===this;Dde(this,oYr(A_t(this))),e&&qs()!==this&&$v(this)}formatText(e,r=null){if(this.isCollapsed())return this.toggleFormat(e),void ag(null);let n=this.getNodes(),o=[];for(let w of n)Ar(w)&&o.push(w);let i=w=>{n.forEach(T=>{if(tt(T)){let O=T.getFormatFlags(e,w);T.setTextFormat(O)}})},a=o.length;if(a===0)return this.toggleFormat(e),ag(null),void i(r);let s=this.anchor,u=this.focus,l=this.isBackward(),c=l?u:s,d=l?s:u,f=0,p=o[0],m=c.type==="element"?0:c.of
|
||
|
|
|
||
|
|
`);let u=s.length;if(!Yi(n)||o>=u){let l=n.getParent();n.remove(),l==null||l.getChildrenSize()!==0||xY(l)||l.remove(),o-=u+a,n=i}else{let l=n.getKey(),c=t.getEditorState().read(()=>{let p=pYr(l);return Yi(p)&&p.isSimpleText()?p.getTextContent():null}),d=u-o,f=s.slice(0,d);if(c!==null&&c!==s){let p=Zde(),m=n;if(n.isSimpleText())n.setTextContent(c);else{let h=rS(c);n.replace(h),m=h}if(jr(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(n.isSimpleText()){let p=e.key===l,m=e.offset;m<o&&(m=u);let h=p?m-o:0,y=p?m:d;if(p&&h===0){let[g]=n.splitText(h,y);g.remove()}else{let[,g]=n.splitText(h,y);g.remove()}}else{let p=rS(f);n.replace(p)}o=0}}}function Bgi(t){let e=t.getStyle(),r=XQr(e);ske.set(e,r)}function Hvt(t,e){(jr(t)?t.isCollapsed():Yi(t)||gi(t))||Kvt(280);let r=uke(jr(t)?t.style:Yi(t)?t.getStyle():t.getTextStyle()),n=Object.entries(e).reduce((i,[a,s])=>(typeof s=="function"?i[a]=s(r[a],t):s===null?delete i[a]:i[a]=s,i),{...r}),o=ZQr(n);jr(t)||Yi(t)?t.setStyle(o):t.setTextStyle(o),ske.set(o,n)}function Ugi(t,e){if(jr(t)&&t.isCollapsed()){Hvt(t,e);let r=t.anchor.getNode();gi(r)&&r.isEmpty()&&Hvt(r,e)}QQr(r=>{Hvt(r,e)})}function QQr(t){let e=Sn();if(!e)return;let r=new Map;if(jr(e))for(let i of sYr(e).getTextSlices())i&&r.set(i.caret.origin.getKey(),i.getSliceIndices());let n=e.getNodes();for(let i of n){if(!Yi(i)||!i.canHaveFormat())continue;let[a,s]=(o=i,r.get(o.getKey())||[0,o.getTextContentSize()]);s!==a&&(Svt(i)||a===0&&s===i.getTextContentSize()?t(i):t(i.splitText(a,s)[a===0?0:1]))}var o;jr(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&een(e)}function een(t){if(t.isBackward()){let{anchor:e,focus:r}=t,{key:n,offset:o,type:i}=e;e.set(r.key,r.offset,r.type),r.set(n,o,i)}}function ten(t,e){let r=t.getFormatType(),n=t.getIndent();r!==e.getFormatType()&&e.setFormat(r),n!==e.getIndent()&&e.setIndent(n)}function zgi(t,e,r=ten){if(t===null)return;let n=t.getStartEndPoints(),o=new Map,i=null;if(n){let[a,s]=n;i=TFe(),i.anchor.set(a.key,a.offset,a.type),i.focus.set(s.key,s.offset,s.type);let u=Jvt(a.getNode(),tfe),l=Jvt(s.getNode(),tfe);gi(u)&&o.set(u.getKey(),u),gi(l)&&o.set(l.getKey(),l)}for(let a of t.getNodes())if(gi(a)&&tfe(a))o.set(a.getKey(),a);else if(n===null){let s=Jvt(a,tfe);gi(s)&&o.set(s.getKey(),s)}for(let[a,s]of o){let u=e();r(s,u),s.replace(u,!0),i&&(a===i.anchor.key&&i.anchor.set(u.getKey(),i.anchor.offset,i.anchor.type),a===i.focus.key&&i.focus.set(u.getKey(),i.focus.offset,i.focus.type))}i&&t.is(Sn())&&Z3(i)}function GQr(t){return t.getNode().isAttached()}function Vgi(t){let e=t;for(;e!==null&&!X3(e);){let r=e.getLatest(),n=e.getParent();r.getChildrenSize()===0&&e.remove(!0),e=n}}function Hgi(t,e,r=null){let n=t.getStartEndPoints(),o=n?n[0]:null,i=t.getNodes(),a=i.length;if(o!==null&&(a===0||a===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let l=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),c=l.getChildren(),d=e();return d.setFormat(l.getFormatType()),d.setIndent(l.getIndent()),c.forEach(f=>d.append(f)),r&&(d=r.append(d)),void l.replace(d)}let s=null,u=[];for(let l=0;l<a;l++){let c=i[l];X3(c)?(Wvt(t,u,u.length,e,r),u=[],s=c):s===null||s!==null&&hYr(c,s)?u.push(c):(Wvt(t,u,u.length,e,r),u=[c])}Wvt(t,u,u.length,e,r)}function Wvt(t,e,r,n,o=null){if(e.length===0)return;let i=e[0],a=new Map,s=[],u=gi(i)?i:i.getParentOrThrow();u.isInline()&&(u=u.getParentOrThrow());let l=!1;for(;u!==null;){let m=u.getPreviousSibling();if(m!==null){u=m,l=!0;break}if(u=u.getParentOrThrow(),X3(u))break}let c=new Set;for(let m=0;m<r;m++){let h=e[m];gi(h)&&h.getChildrenSize()===0&&c.add(h.getKey())}let d=new Set;for(let m=0;m<r;m++){let h=e[m],y=h.getParent();if(y!==null&&y.isInline()&&(y=y.getParent()),y!==null&&yYr(h)&&!d.has(h.getKey())){let g=y.getKey();if(a.get(g)===void 0){let b=n();b.setFormat(y.getFormatType()),b.setIndent(y.getIndent()),s.push(b),a.set(g,b),y.getChildren().forEach(_=>{b.append(_),d.add(_.getKey()),gi(_)&&_.getChildrenKeys().forEach(w=>d.add(w))}),Vgi(y)}}else if(c.has(h.getKey())){gi(h)||Kvt(179);let g=n();g.setFormat(h.getFormatType()),g
|
||
|
|
`||c===`\r
|
||
|
|
`?l.insertParagraph():c===" "?l.insertNodes([uYr()]):l.insertText(c)}}}else e.insertRawText(a)}function awt(t,e,r){t.dispatchCommand(XYr,{nodes:e,selection:r})||(r.insertNodes(e),function(n){if(jr(n)&&n.isCollapsed()){let o=n.anchor,i=null,a=CY(o,"previous");if(a)if(MFe(a))i=a.origin;else{let s=cYr(a,zU(Ci(),"next").getFlipped());for(let u of s){if(Yi(u.origin)){i=u.origin;break}if(gi(u.origin)&&!u.origin.isInline())break}}if(i&&Yi(i)){let s=i.getFormat(),u=i.getStyle();n.format===s&&n.style===u||(n.format=s,n.style=u,n.dirty=!0)}}}(r))}function Den(t,e,r,n=[]){let o=e===null||r.isSelected(e),i=gi(r)&&r.excludeFromCopy("html"),a=r;if(e!==null){let l=UU(r);l=Yi(l)&&e!==null?lke(e,l):l,a=l}let s=gi(a)?a.getChildren():[],u=function(l){let c=l.exportJSON(),d=l.constructor;if(c.type!==d.getType()&&dke(58,d.name),gi(l)){let f=c.children;Array.isArray(f)||dke(59,d.name)}return c}(a);if(Yi(a)){let l=a.__text;l.length>0?u.text=l:o=!1}for(let l=0;l<s.length;l++){let c=s[l],d=Den(t,e,c,u.children);!o&&gi(r)&&d&&r.extractWithChild(c,e,"clone")&&(o=!0)}if(o&&!i)n.push(u);else if(Array.isArray(u.children))for(let l=0;l<u.children.length;l++){let c=u.children[l];n.push(c)}return o}function jen(t,e){let r=[],n=Ci().getChildren();for(let o=0;o<n.length;o++)Den(t,e,n[o],r);return{namespace:t._config.namespace,nodes:r}}function $en(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r],o=wYr(n);Yi(o)&&oen(o),e.push(o)}return e}var NY=null;async function Wyi(t,e,r){if(NY!==null)return!1;if(e!==null)return new Promise((l,c)=>{t.update(()=>{l(Ien(t,e,r))})});let n=t.getRootElement(),o=t._window||window,i=window.document,a=Tvt(o);if(n===null||a===null)return!1;let s=i.createElement("span");s.style.cssText="position: fixed; top: -1000px;",s.append(i.createTextNode("#")),n.append(s);let u=new Range;return u.setStart(s,0),u.setEnd(s,1),a.removeAllRanges(),a.addRange(u),new Promise((l,c)=>{let d=t.registerCommand(AFe,f=>(hfe(f,ClipboardEvent)&&(d(),NY!==null&&(window.clearTimeout(NY),NY=null),l(Ien(t,f,r))),!0),IFe);NY=window.setTimeout(()=>{d(),NY=null,l(!1)},50),i.execCommand("copy"),s.remove()})}function Ien(t,e,r){if(r===void 0){let o=Tvt(t._window);if(!o)return!1;let i=o.anchorNode,a=o.focusNode;if(i!==null&&a!==null&&!iQr(t,i,a))return!1;let s=Sn();if(s===null)return!1;r=Len(s)}e.preventDefault();let n=e.clipboardData;return n!==null&&(Fen(n,r),!0)}var Jyi=[["text/html",Aen],["application/x-lexical-editor",Nen]];function Len(t=Sn()){let e={"text/plain":t?t.getTextContent():""};if(t){let r=OFe();for(let[n,o]of Jyi){let i=o(r,t);i!==null&&(e[n]=i)}}return e}function Fen(t,e){for(let r in e){let n=e[r];n!==void 0&&t.setData(r,n)}}var SN=swt,kHs=SN.$generateJSONFromSelectedNodes,qHs=SN.$generateNodesFromSerializedNodes,BHs=SN.$getClipboardDataFromSelection,ken=SN.$getHtmlContent,UHs=SN.$getLexicalContent,uwt=SN.$insertDataTransferForPlainText,zHs=SN.$insertDataTransferForRichText,VHs=SN.$insertGeneratedNodes,HHs=SN.copyToClipboard,WHs=SN.setLexicalClipboardDataTransfer;var lwt={};En(lwt,{registerPlainText:()=>Qyi});var DY=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,Kyi=DY&&"documentMode"in document?document.documentMode:null,Gyi=!(!DY||!("InputEvent"in window)||Kyi)&&"getTargetRanges"in new window.InputEvent("input"),Xyi=DY&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),qen=DY&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Zyi=DY&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Yyi=DY&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!Zyi;function Ben(t,e){e.update(()=>{if(t!==null){let r=hfe(t,KeyboardEvent)?null:t.clipboardData,n=Sn();if(n!==null&&r!=null){t.preventDefault();let o=ken(e);o!==null&&r.setData("text/html",o),r.setData("text/plain",n.getTextContent())}}})}function Qyi(t){return gL(t.registerCommand(TY,e=>{let r=Sn();return!!jr(r)&&(r.deleteCharacter(e),!0)},nl),t.registerCommand(DYr,e=>{let r=Sn();return!!jr(r)&&(r.deleteWord(e),!0)},nl),t.registerCommand(NYr,e=>{let r=Sn();return!!jr(r)&&(r.deleteLine(e),!0)},nl),t.registerCommand(IYr,e=>{let r=Sn();if(!jr(r))return!1;if(ty
|
||
|
|
`)};function xtn({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:r,onActiveWebTabRemoved:n}){return QU.default.createElement(QU.default.Fragment,null,QU.default.createElement(IT,{config:Fbi,onChange:t,onRemoved:e}),(r||n)&&QU.default.createElement(kbi,{onActiveWebTabAdded:r,onActiveWebTabRemoved:n}))}function kbi({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let r={isPillNode:Lvt,extractData:()=>!0,getKey:()=>"active-web-tab"},n=QU.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=QU.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return QU.default.createElement(IT,{config:r,onChange:n,onRemoved:o})}var Ttn=$(K());function Otn({enableURLPills:t=!1,onImagePaste:e}){let[r]=Di();return Ttn.default.useEffect(()=>r.registerCommand(jFe,n=>{let o=n.clipboardData;if(!o)return!1;if(e){let p=o.items;if(p){let m=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0)return n.preventDefault(),Promise.all(m.map(h=>h.getAsFile())).then(h=>{let y=h.filter(g=>g!==null);y.length>0&&e(y)}),!0}}let i=o.getData("text/plain"),a=i.includes("[["),s=t&&i.includes("http"),u=i.includes("@"),l=i.includes("#"),c=i.includes("{")&&i.includes("}");if(!i||!a&&!s&&!u&&!l&&!c)return!1;let d=Cke(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return d.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(n.preventDefault(),r.update(()=>{let p=Sn();if(!jr(p))return;let m=xke(d);m.length>0&&p.insertNodes(m)}),!0):!1},pL),[r,t,e]),null}var Etn=$(K());function Ptn(){let[t]=Di();return Etn.default.useEffect(()=>t.registerCommand(Ske,e=>{let{text:r,options:n={}}=e;return t.update(()=>{otn(r,n)}),!0},nl),[t]),null}var Fv=$(K());var Mtn=(0,Fv.createContext)(void 0);function ez(){let t=(0,Fv.useContext)(Mtn);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function Rtn({children:t}){let[e,r]=(0,Fv.useState)(null),[n,o]=(0,Fv.useState)(null),i=(0,Fv.useCallback)(c=>{r(c)},[]),a=(0,Fv.useCallback)(c=>{o(()=>c)},[]),s=(0,Fv.useCallback)((c,d=!1)=>{e&&e.dispatchCommand(Ske,{text:c,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),u=(0,Fv.useCallback)(()=>{n&&n()},[n]),l={insertTextWithPills:s,focusInput:u,registerEditor:i,registerFocusHandler:a};return Fv.default.createElement(Mtn.Provider,{value:l},t)}zr();Xe();rd();Qe();var qbi=({value:t,onChange:e,onSubmit:r,placeholder:n="Type a message...",disabled:o=!1,className:i="",onNotesChange:a,onNotesRemoved:s,onURLsChange:u,onURLsRemoved:l,onToolsChange:c,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:y,onWebTabsRemoved:g,onActiveWebTabAdded:b,onActiveWebTabRemoved:_,onEditorReady:w,onImagePaste:T,onTagSelected:O,isCopilotPlus:E=!1,currentActiveFile:P=null,currentChain:R})=>{let[I,A]=Qi.default.useState(null),[B,k]=Qi.default.useState(null),q=ez(),Z=kr(),V=Qi.default.useCallback(re=>{A(()=>re)},[]);(0,Qi.useEffect)(()=>{B&&q.registerEditor(B)},[B,q]),(0,Qi.useEffect)(()=>{I&&q.registerFocusHandler(I)},[I,q]);let Y=Qi.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[WU,JU,t6,mL,hL,KU,...u?[e6]:[]],onError:re=>{ie("Lexical error:",re)},editable:!o}),[u,o]),X=(0,Qi.useCallback)(re=>{re.read(()=>{let le=Ci().getTextContent();e(le)})},[e]),W=(0,Qi.useCallback)(re=>{k(re),w?.(re)},[w]);return Qi.default.createElement(ike,{initialConfig:Y},Qi.default.createElement(YFe,{currentActiveFile:P},Qi.default.createElement("div",{className:Se("tw-relative",i)},Qi.default.createElement(pke,{contentEditable:Qi.default.createElement(mke,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Qi.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},n),ErrorBoundary:wke}),Qi
|
||
|
|
|
||
|
|
\u2026 (truncated ${(r.length-yfe).toLocaleString()} characters for display)`:r}catch{return e.length>yfe?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},orn=({toolName:t,displayName:e,emoji:r,isExecuting:n,result:o,confirmationMessage:i,onAccept:a,onReject:s})=>{let[u,l]=(0,ol.useState)(!1),c=(0,ol.useMemo)(()=>s_i(t,o),[t,o]),d=n&&!o,f=!d&&c!==null;return ol.default.createElement(uy,{open:f?u:!1,onOpenChange:l,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},ol.default.createElement("div",{className:Se("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&ol.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},ol.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:a_i}})),ol.default.createElement(AT,{className:Se("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},ol.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ol.default.createElement("span",{className:"tw-text-base"},r),ol.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&ol.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),ol.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&a&&s&&ol.default.createElement(ol.default.Fragment,null,ol.default.createElement("button",{onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},ol.default.createElement(Yu,{className:"tw-size-4 tw-text-success"})),ol.default.createElement("button",{onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},ol.default.createElement(Ho,{className:"tw-size-4 tw-text-error"}))),f&&ol.default.createElement(od,{className:Se("tw-size-4 tw-text-muted tw-transition-transform",u&&"tw-rotate-90")}))),ol.default.createElement(ly,null,ol.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},ol.default.createElement("div",{className:"tw-text-sm tw-text-muted"},ol.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},c??"No result available"))))))};Xe();var irn=60*60*1e3,BY=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),UY=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),Fwt=(t,e,r)=>{if(e.size>0)return;r.get(t)===e&&r.delete(t)},kwt=(t,e,r,n,o,i)=>{try{n.root.unmount()}catch(a){Ce(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,e.get(r)===n&&e.delete(r),Fwt(t,e,i)},arn=(t,e,r,n,o,i)=>{e.delete(r),n.isUnmounting=!0,setTimeout(()=>{try{n.root.unmount()}catch(a){Ce(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,Fwt(t,e,i)},0)},rz=(t,e,r,n,o,i)=>{n.isUnmounting||(n.isUnmounting=!0,setTimeout(()=>{let a=i.get(t),s=a?.get(r);if(!a||s!==n){n.isUnmounting=!1,Fwt(t,e,i);return}kwt(t,a,r,s,o,i)},0))},srn=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(kwt(t,e,r,i,`${o} (finalizing stale root)`,BY()),i=void 0),i&&i.container&&i.container!==n&&(arn(t,e,r,i,`${o} (container changed)`,BY()),i=void 0),i||(i={root:(0,Lwt.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},urn=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(kwt(t,e,r,i,`${o} (finalizing stale error root)`,UY()),i=void 0),i&&i.container&&i.container!==n&&(arn(t,e,r,i,`${o} (container changed)`,UY()),i=void 0),i||(i={root:(0,Lwt.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},lrn=(t,e)
|
||
|
|
<summary style="${fe}">${oe}</summary>
|
||
|
|
<div class="tw-text-muted" style="${De}">${Fr.trim()}</div>
|
||
|
|
</details>
|
||
|
|
|
||
|
|
`});let Nt=new RegExp(`<${H}>([\\s\\S]*)$`);return z=z.replace(Nt,($e,Fr)=>`<div style="${de}">
|
||
|
|
<div style="${fe}">${Q}</div>
|
||
|
|
<div class="tw-text-muted" style="${De}">${Fr.trim()}</div>
|
||
|
|
</div>`),z}let Bt=new RegExp(`<${H}>([\\s\\S]*?)<\\/${H}>`,"g");return z.replace(Bt,(Pt,Nt)=>{let $e=`${H}-${Le}`;Le+=1;let Fr=qwt(h.current,$e),ft=_.get(Fr)?" open":"";return`<details id="${Fr}"${ft} style="${de}">
|
||
|
|
<summary style="${fe}">${oe}</summary>
|
||
|
|
<div class="tw-text-muted" style="${De}">${Nt.trim()}</div>
|
||
|
|
</details>
|
||
|
|
|
||
|
|
`})},Y=z=>V(z,"think","Thought for a while","Thinking..."),X=z=>{let H=fe=>fe.replace(/<(\/?)writeToFile>/g,"<$1writeFile>"),oe=fe=>{let De=/```(?:xml)?\s*([\s\S]*?<writeFile>[\s\S]*?<\/writeFile>[\s\S]*?)\s*```/g;return fe.replace(De,(st,Le)=>Le.trim())},Q=fe=>{if(!r)return fe;let De=/```xml\s*([\s\S]*?<writeFile>[\s\S]*?)$/g;return fe.replace(De,(st,Le)=>Le.trim())},de=H(z);return de=oe(de),de=Q(de),V(de,"writeFile","Generated new content","Generating changes...")},W=(z,H,oe)=>z.split(/(```[\s\S]*?```|`[^`]*`)/g).map((de,fe)=>fe%2===0?de.replace(H,(De,st)=>{let Le=e.metadataCache.getFirstLinkpathDest(st,Z);return Le?oe(Le):De}):de).join(""),re=xZ(k),ue=W(re,/!\[\[(.*?)]]/g,z=>`})`),le=Y(ue),L=X(le),ne=kzr(L,w.enableInlineCitations).replace(/\[\^(\d+)\](?!:)/g,'<span class="copilot-citation-ref">[$1]</span>'),D=W(ne,/(?<!!)\[\[([^\]]+)]]/g,z=>`<a href="obsidian://open?file=${encodeURIComponent(z.path)}">${z.basename}</a>`);return(z=>{if(!r)return z;let H=/!\[([^\]]*)\]\(([^)]+)\)/g;return z.replace(H,(oe,Q,de)=>{let fe=WWe(de);if(!fe)return oe;let De=Q||"YouTube Video",st=`https://i.ytimg.com/vi/${fe}/hqdefault.jpg`;return`[](${de})`})})(D)},[e,r,w.enableInlineCitations,_]);(0,sr.useEffect)(()=>{let k=f.current;if(!k||t.sender===Zs||!r)return;let q=Y=>{if(Y instanceof PointerEvent&&(Y.button!==0||!Y.isPrimary))return;let X=Hke(Y,k);if(!X||!Bwt(Y,X))return;let W=!X.open;X.open=W,_.set(X.id,W)},Z=Y=>{let X=Hke(Y,k);!X||!Bwt(Y,X)||Y.preventDefault()},V=Y=>{let X=Hke(Y,k);X&&_.set(X.id,X.open)};return k.addEventListener("pointerdown",q,!0),k.addEventListener("click",Z,!0),k.addEventListener("toggle",V,!0),()=>{k.removeEventListener("pointerdown",q,!0),k.removeEventListener("click",Z,!0),k.removeEventListener("toggle",V,!0)}},[r,t.sender,_]),(0,sr.useEffect)(()=>{if(m.current=!1,f.current&&t.sender!==Zs){p.current||(p.current=new s6.Component,p.current.load()),wrn(f.current,_,{overwriteExisting:!r});let k=t.message,q=wce(k);q?.hasReasoning&&q.status!=="idle"?d({status:q.status,elapsedSeconds:q.elapsedSeconds,steps:q.steps}):d(null);let Z=q?.contentAfter??k,V=O(Z),Y=Lat(V,h.current);if(!m.current){let X=new Set,W=new Set;f.current.querySelectorAll('[id^="tool-call-"]').forEach(D=>{let N=D.id.replace("tool-call-","");X.add(N)}),f.current.querySelectorAll('[id^="error-block-"]').forEach(D=>{let N=D.id.replace("error-block-","");W.add(N)}),f.current.querySelectorAll(".message-segment").forEach(D=>D.remove());let L=0;Y.segments.forEach(D=>{if(D.type==="text"&&D.content.trim()){let N=f.current.children[L],z=document.createElement("div");z.className="message-segment",N?f.current.insertBefore(z,N):f.current.appendChild(z),s6.MarkdownRenderer.renderMarkdown(D.content,z,"",p.current),f_i(z),L++}else if(D.type==="toolCall"&&D.toolCall){let N=D.toolCall.id,z=document.getElementById(`tool-call-${N}`);if(!z){let oe=f.current.children[L],Q=document.createElement("div");Q.className="tool-call-container",Q.id=`tool-call-${N}`,oe?f.current.insertBefore(Q,oe):f.current.appendChild(Q),z=Q}let H=srn(h.current,y.current,N,z,"render refresh");!m.current&&!H.isUnmounting&&lrn(H,D.toolCall),L++}else if(D.type==="error"&&D.error){let N=D.error.id,z=document.getElementById(`error-block-${N}`);if(!z){let oe=f.current.children[L],Q=document.createElement("div");Q.className="error-block-container",Q.id=`error-block-${N}`,oe?f.current.insertBefore(Q,oe):f.current.appendChild(Q),z=Q}let H=urn(h.current,g.current,N,z,"error render");!m.current&&!H.isUnmounting&&crn(H,D.error),L++}});let J=new Set(Y.segments.filter(D=>D.type==="toolCall"&&D.toolCall).map(D=>D.toolCall.id));X.forEach(D=>{if(!J.has(D)){let N=document.getElementById(`tool-call-${D}`);N&&(drn(h.current,y.current,D,"tool call removal"),N.remove())}});let ne=new Set(Y.segments.filter(D=>D.type==="error"&&D.error).map(D=>D.error.id));W.forEach(D=>{if(!ne.has(D)){let N=document.getElementById(`error-block-${D}`);N&&(frn(h.current,g.current,D,"error block removal"),N.remove())}}),f.current&&!r&&p_i(f.current)}}return()=>{m.current=!0}},[t,e,p,r,O,_]),(0
|
||
|
|
|
||
|
|
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).
|
||
|
|
|
||
|
|
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")}};u0();Xe();DG();u0();fte();var Crn=require("obsidian");function xrn(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 Trn(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 Crn.TFile&&(r.push(i),r.length>=e))break}return r}KOe();El();Qe();var Wwt=require("obsidian"),Kke=20,Orn=.7,Jke=.3;function g_i(){return kh(ee())}function y_i(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}function Prn(t){if(t.size<=Kke)return t;let e=Array.from(t.entries()).sort((r,n)=>n[1]-r[1]).slice(0,Kke);return new Map(e)}function b_i(t){return Array.isArray(t.embedding)&&t.embedding.length>0}function __i(t){return t.some(e=>e.content.trim().length>0)}async function v_i({db:t,filePath:e,currentNoteEmbeddings:r}){let n=r.map(s=>uq.getDocsByEmbedding(t,s,{limit:Kke,similarity:0})),i=(await Promise.all(n)).flat(),a=y_i(i,e);return Prn(a)}async function Ern(t){try{let e=ee(),r=new l0,n=await r.resolveBaseUrl(Mx(e)),o=tq(app),i=await r.searchRelated(n,UTe(app,t),{folderName:o,limit:Kke}),a=new Map,s=i.results||[];for(let u of s){let l=NG(app,u.path);if(l===t||typeof u.score!="number"||Number.isNaN(u.score))continue;let c=a.get(l);(c===void 0||u.score>c)&&a.set(l,u.score)}return ee().debug&&F(`RelevantNotes(Miyo): received ${s.length} chunks, collected ${a.size} note scores`),Prn(a)}catch(e){return Ce("RelevantNotes(Miyo): failed to compute similarity scores",e),new Map}}async function w_i(t){if(g_i())return Ern(t);let e=await p0.getInstance().getDocumentsByPath(t);if(e.length===0)return new Map;let r=e.filter(n=>b_i(n)).map(n=>n.embedding);if(r.length>0)try{let n=await p0.getInstance().getDb();return v_i({db:n,filePath:t,currentNoteEmbeddings:r})}catch(n){return Ce("RelevantNotes(Orama): failed to compute similarity scores",n),new Map}return __i(e)?Ern(t):new Map}function S_i(t){let e=new Map,n=xrn(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=Trn(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 C_i(t,e){let r=new Map,n=Orn+Jke;for(let[o,i]of t)r.set(o,i*Orn/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=Jke:(i.links||i.backlinks)&&(a=Jke*.8),r.set(o,(r.get(o)??0)+a)}return r}async function Mrn({filePath:t}){let e=app.vault.getAbstractFileByPath(t);if(!(e instanceof Wwt.TFile))return[];let r=await w_i(t),n=S_i(e),o=C_i(r,n);return Array.from(o.entries()).sort((a,s)=>{let u=a[0],l=s[0],c=Gke(r.get(u)??0),d=Gke(r.get(l)??0);return c!==d?d-c:s[1]-a[1]}).map(([a,s])=>{let u=app.vault.getAbstractFileByPath(a);return!(u instanceof Wwt.TFile)||u.extension!=="md"?null:{document:{path:a,title:u.basename},metadata:{score:s,similarityScore:r.get(a),hasOutgoingLinks:n.get(a)?.links??!1,hasBacklinks:n.get(a)?.backlinks??!1}}}).filter(a=>a!==null)}function Gke(t){return t>.7?3:t>.55?2:1}hat();Mr();var u6=require("obsidian"),It=$(K());function x_i(t){let[e,r]=(0,It.useState)([]),[n,o]=(0,It.useState)(0),i=Vwt();return(0,It.useEffect)(()=>mat(()=>o(a=>a+1)),[]),(0,It.useEffect)(()=>{async function a(){if(i?.path)try{let s=await Mrn({filePath:i.path});r(s)}catch(s){Ce("Failed to fetch relevant notes",s),r([])}}a()},[i?.path,t,n]),e}function T_i(t,e){let[r,n]=(0,It.useState)(!0),[o,i]=(0,It.useState)(0);return(0,It.useEffect)(()=>mat(()=>i(a=>a+1)),[]),(0,It.useEffect)(()=>{if(!t)return;async function a(){try{let s=(await Promise.resolve().then(()=>(El(),Bc))).default,{getSettings:u}=await Promise
|
||
|
|
`).map(b=>{if(!b.trim())return b;try{return new URL(b.trim()),b}catch{return b}});p("contextSource.webUrls",g.join(`
|
||
|
|
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),gn.default.createElement(ko,{label:"YouTube URLs"},gn.default.createElement(n_,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
|
||
|
|
`).map(b=>{if(!b.trim())return b;try{let _=new URL(b.trim());return _.hostname.includes("youtube.com")||_.hostname.includes("youtu.be"),b}catch{return b}});p("contextSource.youtubeUrls",g.join(`
|
||
|
|
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),gn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},gn.default.createElement(me,{variant:"ghost",onClick:r,disabled:o},"Cancel"),gn.default.createElement(me,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var Efe=class extends Ofe.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,ynn.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(gn.default.createElement(hvi,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};xn();zr();Xe();Qe();t1();Mr();var _nn=require("obsidian"),at=$(K());function gvi(t,e,r={}){let{caseSensitive:n=!1,searchInName:o=!0,searchInDescription:i=!0}=r;if(!e.trim())return!0;let a=n?e:e.toLowerCase();return!!(o&&(n?t.name:t.name.toLowerCase()).includes(a)||i&&t.description&&(n?t.description:t.description.toLowerCase()).includes(a))}function bnn(t,e,r={}){return!t||t.length===0?[]:e.trim()?t.filter(n=>gvi(n,e,r)):t}function yvi(t){let[e,r]=(0,at.useState)(()=>t?.getRevision()??0);return(0,at.useEffect)(()=>{if(!t){r(0);return}return r(t.getRevision()),t.subscribe(()=>{r(t.getRevision())})},[t]),e}function bvi({project:t,loadContext:e,onEdit:r,onDelete:n}){return at.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-3 tw-transition-all tw-duration-200 tw-bg-secondary/40 hover:tw-border-interactive-accent hover:tw-text-accent hover:tw-shadow-[0_2px_12px_rgba(0,0,0,0.1)] active:tw-scale-[0.98]",onClick:()=>e(t)},at.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2 tw-overflow-hidden"},at.default.createElement("div",{className:"tw-text-accent"},at.default.createElement(Am,{className:"tw-size-4"})),at.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-gap-1.5 tw-overflow-hidden"},at.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[13px] tw-font-medium tw-text-normal"},t.name),t.description&&at.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[12px] tw-text-muted/80"},t.description))),at.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-1 tw-opacity-100 tw-transition-opacity tw-duration-200"},at.default.createElement(vn,null,at.default.createElement(wn,{asChild:!0},at.default.createElement(me,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),r(t)}},at.default.createElement(Lb,{className:"tw-size-4"}))),at.default.createElement(pn,{side:"bottom"},"Edit Project")),at.default.createElement(vn,null,at.default.createElement(wn,{asChild:!0},at.default.createElement(me,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),e(t)}},at.default.createElement($5,{className:"tw-size-4"}))),at.default.createElement(pn,{side:"bottom"},"Start Chat")),at.default.createElement(vn,null,at.default.createElement(wn,{asChild:!0},at.default.createElement(me,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),new nu(app,()=>n(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},at.default.createElement(Iy,{className:"tw-size-4"}))),at.default.createElement(pn,{side:"bottom"},"Delete Project"))))}var cSt=(0,at.memo)(({className:t,projects:e,defaultOpen:r=!1,app:n,plugin:o,onProjectAdded:i,onEditProject:a,hasMessages:s=!1,showChatUI:u,onClose:l,onProjectClose:c})=>{let[d,f]=(0,at.useState)(r),[p,m]=(0,at.useState)(!1),[h,y]=(0,at.useState)(null),[g,b]=(0,at.useState)(""),_=ez(),w=kr(),T=o?.projectManager?.getProjectUsageTimestampsManager?.(),O=yvi(T);(0,at.useEffect)(()=>{s&&f(!1)},[s]);let E=(0,at.useMemo)(()=>iO(e,w.projectListSortStrategy,{getName:q=>q.name,getCreatedAtMs:q=>q.created,getLastUsedAtMs:q=>T?T.getEffectiveLastUsedAt(q.id,q.UsageTimestamps):q.UsageTimestamps}),[e,w.projectListSortStrategy,T,O]),P=(0,at.useM
|
||
|
|
- a positive number
|
||
|
|
- less than the value passed to \`max\` (or ${mSt} if no \`max\` prop is set)
|
||
|
|
- \`null\` or \`undefined\` if the progress is indeterminate.
|
||
|
|
|
||
|
|
Defaulting to \`null\`.`}var hSt=Mnn,Nnn=Inn;zr();var Mfe=Pfe.forwardRef(({className:t,value:e,...r},n)=>Pfe.createElement(hSt,{ref:n,className:Se("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},Pfe.createElement(Nnn,{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)}%)`}})));Mfe.displayName=hSt.displayName;xn();Mr();na();function gSt({onClose:t,onPause:e,onResume:r,onStop:n}){let[o]=e5(),i=(0,dqe.useRef)(null),{isActive:a,isPaused:s,indexedCount:u,totalFiles:l,errors:c,completionStatus:d}=o,f=l>0?Math.round(u/l*100):0;(0,dqe.useEffect)(()=>(i.current&&(clearTimeout(i.current),i.current=null),!a&&d!=="none"&&!(d==="error"&&l===0)&&(i.current=setTimeout(()=>{t()},3e3)),()=>{i.current&&(clearTimeout(i.current),i.current=null)}),[a,d,l,t]);let p=()=>d==="success"?l===0?"Index Up to Date":"Indexing Complete":d==="cancelled"?"Indexing Cancelled":d==="error"?l===0?"Indexing Failed":"Indexing Complete (with errors)":s?"Indexing Paused":"Indexing Vault";return ea.createElement(vL,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},ea.createElement(wL,null,ea.createElement(l6,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},ea.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!a&&d!=="none"?d==="error"?ea.createElement($b,{className:"tw-size-4 tw-text-error"}):d==="success"?ea.createElement(B_,{className:"tw-size-4 tw-text-success"}):ea.createElement(YC,{className:"tw-size-4"}):s?ea.createElement(L5,{className:"tw-size-4 tw-text-warning"}):ea.createElement(Us,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),ea.createElement("span",{className:"tw-text-sm"},p())),ea.createElement(me,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close",onClick:t},ea.createElement(Ho,{className:"tw-size-4"})))),ea.createElement(SL,{className:"tw-space-y-3"},l>0&&ea.createElement("div",{className:"tw-space-y-2"},ea.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},ea.createElement("span",{className:"tw-text-muted"},u,"/",l," files"),ea.createElement("span",{className:"tw-font-medium"},f,"%")),ea.createElement(Mfe,{value:f,className:"tw-h-2"})),c.length>0&&ea.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},ea.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ea.createElement($b,{className:"tw-size-3 tw-text-error"}),ea.createElement(Xc,{variant:"destructive",className:"tw-text-xs"},c.length," ",c.length===1?"error":"errors")),l===0&&c[0]&&ea.createElement("span",{className:"tw-text-xs tw-text-error"},c[0])),a&&ea.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ea.createElement(me,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:s?r:e},s?ea.createElement(ea.Fragment,null,ea.createElement(kre,{className:"tw-mr-1 tw-size-3"}),"Resume"):ea.createElement(ea.Fragment,null,ea.createElement(L5,{className:"tw-mr-1 tw-size-3"}),"Pause")),ea.createElement(me,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:n},ea.createElement(z4,{className:"tw-mr-1 tw-size-3"}),"Stop"))))}var On=$(K()),ySt=$(K());Mr();na();xn();Xe();function bSt({plugin:t,setHiddenCard:e,onEditContext:r}){let[n]=YJ(),o=n.total,i=n.success,a=n.failed,s=n.processingFiles,[u,l]=(0,ySt.useState)(!1),[c,d]=(0,ySt.useState)(!1),f=i.length+a.length,p=o.length>0?Math.round(f/o.length*100):0,m=y=>y.path,h=async y=>{if(!t?.projectManager){ie("ProjectManager not available");return}try{await t.projectManager.retryFailedItem(y)}catch(g){ie(`Error retrying failed item: ${g}`)}};return On.createElement(vL,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},On.createElement(wL,null,On.createElement(l6,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},On.createElement("div",{className:"tw-flex tw-items-center tw-gap-2
|
||
|
|
`).filter(o=>o.trim()),n=[];for(let o of r){let i=jvi(t,o.trim());i&&n.push(i)}return n}function jnn(t){let{app:e,contextNotes:r,setContextNotes:n,selectedImages:o,onAddImage:i,containerRef:a}=t,[s,u]=(0,fqe.useState)(!1);return(0,fqe.useEffect)(()=>{let l=a.current;if(!l)return;let c=p=>{if(p.preventDefault(),p.dataTransfer){if(p.dataTransfer.dropEffect="copy",p.dataTransfer.types.includes("copilot/internal-drag"))return;let m=Array.from(p.dataTransfer.items).some(y=>y.kind==="string"),h=Array.from(p.dataTransfer.items).some(y=>y.kind==="file");(m||h)&&u(!0)}},d=p=>{let m=l.getBoundingClientRect(),h=p.clientX,y=p.clientY;(h<m.left||h>=m.right||y<m.top||y>=m.bottom)&&u(!1)},f=async p=>{if(!p.dataTransfer)return;p.preventDefault(),u(!1);let m=p.dataTransfer.items,h=[],y=[];for(let g=0;g<m.length;g++){let b=m[g];b.kind==="string"?h.push(b):b.kind==="file"&&y.push(b)}if(h.length>0){p.stopPropagation();let g=h.map(w=>new Promise(T=>{w.getAsString(O=>T(O))})),b=await Promise.all(g),_=new Map;for(let w of b){let T=$vi(e,w);for(let O of T)_.set(O.path,O)}for(let w of _.values())if(["png","gif","jpeg","jpg","webp"].includes(w.extension)){if(o.some(I=>I.name===w.name)){new p6.Notice("This image is already in the context");continue}let E=await e.vault.readBinary(w),P=new Blob([E]),R=new File([P],w.name,{type:`image/${w.extension}`});i([R])}else if(uO(w)){if(r.some(E=>E.path===w.path)){new p6.Notice("This note is already in the context");continue}n(E=>[...E,w])}else new p6.Notice(`Unsupported file type: ${w.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let g=[];for(let b of y){let _=b.getAsFile();_&&_.type.startsWith("image/")&&g.push(_)}g.length>0&&i(g)}};return l.addEventListener("dragover",c),l.addEventListener("dragleave",d),l.addEventListener("drop",f),()=>{l.removeEventListener("dragover",c),l.removeEventListener("dragleave",d),l.removeEventListener("drop",f)}},[e,r,o,i,n,a]),{isDragActive:s}}gr();Dt();Xe();y_();var _St=async(t,e,r,n,o,i={})=>{let a=new AbortController;o(a);try{await e.runChain(t,a,n,r,i)}catch(s){ie("Model request failed:",s);let u=lEe("Model request failed: "+Wr(s));r({id:gu(),sender:ow,isErrorMessage:!0,message:u,isVisible:!0,timestamp:vg(new Date)})}};h4();id();Qe();Dt();eEe();var Il=require("obsidian");var qt=$(K());y_();var Lvi=({chainManager:t,onSaveChat:e,updateUserMessageHistory:r,fileParserManager:n,plugin:o,chatUIState:i,chatInput:a})=>{let s=kr(),u=(0,qt.useContext)(zY),{messages:l,addMessage:c}=Dnn(i),[d]=oF(),[f]=aw(),[p,m]=(0,qt.useState)(""),[h,y]=(0,qt.useState)(""),[g,b]=(0,qt.useState)(null),_=(0,qt.useRef)(null),w=(0,qt.useRef)(null),T=(0,qt.useCallback)(nt=>{let Nr=w.current,Ee=Nr&&nt.sender===ow&&!nt.isErrorMessage&&!nt.id?{...nt,id:Nr}:nt;c(Ee),Ee.sender===ow&&Ee.responseMetadata?.tokenUsage?.totalTokens&&b(Ee.responseMetadata.tokenUsage.totalTokens)},[c]),O=(0,qt.useCallback)(nt=>{_.current=nt},[]),[E,P]=(0,qt.useState)(!1),[R,I]=(0,qt.useState)(iw.DEFAULT),[A,B]=(0,qt.useState)([]),[k,q]=(0,qt.useState)(!1),[Z,V]=(0,qt.useState)(!1),[Y,X]=(0,qt.useState)([]),[W,re]=(0,qt.useState)(!1),[ue,le]=(0,qt.useState)([]),[L,J]=(0,qt.useState)(null),[ne,D]=(0,qt.useState)(null),[N]=e5(),z=(0,qt.useRef)(!1),H=(0,qt.useRef)(null),oe=(0,qt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),Q=(0,qt.useMemo)(()=>({setCurrentAiMessage:nt=>z.current&&m(nt),setLoadingMessage:nt=>z.current&&I(nt),setLoading:nt=>z.current&&P(nt)}),[]),[de]=d1t(),fe=de.length>0,De=k&&!fe,st=Z&&!fe,{activeWebTabForMentions:Le}=VU(),Bt=nLe(),Pt=()=>He!=="project"?!1:L!==null?L:Bt==="loading"||Bt==="error";(0,qt.useEffect)(()=>{J(null)},[Bt]);let Nt=()=>He==="project"||ne===!1?!1:N.isActive||N.completionStatus!=="none";(0,qt.useEffect)(()=>{(N.isActive||N.completionStatus!=="none")&&D(null)},[N.isActive,N.completionStatus]);let $e=(0,qt.useCallback)(()=>{D(!1),N.isActive||Sg({completionStatus:"none"})},[N.isActive]),Fr=(0,qt.useCallback)(async()=>{(await Promise.resolve().then(()=>(El(),Bc))).default.getInstance().pauseIndexing()},[]),ft=(0,qt.useCallback)(a
|
||
|
|
`));let Sh={notes:zv,urls:Rb(f)?Nr||[]:[],tags:Ee||[],folders:Mt||[],selectedTextContexts:de,webTabs:Yt||[]};y(""),X([]),w.current=`msg-${gu()}`,Q.setLoading(!0),Q.setLoadingMessage(iw.DEFAULT);let CC=await i.sendMessage(PL,Sh,f,De,st,ul.length>0?ul:void 0,Q.setLoadingMessage);h&&r(h),s.autosaveChat&&Nl();let Vv=i.getLLMMessage(CC);Vv&&await _St(Vv,t,T,Q.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Q.setLoadingMessage}),s.autosaveChat&&Nl()}catch(ul){ie("Error sending message:",ul),new Il.Notice("Failed to send message. Please try again.")}finally{Q.setLoading(!1),Q.setLoadingMessage(iw.DEFAULT),w.current=null}},Nl=(0,qt.useCallback)(async()=>{if(!au){ie("App instance is not available.");return}try{await i.saveChat(d)}catch(nt){ie("Error saving chat as note:",Wr(nt)),new Il.Notice("Failed to save chat as note. Check console for details.")}},[au,i,d]),Vi=(0,qt.useCallback)(nt=>{_.current&&(F(`stopping generation..., reason: ${nt}`),_.current.abort(nt),Q.setLoading(!1),Q.setLoadingMessage(iw.DEFAULT))},[Q]);(0,qt.useEffect)(()=>(z.current=!0,()=>{z.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let g_=(0,qt.useCallback)(async nt=>{if(nt<=0){new Il.Notice("Cannot regenerate the first message.");return}let Nr=l[nt];if(!Nr){new Il.Notice("Message not found.");return}Q.setCurrentAiMessage(""),w.current=`msg-${gu()}`,Q.setLoading(!0);try{await i.regenerateMessage(Nr.id,Q.setCurrentAiMessage,T)?s.debug&&console.log("Message regenerated successfully"):new Il.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&Nl()}catch(Ue){ie("Error regenerating message:",Ue),new Il.Notice("Failed to regenerate message. Please try again.")}finally{Q.setLoading(!1),w.current=null}},[l,i,s.debug,s.autosaveChat,Nl,T,Q]),mg=(0,qt.useCallback)(async(nt,Nr)=>{let Ue=l[nt];if(!(!Ue||Ue.message===Nr))try{if(!await i.editMessage(Ue.id,Nr,f,De)){new Il.Notice("Failed to edit message. Please try again.");return}if(Ue.sender===Zs){let Mt=nt<l.length-1;if(await i.truncateAfterMessageId(Ue.id),Mt){w.current=`msg-${gu()}`,Q.setLoading(!0);try{let Yt=i.getLLMMessage(Ue.id);Yt&&await _St(Yt,t,T,Q.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Q.setLoadingMessage})}catch(Yt){ie("Error regenerating AI response:",Yt),new Il.Notice("Failed to regenerate AI response. Please try again.")}finally{Q.setLoading(!1),w.current=null}}}s.autosaveChat&&Nl()}catch(Ee){ie("Error editing message:",Ee),new Il.Notice("Failed to edit message. Please try again.")}},[l,i,f,De,T,t,s.debug,s.autosaveChat,Nl,Q,O]);(0,qt.useEffect)(()=>{e&&e(Nl)},[e,Nl]);let cS=(0,qt.useCallback)(nt=>{let Nr=s.projectList||[];if(Nr.findIndex(Yt=>Yt.name===nt.name)>=0)throw new Error(`Project "${nt.name}" already exists, please use a different name`);let Ee=[...Nr,nt];return Re("projectList",Ee),Gu()?.id===nt.id?FLe().then(()=>{new Il.Notice(`${nt.name} added and context loaded`)}).catch(Yt=>{ie("Error loading project context:",Yt),new Il.Notice(`${nt.name} added but context loading failed`)}):new Il.Notice(`${nt.name} added successfully`),!0},[s.projectList]),ji=(0,qt.useCallback)((nt,Nr)=>{let Ue=s.projectList||[];if(!Ue.find(Ln=>Ln.name===nt.name))throw new Error(`Project "${nt.name}" does not exist`);let Mt=Ue.map(Ln=>Ln.name===nt.name?Nr:Ln);return Re("projectList",Mt),Gu()?.id===nt.id?(C4(Nr),FLe().then(()=>{new Il.Notice(`${nt.name} updated and context reloaded`)}).catch(Ln=>{ie("Error reloading project context:",Ln),new Il.Notice(`${nt.name} updated but context reload failed`)})):new Il.Notice(`${nt.name} updated successfully`),!0},[s.projectList]),LT=(0,qt.useCallback)(nt=>{let Ue=zC().find(Ee=>Ee.id===nt);l1t(nt),Ue?.sourceType==="web"&&o.suppressCurrentWebSelection(Ue.url)},[o]);(0,qt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(de)},[de,o]),(0,qt.useEffect)(()=>{let nt=()=>{a.focusInput()};return u?.addEventListener(MS.CHAT_IS_VISIBLE,nt),()=>{u?.removeEventListener(MS.CHAT_IS_VISIBLE,nt)}},[u,a]);let SC=(0,qt.useCallback)(async nt=>{let Nr=l[nt];if(!Nr){new Il.Notice("Message not found.");return}try{a
|
||
|
|
|
||
|
|
Original name: ${a.title}
|
||
|
|
|
||
|
|
${a.content}`}):e.push(a)}await Zm.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 ${tU()}.`;r.length>0&&(await Uvi(r),i+=`
|
||
|
|
|
||
|
|
We found ${r.length} unsupported commands. They are saved in ${tU()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),Re("inlineEditCommands",[]),new nu(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function vSt(){let t=Sv(),e=IWr.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Zm.getInstance().updateCommands(r)}async function Vnn(){if(ee().suggestedDefaultCommands)return;Sv().length===0&&(new nu(app,()=>{vSt()},"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(),Re("suggestedDefaultCommands",!0))}gr();Qe();rd();na();Xe();gr();async function Hnn(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Zs){let o=t[r+1];o?.sender===ow&&await e.saveContext({input:n.message},{output:o.message})}}}na();rd();gr();var Knn=$(oH());Xe();var Wnn=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],Jnn={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var az=class az{constructor(){}static getInstance(){return az.instance||(az.instance=new az),az.instance}buildEnvelope(e){let r=Wnn.map(s=>this.buildLayer(s,e.layerSegments[s]??[])),n=this.serializeLayers(r),o=this.collectLayerHashes(r),i=this.hash(n),a=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return a&&F(`[PromptContextEngine] Built envelope for ${a}`,o),{version:az.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:r,serializedText:n,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(r)}}}buildLayer(e,r){let n=r.map((i,a)=>({...i,id:i.id||`${e}-segment-${a}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(n.map(i=>i.content).filter(Boolean).join(`
|
||
|
|
|
||
|
|
`));return{id:e,label:Jnn[e],text:o,segments:n,stable:n.every(i=>i.stable),metadata:n.length===1?n[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(r=>r.text).filter(r=>r.length>0).join(`
|
||
|
|
|
||
|
|
`)}collectLayerHashes(e){return e.reduce((r,n)=>(r[n.id]=n.hash,r),{})}hash(e){return(0,Knn.SHA256)(e||"").toString()}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let r=[];return e.forEach(n=>{if(!n.text)return;n.text.includes("\0")&&r.push(`Layer ${n.id} contains control characters and was normalized`)}),r}};az.ENVELOPE_VERSION=1;var gqe=az;function zvi(t){let e=/<path>([^<]+)<\/path>/.exec(t);if(e)return e[1];let r=/<url>([^<]+)<\/url>/.exec(t);if(r)return r[1];let n=/<name>([^<]+)<\/name>/.exec(t);return n?n[1]:""}function Vvi(t,e,r,n={}){let o=n.verbatimThreshold??Xw.verbatimThreshold;if(t.length<=o)return t;let i=n.previewCharsPerSection??Xw.previewCharsPerSection,a=n.maxSections??Xw.maxSections,s=ZW(t,i,a);return`<prior_context source="${sje(e)}" type="${r}">
|
||
|
|
${s}
|
||
|
|
</prior_context>`}function Gnn(t,e,r={}){if(!aje(e))return t;let n=r.verbatimThreshold??Xw.verbatimThreshold;if(t.length<=n)return t;let o=JX(t,e)||zvi(t),i=Cce(t),a=XW(e);return Vvi(i,o,a,r)}function Xnn(){return`<prior_context_note>
|
||
|
|
The above prior_context blocks contain previews of content from earlier turns.
|
||
|
|
To access full content: use [[note title]] for notes, or ask to read a specific URL/video.
|
||
|
|
</prior_context_note>`}function Znn(t,e){if(!t.trim())return[];let r=[],o=[...WX.map(u=>u.tag),"prior_context"],i=new RegExp(`<(${o.join("|")})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g"),a=new Map,s;for(;(s=i.exec(t))!==null;){let u=s[0],l=s[1];if(l==="prior_context"){let d=/source="([^"]+)"/.exec(u)?.[1]??"prior_context";r.push({id:d,content:u,stable:e,metadata:{source:"previous_turns_compacted",notePath:d}})}else{let c=JX(u,l),d;if(c)d=c;else{let p=(a.get(l)||0)+1;a.set(l,p),d=p===1?l:`${l}:${p}`}let f=XW(l)==="note";r.push({id:d,content:u,stable:e,metadata:{source:e?"previous_turns":"current_turn",...f?{notePath:d}:{}}})}}return r}na();gr();Xe();T3();EZ();Dt();AZ();var jfe=require("obsidian");gr();var yqe=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processEmbeddedPDFs(e,r,n){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let a of i){let s=a[1],u=r.getAbstractFileByPath(s);if(u instanceof jfe.TFile)try{let l=await n.parseFile(u,r);e=e.replace(a[0],`
|
||
|
|
|
||
|
|
<${hte}>
|
||
|
|
<name>${s}</name>
|
||
|
|
<content>
|
||
|
|
${l}
|
||
|
|
</content>
|
||
|
|
</${hte}>
|
||
|
|
|
||
|
|
`)}catch(l){ie(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
|
||
|
|
|
||
|
|
<${hte}>
|
||
|
|
<name>${s}</name>
|
||
|
|
<error>Could not process PDF</error>
|
||
|
|
</${hte}>
|
||
|
|
|
||
|
|
`)}}return e}async processDataviewBlocks(e,r){let n=app.plugins?.plugins?.dataview;if(!n)return e;let o=n.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,a=[...e.matchAll(i)];for(let s=a.length-1;s>=0;s--){let u=a[s],l=u[1],c=u[2].trim(),d=u.index,f=d+u[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,c,l,r),new Promise((h,y)=>setTimeout(()=>y(new Error("Query timeout")),5e3))]),m=`
|
||
|
|
|
||
|
|
<${gte}>
|
||
|
|
<query_type>${l}</query_type>
|
||
|
|
<original_query>
|
||
|
|
${c}
|
||
|
|
</original_query>
|
||
|
|
<executed_result>
|
||
|
|
${p}
|
||
|
|
</executed_result>
|
||
|
|
</${gte}>
|
||
|
|
|
||
|
|
`;e=e.slice(0,d)+m+e.slice(f)}catch(p){ie("Error executing Dataview query:",p);let m=`
|
||
|
|
|
||
|
|
<${gte}>
|
||
|
|
<query_type>${l}</query_type>
|
||
|
|
<original_query>
|
||
|
|
${c}
|
||
|
|
</original_query>
|
||
|
|
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
|
||
|
|
</${gte}>
|
||
|
|
|
||
|
|
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,r,n,o){if(n==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(r,o);if(!i.successful)throw new Error(i.error||"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers,e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(`
|
||
|
|
`):String(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(r=>`- ${this.formatDataviewValue(r)}`).join(`
|
||
|
|
`)}formatDataviewTable(e,r){if(!r||r.length===0)return"No results";let n=`| ${e.join(" | ")} |
|
||
|
|
`;n+=`| ${e.map(()=>"---").join(" | ")} |
|
||
|
|
`;for(let o of r)n+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
|
||
|
|
`;return n}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(r=>`- ${r.completed?"[x]":"[ ]"} ${this.formatDataviewValue(r.text||r)}`).join(`
|
||
|
|
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&e.path?`[[${e.path}]]`:Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(", "):String(e)}async buildMarkdownContextContent(e,r,n,o){let i=await n.parseFile(e,r);return i=await this.processEmbeddedNotes(i,e,r,n,o),Rb(o)&&(i=await this.processEmbeddedPDFs(i,r,n)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,r,n,o,i){let a=/!\[\[([^\]]+)\]\]/g,s,u=0,l="";for(;(s=a.exec(e))!==null;){l+=e.slice(u,s.index);let c=s[1].trim(),d=await this.buildEmbeddedNoteBlock(c,s[0],r,n,o,i);l+=d,u=s.index+s[0].length}return l+=e.slice(u),l}async buildEmbeddedNoteBlock(e,r,n,o,i,a){let s=this.parseEmbeddedLinkTarget(e);if(!s)return r;let u=s.path===null?n:app.metadataCache.getFirstLinkpathDest(s.path,n.path);if(!(u instanceof jfe.TFile))return this.formatEmbeddedNoteBlock({title:s.path??n.basename,path:s.path??n.path,heading:s.heading,blockId:s.blockId,error:"Embedded note not found"});if(u.extension!=="md")return r;try{let l=await i.parseFile(u,o);if(s.heading||s.blockId){let c=this.extractMarkdownSegment(u,l,s);if(!c.found){let d=s.blockId?`block reference "${s.blockId}"`:`heading "${s.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${u.path}`)}l=c.content}return Rb(a)&&(l=await this.processEmbeddedPDFs(l,o,i)),l=await this.processDataviewBlocks(l,u.path),this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,content:l})}catch(l){Ce("Failed to process embedded note",l);let c=l instanceof Error?l.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,error:c})}}parseEmbeddedLinkTarget(e){if(!e)return null;let r=e.indexOf("|"),o=(r>=0?e.slice(0,r):e).trim();if(!o)return{path:null};let i,a,s=o.indexOf("#^");s!==-1&&(i=o.slice(s+2).trim(),o=o.slice(0,s));let u=o.indexOf("#");return u!==-1&&(a=o.slice(u+1).trim(),o=o.slice(0,u)),{path:o.length>0?o:null,heading:a&&a.length>0?a:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,r,n){let o=app.metadataCache.getFileCache(e);if(n.blockId){let i=o?.blocks?.[n.blockId],a=i?.position?.start?.offset,s=i?.position?.end?.offset;return a===void 0||s===void 0?{content:"",found:!1}:{content:r.slice(a,s),found:!0}}if(n.heading){let i=o?.headings??[],a=this.normalizeHeadingForMatch(n.heading),s=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===a);if(s===-1)return{content:"",found:!1};let u=i[s],l=u.position?.start?.offset??0,c=r.length;for(let d=s+1;d<i.length;d++)if(i[d].level<=u.level){c=i[d].position?.start?.offset??c;break}return{content:r.slice(l,c),found:!0}}return{content:r,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:r,path:n,heading:o,blockId:i,content:a,error:s}=e,u=`
|
||
|
|
|
||
|
|
<${QWe}>
|
||
|
|
<title>${r}</title>
|
||
|
|
<path>${n}</path>`;return o&&(u+=`
|
||
|
|
<heading>${o}</heading>`),i&&(u+=`
|
||
|
|
<block_id>${i}</block_id>`),s?u+=`
|
||
|
|
<error>${s}</error>`:u+=`
|
||
|
|
<content>
|
||
|
|
${a??""}
|
||
|
|
</content>`,u+=`
|
||
|
|
</${QWe}>
|
||
|
|
|
||
|
|
`,u}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=pte)=>{try{if(e.has(d.path)){F(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!r.supportsExtension(d.extension)){Ce(`Unsupported file type: ${d.extension}`);return}if(!Rb(s)&&!Ege(d)){Ce(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new jfe.Notice(zJ.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,n,r,s):await r.parseFile(d,n),m=await n.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",y=m?new Date(m.mtime).toISOString():"Unknown";u+=`
|
||
|
|
|
||
|
|
<${f}>
|
||
|
|
<title>${Mc(d.basename)}</title>
|
||
|
|
<path>${d.path}</path>
|
||
|
|
<ctime>${h}</ctime>
|
||
|
|
<mtime>${y}</mtime>
|
||
|
|
<content>
|
||
|
|
${p}
|
||
|
|
</content>
|
||
|
|
</${f}>`}catch(p){ie(`Error processing file ${d.path}:`,p),u+=`
|
||
|
|
|
||
|
|
<${f}_error>
|
||
|
|
<title>${Mc(d.basename)}</title>
|
||
|
|
<path>${d.path}</path>
|
||
|
|
<error>[Error: Could not process file]</error>
|
||
|
|
</${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=zC();if(!e||e.length===0)return"";let r="";for(let n of e)n.sourceType==="web"?r+=`
|
||
|
|
|
||
|
|
<${YWe}>
|
||
|
|
<title>${Mc(n.title)}</title>
|
||
|
|
<url>${Mc(n.url)}</url>
|
||
|
|
<content>
|
||
|
|
${Mc(n.content)}
|
||
|
|
</content>
|
||
|
|
</${YWe}>`:r+=`
|
||
|
|
|
||
|
|
<${N_}>
|
||
|
|
<title>${Mc(n.noteTitle)}</title>
|
||
|
|
<path>${Mc(n.notePath)}</path>
|
||
|
|
<start_line>${n.startLine.toString()}</start_line>
|
||
|
|
<end_line>${n.endLine.toString()}</end_line>
|
||
|
|
<content>
|
||
|
|
${n.content}
|
||
|
|
</content>
|
||
|
|
</${N_}>`;return r}async processContextWebTabs(e){if(!e||e.length===0)return"";let r=2500,n=8e3,o=15e3,i=2,a=(b,_)=>{let w=[`
|
||
|
|
|
||
|
|
<${b}>`,`
|
||
|
|
<title>${Mc(_.title)}</title>`,`
|
||
|
|
<url>${Mc(_.url)}</url>`];return _.mode&&w.push(`
|
||
|
|
<mode>${Mc(_.mode)}</mode>`),_.error?w.push(`
|
||
|
|
<error>${Mc(_.error)}</error>`):_.content!==void 0&&w.push(`
|
||
|
|
<content>
|
||
|
|
${Mc(_.content)}
|
||
|
|
</content>`),w.push(`
|
||
|
|
</${b}>`),w.join("")},s=b=>{let _=[`
|
||
|
|
|
||
|
|
<${r3e}>`,`
|
||
|
|
<title>${Mc(b.title)}</title>`,`
|
||
|
|
<url>${Mc(b.url)}</url>`,`
|
||
|
|
<video_id>${Mc(b.videoId)}</video_id>`];b.isActive&&_.push(`
|
||
|
|
<is_active>true</is_active>`),b.channel&&_.push(`
|
||
|
|
<channel>${Mc(b.channel)}</channel>`),b.uploadDate&&_.push(`
|
||
|
|
<upload_date>${Mc(b.uploadDate)}</upload_date>`),b.duration&&_.push(`
|
||
|
|
<duration>${Mc(b.duration)}</duration>`),b.genre&&_.push(`
|
||
|
|
<genre>${Mc(b.genre)}</genre>`),b.description&&_.push(`
|
||
|
|
<description>${Mc(b.description)}</description>`),b.error&&_.push(`
|
||
|
|
<error>${Mc(b.error)}</error>`);let w=b.transcript||"No transcript available for this video";return _.push(`
|
||
|
|
<content>
|
||
|
|
${Mc(w)}
|
||
|
|
</content>`),_.push(`
|
||
|
|
</${r3e}>`),_.join("")},u=null,l=[],c=new Set,d=new Set,f=md(app),p=b=>{let _=f.getYouTubeVideoId(b);return _?d.has(_)?!0:(d.add(_),!1):c.has(b)?!0:(c.add(b),!1)};for(let b of e){let _=ub(b.url);_&&b.isActive&&!u&&(u={...b,url:_},p(_))}for(let b of e){let _=ub(b.url);!_||p(_)||l.push({...b,url:_})}if(!u&&l.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let b=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),_=[];u&&_.push(a(Dge,{title:u.title||"Unknown",url:u.url,error:b}));for(let w of l)_.push(a(t3e,{title:w.title||"Unknown",url:w.url,error:b}));return _.join("")}let h=async(b,_)=>{try{let w=b.url,T=f.getYouTubeVideoId(w);if(T)return await y(b,T,_===Dge);let O=f.findLeafByUrl(w,{title:b.title});if(!O)return a(_,{title:b.title||"Unknown",url:w,error:"Web tab not found or closed"});let E=f.getPageInfo(O),P=O.view;if(!(P.webviewMounted===void 0||P.webviewFirstLoadFinished===void 0?!0:!!(P.webviewMounted&&P.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(O,r),E=f.getPageInfo(O)}catch(B){return Ce(`Web tab content not loaded yet for ${w}:`,B),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,error:"Web tab content not loaded yet"})}let I=new AbortController,A=setTimeout(()=>{I.abort()},n);try{let B=await f.getReaderModeMarkdown(O,{signal:I.signal});return E=f.getPageInfo(O),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,content:B})}finally{clearTimeout(A)}}catch(w){return ie(`Error processing web tab ${b.url}:`,w),a(_,{title:b.title||"Unknown",url:b.url,error:w instanceof hU?"Web tab content extraction timed out":"Could not process web tab"})}},y=async(b,_,w)=>{try{let T=null,O=b.url;for(let A of f.getLeaves()){let B=f.getPageInfo(A).url;if(f.getYouTubeVideoId(B)===_){T=A,O=B;break}}if(!T)return s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:"Web tab not found or closed"});let E=T.view;if(!(E.webviewMounted===void 0||E.webviewFirstLoadFinished===void 0?!0:!!(E.webviewMounted&&E.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(T,r)}catch(A){return Ce(`YouTube tab content not loaded yet for ${O}:`,A),s({title:b.title||"YouTube Video",url:O,videoId:_,isActive:w,error:"Web tab content not loaded yet"})}let R=await f.getYouTubeTranscript(T,{timeoutMs:o}),I=R.transcript.length>0?R.transcript.map(A=>`${A.timestamp}: ${A.text}`).join(`
|
||
|
|
`):void 0;return s({title:R.title||b.title||"YouTube Video",url:O,videoId:R.videoId,channel:R.channel,description:R.description,uploadDate:R.uploadDate,duration:R.duration,genre:R.genre,transcript:I,isActive:w})}catch(T){return Ce(`YouTube transcript extraction failed for ${b.url}:`,T),s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:T instanceof Error?T.message:"Failed to extract video info"})}},g=[];if(u){let b=await h(u,Dge);g.push(b)}for(let b=0;b<l.length;b+=i){let _=l.slice(b,b+i),w=await Promise.all(_.map(T=>h(T,t3e)));g.push(...w)}return g.join("")}};Xe();Qe();Dt();var SSt=null;async function Hvi(){return SSt||(SSt=(await Promise.resolve().then(()=>(Qnn(),Ynn))).ContextCompactor),SSt.getInstance()}var bqe=class t{constructor(){this.contextProcessor=yqe.getInstance(),this.mention=QG.getInstance(),this.promptContextEngine=gqe.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a,s,u,l=[],c){try{F(`[ContextManager] Processing context for message ${e.id}`);let d=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=await kce(d,"",n,a),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,s),y=e.context?.urls||[],g=o==="copilot_plus"?await this.mention.processUrlList(y):{urlContext:"",imageUrls:[]},b=new Set([...p.map(J=>J.path),...l.map(J=>J.path),...h]),_=new Set,T=(e.context?.notes||[]).filter(J=>!h.has(J.path));i&&o!=="project"&&a&&!b.has(a.path)&&!T.some(J=>J.path===a.path)&&T.push(a);let O=await this.contextProcessor.processContextNotes(b,r,n,T,i,a,o);T.forEach(J=>{b.add(J.path),_.add(J.path)});let E=e.context?.tags||[],P="",R=[];if(E.length>0){let ne=Oge(n,E).filter(D=>!b.has(D.path));ne.length>0&&(P=await this.contextProcessor.processContextNotes(new Set,r,n,ne,!1,null,o),ne.forEach(D=>{b.add(D.path),_.add(D.path),R.push(D.path)}))}let I=e.context?.folders||[],A="",B=[];if(I.length>0){let ne=I.flatMap(D=>ite(n,D)).filter(D=>!b.has(D.path));ne.length>0&&(A=await this.contextProcessor.processContextNotes(new Set,r,n,ne,!1,null,o),ne.forEach(D=>{b.add(D.path),_.add(D.path),B.push(D.path)}))}let k=this.contextProcessor.processSelectedTextContexts(),q=e.context?.webTabs||[],Z=await this.contextProcessor.processContextWebTabs(q),V=m+O+P+A+g.urlContext+k+Z,Y=f+V,re=(o==="project"?1e6:ee().autoCompactThreshold)*4,ue=!1,le=V;if(Y.length>re){c?.(iw.COMPACTING);let ne=await(await Hvi()).compact(V);ne.wasCompacted&&(le=ne.content,Y=f+le,ue=!0,F(`[ContextManager] Compacted context: ${ne.originalCharCount} -> ${ne.compactedCharCount} chars`)),c?.(iw.DEFAULT)}F(`[ContextManager] Successfully processed context for message ${e.id}`);let L=ue?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,compactedContext:le,compactedPaths:Array.from(_)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:O,tagContextAddition:P,tagNotePaths:R,folderContextAddition:A,folderNotePaths:B,urlContext:g.urlContext,selectedText:k,webTabContext:Z});return{processedContent:Y,contextEnvelope:L}}catch(d){return F(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,r,n,o,i,a,s,u,l=[]){let c=r.getMessage(e);if(!c||c.sender!=="user"||!c.id)return;F(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=await this.processMessageContext(c,n,o,i,a,s,r,u,l);r.updateProcessedText(c.id,d,f),F(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,r){let n=r.getDisplayMessages(),o=n.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=n.slice(0,o).filter(p=>p.sender==="user"),a=new Map,s=[],u=new Set,l=-1;for(let p=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(g=>g.id==="L3_TURN")?.segments?.some(g=>g.metadata?.wasCompacted)){l=p;break}for(let p=0;p<i.length;p++){let h=i[p]
|
||
|
|
`);return{l2Context:/<prior_context\s+source=/.test(c)?c+`
|
||
|
|
|
||
|
|
`+Xnn():c,l2Paths:u}}buildPromptContextEnvelope(e){let r=e.message.id;if(!r)return;let n={};if(e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(n.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendParsedSegments(o,e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendParsedSegments(o,e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendParsedSegments(o,e.urlContext),this.appendParsedSegments(o,e.selectedText),this.appendParsedSegments(o,e.webTabContext),o.length>0&&(n.L3_TURN=o),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let r=e.message.id;if(!r)return;let n={};return e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(n.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,r){return Znn(e,r)}appendParsedSegments(e,r,n){let o=(r||"").trim();if(!o)return;let i=this.parseContextIntoSegments(o,!1);if(i.length>0)for(let a of i)n&&(a.metadata={...a.metadata,...n}),e.push(a);else e.push({id:`unparsed-${Date.now()}`,content:o,stable:!1,metadata:{source:"unparsed",...n}})}createMessageContext(e,r,n=zC()){return{notes:e,urls:r,selectedTextContexts:n}}async extractContextNotes(e,r,n=[]){return[...await ES(e,r),...n].filter((s,u,l)=>l.findIndex(c=>c.path===s.path)===u)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return zC()}compactSegmentForL2(e){let r=[...WX.map(i=>i.tag),"prior_context","prior_context_note"].join("|"),n=new RegExp(`<(${r})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g");return e.replace(n,(i,a)=>{let s=WX.find(u=>u.tag===a);return s&&!s.recoverable||a==="prior_context_note"?"":a==="prior_context"?i:s?Gnn(i,a):i}).trim()}};Dt();Xe();var tQ=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}addMessage(e,r,n,o,i){if(typeof e=="object"){let c=e,d=c.id||this.generateId(),f=c.timestamp||vg(new Date),p={id:d,displayText:c.message,processedText:c.originalMessage||c.message,sender:c.sender,timestamp:f,context:c.context,contextEnvelope:c.contextEnvelope,isVisible:c.isVisible!==!1,isErrorMessage:c.isErrorMessage,sources:c.sources,content:c.content,responseMetadata:c.responseMetadata};return this.messages.push(p),F(`[MessageRepository] Added message with ID: ${d}`),d}if(r===void 0||n===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let a=e,s=this.generateId(),u=vg(new Date),l={id:s,displayText:a,processedText:r,sender:n,timestamp:u,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(l),F(`[MessageRepository] Added message with ID: ${s}`),s}editMessage(e,r){let n=this.messages.find(o=>o.id===e);return n?n.displayText===r?(F(`[MessageRepository] No changes needed for message: ${e}`),!0):(n.displayText=r,n.sender==="user"||n.sender==="USER"?F(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(n.processedText=r,F(`[MessageRepository] Edited AI message ${e}`)),!0):(F(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,r,n){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=r,
|
||
|
|
`}return l+u});i!==o&&await t.vault.adapter.write(e,i)}async function vqe(t,e){let n=(await t.vault.adapter.read(e)).match(/^---\n([\s\S]*?)\n---/)?.[1];if(!n)return null;let o={};for(let i of n.split(`
|
||
|
|
`)){let a=i.match(/^(\w+):\s*(.+)/);a&&(o[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}return o}async function ton(t,e){let r=await t.vault.adapter.stat(e),n=e.split("/").pop()??"";return{path:e,name:n,basename:n.replace(/\.md$/,""),extension:"md",stat:r??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}}var f_=require("obsidian"),TSt=100;function Wvi(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Lfe=class{constructor(e,r,n){this.app=e;this.messageRepo=r;this.chainManager=n}async saveChat(e){try{let r=this.messageRepo.getDisplayMessages();if(r.length===0){new f_.Notice("No messages to save.");return}let n=ee(),o=this.formatChatContent(r),i=r[0].timestamp?.epoch||Date.now();await ql(n.defaultSaveFolder);let a=await this.findFileByEpoch(i),s=a?this.app.metadataCache.getFileCache(a)?.frontmatter:void 0,u=s?.topic,l=s?.lastAccessedAt;if(a&&!s)try{let h=await vqe(this.app,a.path);h&&(h.topic&&(u=h.topic),h.lastAccessedAt&&(l=Number(h.lastAccessedAt)))}catch{}let c=Gu(),d=a?a.path:this.generateFileName(c,r,i,u),f=this.generateNoteContent(o,i,e,u,l),p=a,m=a!=null&&xSt(this.app,a.path);if(a&&m)await this.app.vault.modify(a,f),F(`[ChatPersistenceManager] Updated existing chat file: ${a.path}`);else if(!xSt(this.app,d)&&await this.app.vault.adapter.exists(d))await this.app.vault.adapter.write(d,f),new f_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Updated existing chat file via adapter: ${d}`);else try{p=await this.app.vault.create(d,f),new f_.Notice(`Chat saved as note: ${d}`),F(`[ChatPersistenceManager] Created new chat file: ${d}`)}catch(h){if(this.isFileAlreadyExistsError(h)){let y=this.app.vault.getAbstractFileByPath(d);if(y&&y instanceof f_.TFile){let g=this.app.metadataCache.getFileCache(y)?.frontmatter;u=g?.topic??u;let b=g?.lastAccessedAt,_=this.generateNoteContent(o,i,e,u,b);await this.app.vault.modify(y,_),p=y,new f_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict by updating existing chat file: ${y.path}`)}else await this.app.vault.adapter.write(d,f),new f_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict via adapter: ${d}`)}else if(this.isNameTooLongError(h)){let y=c?`${c.id}__`:"",g=`${n.defaultSaveFolder}/${y}chat-${i}.md`;try{p=await this.app.vault.create(g,f),new f_.Notice(`Chat saved as note: ${g}`),Ce(`[ChatPersistenceManager] Used minimal filename due to length constraints: ${g}`)}catch(b){if(this.isFileAlreadyExistsError(b)){let _=this.app.vault.getAbstractFileByPath(g);if(_&&_ instanceof f_.TFile){let w=this.app.metadataCache.getFileCache(_)?.frontmatter,T=w?.lastAccessedAt,O=w?.topic,E=this.generateNoteContent(o,i,e,O,T);await this.app.vault.modify(_,E),p=_,new f_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict by updating existing chat file: ${_.path}`)}else await this.app.vault.adapter.write(g,f),new f_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict via adapter: ${g}`)}else throw b}}else throw h}this.generateTopicAsyncIfNeeded(c,p,r,u)}catch(r){ie("[ChatPersistenceManager] Error saving chat:",r),new f_.Notice("Failed to save chat as note. Check console for details.")}}async loadChat(e){try{let r;try{r=await this.app.vault.read(e)}catch{r=await this.app.vault.adapter.read(e.path)}let n=this.parseChatContent(r);return F(`[ChatPersistenceManager] Loaded ${n.length} messages from ${e.path}`),n}catch(r){return ie("[ChatPersistenceManager] Error loading chat:",r),new f_.Notice("Failed to load chat history. Check console for details."),[]}}async getChatHistoryFiles(){let e=ee(),r=await _qe(this.app,e.defaultSaveFolder);if(r.length===0)return[];let n=Gu();return r.filter(o=>n?o.basename.startsWith(`${n.id}__`):!o.basename.includes("__")||!o.basename.split("__")[0])}formatChatContent(e){return e.map(r=>{let n=r.timestamp?r.timestamp.display:"Unknown time",o=r.message;if(r.sender===ow){let a=wce(o);a&&(o
|
||
|
|
[Context: ${a.join(" | ")}]`)}return i+=`
|
||
|
|
[Timestamp: ${n}]`,i}).join(`
|
||
|
|
|
||
|
|
`)}parseChatContent(e){let r=[],n=e.match(/^---\n([\s\S]*?)\n---/),o=e;n&&(o=e.slice(n[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,a;for(;(a=i.exec(o))!==null;){let s=a[1]==="user"?Zs:ow,u=a[2].trim(),l=u.split(`
|
||
|
|
`),c=u,d="Unknown time",f,p=l.length;if(l[p-1]?.startsWith("[Timestamp: ")){let h=l[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&l[p-1]?.startsWith("[Context: ")){let h=l[p-1].match(/\[Context: (.*?)\]/);if(h){let y=h[1];f=this.parseContextString(y),p--}}if(c=l.slice(0,p).join(`
|
||
|
|
`).trim(),s===ow){c=c.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,"");let h=wce(c);h&&(c=h.contentAfter),c=c.replace(/\n{3,}/g,`
|
||
|
|
|
||
|
|
`).trim()}let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}r.push({message:c,sender:s,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return r}parseContextString(e){let r={notes:[],urls:[],tags:[],folders:[],webTabs:[]},n=e.split(" | ");for(let o of n){let i=o.trim();if(i.startsWith("Notes: ")){let a=i.substring(7);a&&(r.notes=a.split(", ").map(s=>{let u=s.trim(),l=this.app.vault.getAbstractFileByPath(u);if(l instanceof f_.TFile)return l;let c=u.includes("/")?u.split("/").pop():u,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===c);return d.length===1?(F(`[ChatPersistenceManager] Resolved legacy basename "${c}" to ${d[0].path}`),d[0]):(d.length>1?Ce(`[ChatPersistenceManager] Ambiguous basename "${c}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):Ce(`[ChatPersistenceManager] Note not found: ${u}`),null)}).filter(s=>s!==null))}else if(i.startsWith("URLs: ")){let a=i.substring(6);a&&(r.urls=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let a=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);a&&(r.webTabs=a.split(", ").map(s=>s.trim()).filter(s=>s.length>0).map(s=>({url:s})))}else if(i.startsWith("Tags: ")){let a=i.substring(6);a&&(r.tags=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Folders: ")){let a=i.substring(9);a&&(r.folders=a.split(", ").map(s=>s.trim()))}}if(r.notes.length>0||r.urls.length>0||r.tags.length>0||r.folders.length>0||r.webTabs.length>0)return r}async findFileByEpoch(e){let r=await this.getChatHistoryFiles();for(let n of r){let o=this.app.metadataCache.getFileCache(n)?.frontmatter?.epoch;if(o===void 0)try{let a=await vqe(this.app,n.path);a?.epoch&&(o=Number(a.epoch))}catch{continue}let i=typeof o=="number"?o:typeof o=="string"?Number(o):void 0;if(typeof i=="number"&&!Number.isNaN(i)&&i===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((c,d,f)=>f>=n?c:c+(c?`
|
||
|
|
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,s=await r.invoke(a),u=typeof s=="string"?s:s.content??s.text??s;return tF(u).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(r){ie("[ChatPersistenceManager] Error generating AI topic:",r);return}}generateFileName(e,r,n,o){let i=ee(),s=vg(new Date(n)).fileName,u;if(o)u=o;else{let T=r.find(O=>O.sender===Zs);u=T&&T.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let l=i.defaultConversationNoteName||"{$date}_{$time}__{$topic}",c=e===void 0?Gu():e,d=c?`${c.id}__`:"",f=b4(".md"),p=b4(d),m=l.replace("{$topic}","").replace("{$date}",s.split("_")[0]).replace("{$time}",s.split("_")[1]),h=b4(m),y=Math.max(20,TSt-f-p-h),g=u.replace(/\s+/g,"_"),b=ote(g,y);l=l.replace("{$topic}",b).replace("{$date}",s.split("_")[0]).replace("{$time}",s.split("_")[1]);let _=l.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),w=`${d}${_}.md`;if(b4(w)>TSt){let T=TSt-f-p,O=ote(_,T);return`${i.defaultSaveFolder}/${d}${O}.md`}return`${i.defaultSaveFolder}/${w}`}generateNoteContent(e,r,n,o,i){let a=ee(),s=Gu();return`---
|
||
|
|
epoch: ${r}
|
||
|
|
modelKey: "${Wvi(n)}"
|
||
|
|
${o?`topic: "${o}"`:""}
|
||
|
|
${i?`lastAccessedAt: ${i}`:""}
|
||
|
|
${s?`projectId: ${s.id}`:""}
|
||
|
|
${s?`projectName: ${s.name}`:""}
|
||
|
|
tags:
|
||
|
|
- ${a.defaultConversationTag}
|
||
|
|
---
|
||
|
|
|
||
|
|
${e}`}generateTopicAsyncIfNeeded(e,r,n,o){!ee().generateAIChatTitleOnSave||!r||o||(async()=>{try{let a=await this.generateAITopic(n);if(!a)return;await this.applyTopicToFrontmatter(r,a),await this.renameFileToMatchTopic(e,r,a)}catch(a){ie("[ChatPersistenceManager] Error during async topic generation:",a)}})()}async applyTopicToFrontmatter(e,r){try{await $fe(this.app,e.path,{topic:r.trim()}),F(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(n){ie("[ChatPersistenceManager] Error applying AI topic to file:",n)}}isNameTooLongError(e){if(!e)return!1;let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?(e instanceof Error?e.message:String(e)).toLowerCase().includes("already exists"):!1}async renameFileToMatchTopic(e,r,n){if(!r||!n)return;let o,i=this.app.metadataCache.getFileCache(r);if(i?.frontmatter?.epoch)o=i.frontmatter.epoch;else try{let u=await vqe(this.app,r.path);u?.epoch&&(o=Number(u.epoch))}catch{}if(!o)return;let a=this.messageRepo.getDisplayMessages(),s=this.generateFileName(e,a,o,n);r.path!==s&&await this.app.fileManager.renameFile(r,s)}};gr();T3();AZ();var wqe=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=bqe.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new Lfe(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(F(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){F(`[ChatManager] Creating new message repository for project: ${r}`);let o=new tQ;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new Lfe(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,r,n){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!ee().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await kce(e,"",r,n,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return Ce("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:r,userCustomPrompt:n,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(r)?r.replace(i,()=>`<user_custom_instructions>
|
||
|
|
${o}
|
||
|
|
</user_custom_instructions>`):r===n?o:(F("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),r)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:r,systemPromptWithoutMemory:n,processedSystemPromptWithoutMemory:o}=e;return r.endsWith(n)?`${r.slice(0,r.length-n.length)}${o}`:(F("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),r)}async getSystemPromptForMessage(e,r,n){let o=pDe(),i=[],a=await _$(this.chainManager.userMemoryManager),s=b$(),u=a;if(o){let l=await this.processSystemPromptTemplates(o,r,n),c=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:s,userCustomPrompt:o,processedUserCustomPrompt:l.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:a,systemPromptWithoutMemory:s,processedSystemPromptWithoutMemory:c});d!==a&&i.push(...l.includedFiles),u=d}if(e==="project"){let l=Gu();if(l){let c=await Vg.instance.getProjectContext(l.id),d=await this.processSystemPromptTemplates(l.systemPrompt,r,n);i.push(...d.includedFiles);let f=`${u}
|
||
|
|
|
||
|
|
<project_system_prompt>
|
||
|
|
${d.processedPrompt}
|
||
|
|
</project_system_prompt>`;if(c){let m=c;c.length>24e5&&(m=c.substring(0,24e5),Ce(`Project context truncated from ${Math.round(c.length/4e3)}k to ${Math.round(24e5/4e3)}k estimated tokens to stay within token budget`)),f+=`
|
||
|
|
|
||
|
|
<project_context>
|
||
|
|
${m}
|
||
|
|
</project_context>`}return{processedPrompt:f,includedFiles:i}}}return{processedPrompt:u,includedFiles:i}}buildWebTabsWithActiveSnapshot(e,r){let n=$8r(e);if(!r)return n;try{let a=md(this.plugin.app).getActiveWebTabState().activeWebTabForMentions,s=IZ(a?.url);if(!s)return n;let u=n.map(c=>{if(c.isActive){let{isActive:d,...f}=c;return f}return c}),l=u.findIndex(c=>IZ(c.url)===s);if(l>=0){let c=u[l];return u[l]={...c,url:ub(a?.url)??c.url,title:a?.title??c.title,faviconUrl:a?.faviconUrl??c.faviconUrl,isActive:!0},u}return[...u,{url:ub(a?.url)??s,title:a?.title,faviconUrl:a?.faviconUrl,isActive:!0}]}catch(o){return Ce("[ChatManager] Failed to resolve active web tab:",o),n}}async sendMessage(e,r,n,o=!1,i=!1,a,s){try{F(`[ChatManager] Sending message: "${e}"`);let u=this.plugin.app.workspace.getActiveFile(),l={...r};if(o&&u){let _=r.notes||[],w=_.some(T=>T.path===u.path);l.notes=w?_:[..._,u]}let d=!((l.selectedTextContexts||[]).length>0)&&(i||e.includes(yte));l.webTabs=this.buildWebTabsWithActiveSnapshot(l.webTabs||[],d);let f=this.getCurrentMessageRepo(),p=f.addMessage(e,e,Zs,l,a);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=f.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:y}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,u),{processedContent:g,contextEnvelope:b}=await this.contextManager.processMessageContext(m,this.fileParserManager,this.plugin.app.vault,n,o,u,f,h,y,s);return f.updateProcessedText(p,g,b),F(`[ChatManager] Successfully sent message ${p}`),p}catch(u){throw F("[ChatManager] Error sending message:",u),u}}async editMessage(e,r,n,o=!1){try{F(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile(),{processedPrompt:u,includedFiles:l}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,s);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s,u,l),await this.updateChainMemory(),F(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return F(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{F(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return F(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return F("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Zs)return F("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return F("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return F("[ChatManager] LLM message not found for regeneration"),!1;if(!c.contextEnvelope){F("[ChatManager] Context envelope missing, reprocessing context for regeneration");let f=UC(),p=this.plugin.app.workspace.getActiveFile(),{processedPrompt:m,includedFiles:h}=await this.getSystemPromptForMessage(f,this.plugin.app.vault,p);await this.contextManager.reprocessMessageContext(l.id,i,this.fileParserManager,this.plugin.app.vault,f,!1,p,m,h),c=i.getLLMMessage(l.id)}let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:ee().debug}),F(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return F(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return F(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),F(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return F(`[ChatManager] Error deleting message ${e}:`,r),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),F("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.up
|
||
|
|
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.
|
||
|
|
`},Qvi={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 ewi(t){let{announcements:e=Qvi,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=Yvi}=t,{announce:i,announcement:a}=pon(),s=g6("DndLiveRegion"),[u,l]=(0,Ze.useState)(!1);if((0,Ze.useEffect)(()=>{l(!0)},[]),Xvi((0,Ze.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=Ze.default.createElement(Ze.default.Fragment,null,Ze.default.createElement(don,{id:n,value:o.draggable}),Ze.default.createElement(fon,{id:s,announcement:a}));return r?(0,v6.createPortal)(c,r):c}var _h;(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"})(_h||(_h={}));function Rqe(){}function iQ(t,e){return(0,Ze.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function Aqe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Ze.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var DT=Object.freeze({x:0,y:0});function Eon(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Pon(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function twi(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function mon(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 $St(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function hon(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 aQ=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=hon(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=Eon(hon(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(Pon)},Mon=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=mon(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=mon(u),c=o.reduce((f,p,m)=>f+Eon(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(Pon)};function rwi(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 nwi=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=rwi(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(twi)};function owi(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function Ron(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:DT}function iwi(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 awi=iwi(1);function swi(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
|
||
|
|
|
||
|
|
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
|
||
|
|
|
||
|
|
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return al.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},qSi="DialogDescriptionWarning",BSi=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${vin(qSi).contentName}}.`;return al.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},win=ain,Sin=uin,Cin=cin,zSt=din,VSt=fin,HSt=min,WSt=gin,xin=bin;Mr();zr();var Kqe=win,Tin=Sin,zSi=Cin;var Oin=dy.forwardRef(({className:t,...e},r)=>dy.createElement(zSt,{ref:r,className:Se("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}));Oin.displayName=zSt.displayName;var Zfe=dy.forwardRef(({className:t,children:e,container:r,...n},o)=>dy.createElement(zSi,{container:r},dy.createElement(Oin,null),dy.createElement(VSt,{ref:o,className:Se("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,dy.createElement(xin,{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"},dy.createElement(Ho,{className:"tw-size-4"}),dy.createElement("span",{className:"tw-sr-only"},"Close")))));Zfe.displayName=VSt.displayName;var Yfe=({className:t,...e})=>dy.createElement("div",{className:Se("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});Yfe.displayName="DialogHeader";var VSi=({className:t,...e})=>dy.createElement("div",{className:Se("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});VSi.displayName="DialogFooter";var Qfe=dy.forwardRef(({className:t,...e},r)=>dy.createElement(HSt,{ref:r,className:Se("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));Qfe.displayName=HSt.displayName;var epe=dy.forwardRef(({className:t,...e},r)=>dy.createElement(WSt,{ref:r,className:Se("tw-text-sm tw-text-muted",t),...e}));epe.displayName=WSt.displayName;Dt();function Rr(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=sz(),a="onChange"in t?t.onChange:void 0,s=(0,Al.useMemo)(()=>{if(a)return Ige(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return Al.default.createElement(ni,{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 Al.default.createElement(xN,{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 Al.default.createElement(n_,{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 Al.default.createElement(tT,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Al.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Al.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:Se("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-s
|
||
|
|
detail: `+f)}return d}finally{clearTimeout(c)}},i;try{i=await o(!1)}catch(u){Ce("First fetch attempt failed, trying with safeFetch...");try{i=await o(!0)}catch(l){let c=`
|
||
|
|
without CORS Error: `+Wr(u)+`
|
||
|
|
with CORS Error: `+Wr(l);throw new Error(c)}}let a=await i.json();return{success:!0,models:JSt(t,a)}}catch(e){return ie(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:Wr(e)}}}async function Nin(t,e,r){let n=r?.skipVerification??!1,i=!!e.find(c=>c.name===t.name&&c.provider===t.provider),a=t.provider==="github-copilot"?void 0:nw(t.provider),s={name:t.name,provider:t.provider,apiKey:a,enabled:!0},u=!1,l;if(!n)try{await Vg.instance.getCurrentChainManager().chatModelManager.ping(s)}catch(c){if(u=!0,l=Wr(c),s.provider==="github-copilot"&&l.toLowerCase().includes("not supported")){let d=g$.getInstance().getPolicyTerms(t.id);d&&(l+=`
|
||
|
|
|
||
|
|
${d}`)}ie("Model verification failed:",c)}return{success:!0,alreadyExists:i,verificationFailed:u,verificationError:l}}function Din(t){return{name:t.name,provider:t.provider,enabled:!0}}Dt();Mr();var OL=require("obsidian"),Gs=$(K());function ZSi(t){return t.split(/\n\n+/).map((r,n)=>{let i=r.split(/(\[[^\]]+\]\([^)]+\))/g).map((a,s)=>{let u=a.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return u?Gs.default.createElement("a",{key:s,href:u[2],target:"_blank",rel:"noopener noreferrer",className:"tw-underline"},u[1]):a});return Gs.default.createElement("p",{key:n,className:n>0?"tw-mt-1":""},i)})}function Zqe({provider:t,isReady:e,expanded:r=!1,skipVerification:n=!1,credentialVersion:o}){let i=kr(),[a,s]=(0,Gs.useState)(null),[u,l]=(0,Gs.useState)(!1),[c,d]=(0,Gs.useState)(null),[f,p]=(0,Gs.useState)(null),[m,h]=(0,Gs.useState)(!1),[y,g]=(0,Gs.useState)(null),b=(0,Gs.useRef)(!1),_=(0,Gs.useCallback)(async()=>{if(!(b.current||!e)){b.current=!0,l(!0),d(null);try{let O=await Ain(t);O.success?s(O.models):(d(O.error||"Failed to load models"),new OL.Notice(`Failed to load models for ${wg(t)}: ${O.error}`,5e3))}catch(O){let E=Wr(O);d(E),new OL.Notice(`Failed to load models for ${wg(t)}: ${E}`,5e3)}finally{l(!1),b.current=!1}}},[t,e]);(0,Gs.useEffect)(()=>{s(null),p(null),d(null),g(null)},[t,o]),(0,Gs.useEffect)(()=>{r&&e&&a===null&&!u&&!c&&_()},[r,e,a,u,c,_]);let w=async()=>{if(!f){new OL.Notice("Please select a model first");return}h(!0),g(null);try{let O=await Nin({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:n});if(O.alreadyExists)O.verificationFailed?(g(O.verificationError??null),new OL.Notice(`Model ${f.name} already exists (verification failed: ${O.verificationError})`,1e4)):new OL.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let E=Din({id:f.id,name:f.name,provider:t}),P=[...i.activeModels,E];Re("activeModels",P),O.verificationFailed?(g(O.verificationError??null),new OL.Notice(`Model ${f.name} added (verification failed: ${O.verificationError})`,1e4)):new OL.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(O){ie("Error adding model:",O),new OL.Notice(`Failed to add model: ${Wr(O)}`)}finally{h(!1)}},T=a?.filter((O,E,P)=>P.findIndex(R=>R.id===O.id)===E).sort((O,E)=>O.name.localeCompare(E.name));return Gs.default.createElement(ko,{label:"Model",description:"Add the selected model to your models list. After adding, check the Model Tab."},Gs.default.createElement("div",null,Gs.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Gs.default.createElement("div",{className:"tw-flex-1"},Gs.default.createElement(dN,{options:T?.map(O=>({label:O.name,value:O.id}))||[],onChange:O=>{let E=O.target.value,P=a?.find(R=>R.id===E);P&&(p(P),g(null))},onClick:()=>{a===null&&!u&&_()},value:f?.id||"",placeholder:"Select Model",disabled:!e||u})),Gs.default.createElement("div",{className:"tw-w-[72px]"},Gs.default.createElement(me,{onClick:w,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},m?Gs.default.createElement(Us,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),Gs.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},u&&Gs.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),c&&Gs.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models. ",c),a&&a.length===0&&Gs.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models available."),a===null&&!u&&!c&&Gs.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Click to load available models."),y&&Gs.default.createElement("div",{className:"tw-mt-2 tw-rounded-md tw-border tw-border-border tw-p-2 tw-text-error tw-bg-modifier-error/10"},ZSi(y)))))}Mr();var O6=require("obsidian"),Sr=$(K());function jin(){let t=kr(),[e]=(0,Sr.useState)(()=>g$.getInstance()),[r,n]=(0,Sr.useState)("idle"),[o,i]=(0,Sr.useState)(null),[a,s]=(0,Sr.useState)(0),[u,l]=(0,Sr.useState)(null),[c,d]=(0,Sr.useState)(!1),f=(0,Sr.useRef)(0),p=(0,Sr.useRef)(!0);(0,Sr.useEffect)(()=>(p.current=!0,(
|
||
|
|
`)}async function p0i(t,e){let r=[],n=t.provider?.trim()??"",o=Qqe(n),i=t.baseUrl?.trim()??"",a=fz(i||o||"https://api.example.com/v1"),s=c0i(a),u=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let l=await mQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${l.apiKey}`};return t.openAIOrgId?.trim()&&(c["OpenAI-Organization"]=t.openAIOrgId.trim()),n==="openrouterai"&&(c["HTTP-Referer"]="https://obsidiancopilot.com",c["X-Title"]="Obsidian Copilot"),e?{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/embeddings`,headers:c,body:{model:u,input:npe}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/chat/completions`,headers:c,body:{model:u,messages:[{role:"user",content:P6}],stream:!1,max_tokens:KSt}}}}function m0i(t,e,r,n){let o=[],i=t.azureOpenAIApiInstanceName?.trim()||"[instance]";t.azureOpenAIApiInstanceName?.trim()||o.push("Azure instance name is empty; using placeholder.");let a=t.baseUrl?.trim();if(a){let s=l0i(a);if(s){let u=fz(s.pathname||"");u.includes("/openai/deployments/")&&(u=u.split("/openai/deployments/")[0]);let l=`${s.origin}${u}`;return{warnings:o,url:`${l}/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}}return{warnings:o,url:`https://${i}.openai.azure.com/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}async function h0i(t,e){let r=[],n=await mQ(t.apiKey);r.push(...n.warnings);let o=e?"embeddings":"chat/completions";if(t.baseUrl?.trim()){let{normalizeAzureUrl:l}=await Promise.resolve().then(()=>(LW(),imt)),{baseUrl:c,apiVersion:d}=l(t.baseUrl.trim()),f=d||t.azureOpenAIApiVersion?.trim()||"2024-05-01-preview",p=`${c}/${o}?api-version=${encodeURIComponent(f)}`,m=t.name?.trim(),h=e?{input:npe,...m?{model:m}:{}}:{messages:[{role:"user",content:P6}],stream:!1,max_tokens:KSt,...m?{model:m}:{}};return{ok:!0,warnings:r,spec:{method:"POST",url:p,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":n.apiKey},body:h}}}let i=e?t.azureOpenAIApiEmbeddingDeploymentName?.trim()||"[deployment]":t.azureOpenAIApiDeploymentName?.trim()||"[deployment]";(!i||i==="[deployment]")&&r.push("Azure deployment name is empty; using placeholder.");let a=t.azureOpenAIApiVersion?.trim()||"[api-version]";t.azureOpenAIApiVersion?.trim()||r.push("Azure api-version is empty; using placeholder.");let s=m0i(t,i,o,a);r.push(...s.warnings);let u=e?{input:npe}:{messages:[{role:"user",content:P6}],stream:!1,max_tokens:KSt};return{ok:!0,warnings:r,spec:{method:"POST",url:s.url,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":n.apiKey},body:u}}}async function g0i(t){let e=[],r=t.baseUrl?.trim()??"",n=Qqe("anthropic"),o=fz(r||n||"https://api.anthropic.com"),i=["/v1/messages","/v1"];for(let l of i)if(o.endsWith(l)){o=o.slice(0,-l.length);break}let a=`${o}/v1/messages`,s=await mQ(t.apiKey);e.push(...s.warnings);let u=t.name?.trim()||"<MODEL_NAME>";return t.name?.trim()||e.push("Model name is empty; using placeholder."),{ok:!0,warnings:e,spec:{method:"POST",url:a,headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":s.apiKey,"anthropic-version":n0i},body:{model:u,max_tokens:i0i,messages:[{role:"user",content:P6}]}}}}async function y0i(t,e){let r=[],n=t.baseUrl?.trim()??"",o=Qqe("google"),a=d0i(n||o||"https://generativelanguage.googleapis.com"),s=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let u=s.includes("/")?s:`models/${s}`,l=await mQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":l.apiKey};return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:embedContent`,headers:c,body:{content:{parts:[{text:npe}]}}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:generateContent`,headers:c,body:{contents:[{role:"user",parts:[{text:P6}]}],generationConfig:{maxOutputTokens:s0i}}}}}function b0i(t){return/(^|\.)anthropic\./.test(t)}async function _0i(t){le
|
||
|
|
`),warnings:e}}async function v0i(t,e){let r=[],n=t.baseUrl?.trim()??"",o=Qqe("ollama"),i=f0i(fz(n||o||"http://localhost:11434")),a=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let s={"Content-Type":"application/json",Accept:"application/json"};if(t.apiKey?.trim()){let l=await mQ(t.apiKey),c=l.warnings.filter(d=>!d.includes("API key is empty"));r.push(...c),s.Authorization=`Bearer ${l.apiKey}`}return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/embed`,headers:s,body:{model:a,input:npe,truncate:!0}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/chat`,headers:s,body:{model:a,messages:[{role:"user",content:P6}],stream:!1}}}}async function Vin(t){let e=[],r=t.provider?.trim();if(!r)return{ok:!1,error:"Provider is required to build a curl command.",warnings:e};let n=!!t.isEmbeddingModel;if(r==="azure openai"){let o=await h0i(t,n);return o.ok?{ok:!0,command:E6(o.spec),warnings:o.warnings}:o}if(r==="anthropic"){if(n)return{ok:!1,error:"Anthropic does not support embeddings.",warnings:e};let o=await g0i(t);return o.ok?{ok:!0,command:E6(o.spec),warnings:o.warnings}:o}if(r==="amazon-bedrock")return n?{ok:!1,error:"Bedrock embeddings are not supported by this generator.",warnings:e}:await _0i(t);if(r==="google"||r==="google"){let o=await y0i(t,n);return o.ok?{ok:!0,command:E6(o.spec),warnings:o.warnings}:o}if(r==="ollama"||r==="ollama"){let o=await v0i(t,n);return o.ok?{ok:!0,command:E6(o.spec),warnings:o.warnings}:o}if(u0i.has(r)){let o=await p0i(t,n);return o.ok?{ok:!0,command:E6(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider "${r}" is not supported for curl generation.`,warnings:e}}Mr();g4();var pz=require("obsidian"),Ye=$(K()),GSt=({open:t,onOpenChange:e,onAdd:r,ping:n,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=sz(),a=ee(),s=o?"openai":"openrouterai",u=L=>L==="azure openai"&&!E.baseUrl,[l,c]=(0,Ye.useState)(null),[d,f]=(0,Ye.useState)(u(s)),[p,m]=(0,Ye.useState)(!1),[h,y]=(0,Ye.useState)("idle"),[g,b]=(0,Ye.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),_=(L,J)=>{b(ne=>({...ne,[L]:J}))},w=()=>{b({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},T=()=>{let L=!0,J={...g};return J.name=!E.name,E.name||(L=!1),E.provider==="azure openai"&&(o||!E.baseUrl?.trim())&&(J.instanceName=!E.azureOpenAIApiInstanceName,J.apiVersion=!E.azureOpenAIApiVersion,o?(J.embeddingDeploymentName=!E.azureOpenAIApiEmbeddingDeploymentName,E.azureOpenAIApiEmbeddingDeploymentName||(L=!1)):(J.deploymentName=!E.azureOpenAIApiDeploymentName,E.azureOpenAIApiDeploymentName||(L=!1)),(!E.azureOpenAIApiInstanceName||!E.azureOpenAIApiVersion)&&(L=!1)),E.provider,"amazon-bedrock",J.bedrockRegion=!1,b(J),L},O=(L=s)=>{let J={name:"",provider:L,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:nw(L),isEmbeddingModel:o,capabilities:[]};if(!o){let ne={...J,stream:!0};return L==="amazon-bedrock"?{...ne,bedrockRegion:a.amazonBedrockRegion}:ne}return J},[E,P]=(0,Ye.useState)(O()),R=L=>{P(J=>({...J,...L})),y("idle")},I=L=>({...L,name:L.name?.trim(),baseUrl:L.baseUrl?.trim(),apiKey:L.apiKey?.trim(),openAIOrgId:L.openAIOrgId?.trim(),azureOpenAIApiInstanceName:L.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:L.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:L.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:L.azureOpenAIApiVersion?.trim(),bedrockRegion:L.bedrockRegion?.trim()}),[A,B]=(0,Ye.useState)(o1(s)),k=()=>!!(E.name&&E.provider),q=()=>p||!k(),Z=()=>{if(!T()){new pz.Notice("Please fill in all required fields");return}let L=I(E);r(L),e(!1),P(O()),w(),y("idle"),f(!1)},V=L=>{B(o1(L)),y("idle"),P({...E,provider:L,apiKey:nw(L),...L==="openai"?{openAIOrgId:a.openAIOrgId}:{},...L==="azure openai"?{azureOpenAIApiInstanceName:a.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:a.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:a.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentName:a.
|
||
|
|
/*! 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
|
||
|
|
*)
|
||
|
|
|
||
|
|
@langchain/core/dist/utils/sax-js/sax.js:
|
||
|
|
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
|
||
|
|
|
||
|
|
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-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/arrow-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/book-open.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/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.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/check.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/chevron-down.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/chevron-right.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/chevron-up.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle-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-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/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.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle-help.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle-plus.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle-stop.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle-x.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/circle.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/clipboard-paste.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/coins.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-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/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-clock.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/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/hash.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-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-square-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/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/pause.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/play.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/plus.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/refresh-ccw.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/refresh-cw.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/replace.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/rotate-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/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/send.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/settings.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/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/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/wrench.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/icons/x.js:
|
||
|
|
(**
|
||
|
|
* @license lucide-react v0.462.0 - ISC
|
||
|
|
*
|
||
|
|
* This source code is licensed under the ISC license.
|
||
|
|
* See the LICENSE file in the root directory of this source tree.
|
||
|
|
*)
|
||
|
|
|
||
|
|
lucide-react/dist/esm/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
|
||
|
|
*
|
||
|
|
* 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.
|
||
|
|
*)
|
||
|
|
|
||
|
|
safe-buffer/index.js:
|
||
|
|
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
||
|
|
|
||
|
|
@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
|
||
|
|
*)
|
||
|
|
|
||
|
|
@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 */
|