`].join("");var J}function MI(F){return F.flags!==void 0?F.flags:[F.global?"g":"",F.ignoreCase?"i":"",F.multiline?"m":"",F.unicode?"u":"",F.sticky?"y":""].join("")}function x(){for(var F=[].slice.call(arguments),u=F.length,J=0;J<u;J+=1)C(F[J]);return c(function(L,M){for(var D,q=new Array(u),hI=0;hI<u;hI+=1){if(!(D=e(F[hI]._(L,M),D)).status)return D;q[hI]=D.value,M=D.index}return e(w(M,q),D)})}function FI(){var F=[].slice.call(arguments);if(F.length===0)throw new Error("seqMap needs at least one argument");var u=F.pop();return j(u),x.apply(null,F).map(function(J){return u.apply(null,J)})}function nI(){var F=[].slice.call(arguments),u=F.length;if(u===0)return iZ("zero alternates");for(var J=0;J<u;J+=1)C(F[J]);return c(function(L,M){for(var D,q=0;q<F.length;q+=1)if((D=e(F[q]._(L,M),D)).status)return D;return D})}function UG(F,u){return zc(F,u).or(pb([]))}function zc(F,u){return C(F),C(u),FI(F,u.then(F).many(),function(J,L){return[J].concat(L)})}function AZ(F){k(F);var u="'"+F+"'";return c(function(J,L){var M=L+F.length,D=J.slice(L,M);return D===F?w(M,D):o(L,u)})}function _l(F,u){(function(M){if(!(M instanceof RegExp))throw new Error("not a regexp: "+M);for(var D=MI(M),q=0;q<D.length;q++){var hI=D.charAt(q);if(hI!=="i"&&hI!=="m"&&hI!=="u"&&hI!=="s")throw new Error('unsupported regexp flag "'+hI+'": '+M)}})(F),arguments.length>=2?A(u):u=0;var J=function(M){return RegExp("^(?:"+M.source+")",MI(M))}(F),L=""+F;return c(function(M,D){var q=J.exec(M.slice(D));if(q){if(0<=u&&u<=q.length){var hI=q[0],TI=q[u];return w(D+hI.length,TI)}return o(D,"valid match group (0 to "+q.length+") in "+L)}return o(D,L)})}function pb(F){return c(function(u,J){return w(J,F)})}function iZ(F){return c(function(u,J){return o(J,F)})}function xc(F){if(X(F))return c(function(u,J){var L=F._(u,J);return L.index=J,L.value="",L});if(typeof F=="string")return xc(AZ(F));if(F instanceof RegExp)return xc(_l(F));throw new Error("not a string, regexp, or parser: "+F)}function OY(F){return C(F),c(function(u,J){var L=F._(u,J),M=u.slice(J,L.index);return L.status?o(J,'not "'+M+'"'):w(J,null)})}function yl(F){return j(F),c(function(u,J){var L=i(u,J);return J<u.length&&F(L)?w(J+1,L):o(J,"a character/byte matching "+F)})}function LZ(F,u){arguments.length<2&&(u=F,F=void 0);var J=c(function(L,M){return J._=u()._,J._(L,M)});return F?J.desc(F):J}function Uc(){return iZ("fantasy-land/empty")}W.parse=function(F){if(typeof F!="string"&&!z(F))throw new Error(".parse must be called with a string or Buffer as its argument");var u,J=this.skip(Bc)._(F,0);return u=J.status?{status:!0,value:J.value}:{status:!1,index:bI(F,J.furthest),expected:J.expected},delete _[F],u},W.tryParse=function(F){var u=this.parse(F);if(u.status)return u.value;var J=YG(F,u),L=new Error(J);throw L.type="ParsimmonError",L.result=u,L},W.assert=function(F,u){return this.chain(function(J){return F(J)?pb(J):iZ(u)})},W.or=function(F){return nI(this,F)},W.trim=function(F){return this.wrap(F,F)},W.wrap=function(F,u){return FI(F,this,u,function(J,L){return L})},W.thru=function(F){return F(this)},W.then=function(F){return C(F),x(this,F).map(function(u){return u[1]})},W.many=function(){var F=this;return c(function(u,J){for(var L=[],M=void 0;;){if(!(M=e(F._(u,J),M)).status)return e(w(J,L),M);if(J===M.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");J=M.index,L.push(M.value)}})},W.tieWith=function(F){return k(F),this.map(function(u){if(function(M){if(!v(M))throw new Error("not an array: "+M)}(u),u.length){k(u[0]);for(var J=u[0],L=1;L<u.length;L++)k(u[L]),J+=F+u[L];return J}return""})},W.tie=function(){return this.tieWith("")},W.times=function(F,u){var J=this;return arguments.length<2&&(u=F),A(F),A(u),c(function(L,M){for(var D=[],q=void 0,hI=void 0,TI=0;TI<F;TI+=1){if(hI=e(q=J._(L,M),hI),!q.status)return hI;M=q.index,D.push(q.value)}for(;TI<u&&(hI=e(q=J._(L,M),hI),q.status);TI+=1)M=q.index,D.push(q.value);return e(w(M,D),hI)})},W.result=function(F){return this.map(function(){return F})},W.atMost=function(F){return this.ti
`),Cp=AZ(`\r
`),gp=nI(Cp,yp,Jp).desc("newline"),ew=nI(gp,Bc);c.all=MY,c.alt=nI,c.any=yd,c.cr=Jp,c.createLanguage=function(F){varu={};for(varJinF)({}).hasOwnProperty.call(F,J)&&function(L){u[L]=LZ(function(){returnF[L](u)})}(J);returnu},c.crlf=Cp,c.custom=function(F){returnc(F(w,o))},c.digit=jY,c.digits=KY,c.empty=Uc,c.end=ew,c.eof=Bc,c.fail=iZ,c.formatError=YG,c.index=dZ,c.isParser=X,c.lazy=LZ,c.letter=Hw,c.letters=nw,c.lf=yp,c.lookahead=xc,c.makeFailure=o,c.makeSuccess=w,c.newline=gp,c.noneOf=function(F){returnyl(function(u){returnF.indexOf(u)<0}).desc("none of '"+F+"'")},c.notFollowedBy=OY,c.of=pb,c.oneOf=function(F){for(varu=F.split(""),J=0;J<u.length;J++)u[J]="'"+u[J]+"'";returnyl(function(L){returnF.indexOf(L)>=0}).desc(u)},c.optWhitespace=uw,c.Parser=c,c.range=function(F,u){returnyl(function(J){returnF<=J&&J<=u}).desc(F+"-"+u)},c.regex=_l,c.regexp=_l,c.sepBy=UG,c.sepBy1=zc,c.seq=x,c.seqMap=FI,c.seqObj=function(){for(varF,u={},J=0,L=(F=arguments,Array.prototype.slice.call(F)),M=L.length,D=0;D<M;D+=1){varq=L[D];if(!X(q)){if(v(q)&&q.length===2&&typeofq[0]=="string"&&X(q[1])){varhI=q[0];if(Object.prototype.hasOwnProperty.call(u,hI))thrownewError("seqObj: duplicate key "+hI);u[hI]=!0,J++;continue}thrownewError("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(J===0)thrownewError("seqObj expects at least one named parser, found zero");returnc(function(TI,PG){for(variG,xb={},Ql=0;Ql<M;Ql+=1){varUb,Oc;if(v(L[Ql])?(Ub=L[Ql][0],Oc=L[Ql][1]):(Ub=null,Oc=L[Ql]),!(iG=e(Oc._(TI,PG),iG)).status)returniG;Ub&&(xb[Ub]=iG.value),PG=iG.index}returne(w(PG,xb),iG)})},c.string=AZ,c.succeed=pb,c.takeWhile=function(F){returnj(F),c(function(u,J){for(varL=J;L<u.length&&F(i(u,L));)L++;returnw(L,u.slice(J,L))})},c.test=yl,c.whitespace=tw,c["fantasy-land/empty"]=Uc,c["fantasy-land/of"]=pb,c.Binary={bitSeq:h,bitSeqObj:function(F){a();varu={},J=0,L=N(function(D){if(v(D)){varq=D;if(q.length!==2)thrownewError("["+q.join(", ")+"] should be length 2, got length "+q.length);if(k(q[0]),A(q[1]),Object.prototype.hasOwnProperty.call(u,q[0]))thrownewError("duplicate key in bitSeqObj: "+q[0]);returnu[q[0]]=!0,J++,q}returnA(D),[null,D]},F);if(J<1)thrownewError("bitSeqObj expects at least one named pair, got ["+F.join(", ")+"]");varM=N(function(D){returnD[0]},L);returnh(N(function(D){returnD[1]},L)).map(function(D){returnm(function(q,hI){returnhI[0]!==null&&(q[hI[0]]=hI[1]),q},{},N(function(q,hI){return[q,D[hI]]},M))})},byte:function(F){if(a(),A(F),F>255)thrownewError("Value specified to byte constructor ("+F+"=0x"+F.toString(16)+") is larger in value than a single byte.");varu=(F>15?"0x":"0x0")+F.toString(16);returnc(function(J,L){varM=i(J,L);returnM===F?w(L+1,M):o(L,u)})},buffer:function(F){returnR("buffer",F).map(function(u){returnBuffer.from(u)})},encodedString:function(F,u){returnR("string",u).map(function(J){returnJ.toString(F)})},uintBE:p,uint8BE:p(1),uint16BE:p(2),uint32BE:p(4),uintLE:n,uint8LE:n(1),uint16LE:n(2),uint32LE:n(4),intBE:t,int8BE:t(1),int16BE:t(2),int32BE:t(4),intLE:s,int8LE:s(1),int16LE:s(2),int32LE:s(4),floatBE:R("floatBE",4).map(function(F){returnF.readFloatBE(0)}),floatLE:R("floatLE",4).map(function(F){returnF.readFloatLE(0)}),doubleBE:R("doubleBE",8).map(function(F){returnF.readDoubleBE(0)}),doubleLE:R("doubleLE",8).map(function(F){returnF.readDoubleLE(0)})},G.exports=c}])})})(Oa,Oa.exports);varQ=Oa.exports,AX=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u
${I}`:""}`;function Ha(b){if(b){let I=new _0.Notice(P0("starting",""),1e6);return{setMessage:(G,l)=>{I.setMessage(P0(G,l))},hide:()=>I.hide()}}return{setMessage:(I,G)=>{B.logMessage(`(${I}) ${G}`)},hide:()=>{}}}var el=(b,I)=>{let G=I.name==="gpt-3.5-turbo-16k"?"gpt-3.5-turbo":I.name;G=G==="gpt-4-1106-preview"?"gpt-4":G,G=G==="gpt-3.5-turbo-1106"?"gpt-3.5-turbo":G;try{return S0(G).encode(b).length}catch{return KF("cl100k_base").encode(b).length}};async function l5(b,I,G){if(typeof b!="function")throw new TypeError("Callbackmustbeafunction.");if(!(I instanceof Promise))throw new TypeError("PromisemustbeaninstanceofPromise.");if(typeof G!="number"||G<=0)throw new TypeError("Intervalmustbeapositivenumber.");let l=!1;for(I.finally(()=>{l=!0});!l;)b(),await sleep(G)}async function b5(b,I,G){let l;if(I.enable)l=G.find(d=>d.path.endsWith(I.name));else{let d=G.map(m=>m.basename);l=await jG.Suggest(b,d,G)}tl(l,"Prompttemplatedoesnotexist");let Z=l.path,c=b.vault.getAbstractFileByPath(Z);tl(c instanceof $0.TFile,`${Z} is not a file`);let W=await b.vault.cachedRead(c);return[l.basename,W]}async function Iu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ha(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,promptTemplate:d,systemPrompt:m,promptTemplateFolder:N}=I,Y=EW(b,N),[V,a]=await b5(b,d,Y);l.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let h=await G(a),R=["prompting",`Using prompt template "${V}".`];l.setMessage(R[0],R[1]);let p=Qa(b,Z,c,m,I.modelOptions)(h),t=(await TF(p,100,v=>{l.setMessage(R[0],`${R[1]} (${(v/1e3).toFixed(2)}s)`)},v=>{l.setMessage("finished",`Took ${(v/1e3).toFixed(2)}s.`)})).content,s=(">"+t).replace(/\n/g,`
> `),X={[W]:t,[`${W}-quoted`]:s};return setTimeout(()=>l.hide(),5e3),X}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}async function TF(b,I,G,l){let Z=Date.now();return await l5(()=>G(Date.now()-Z),b,I),l(Date.now()-Z),await b}async function Gu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ha(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,prompt:m,modelOptions:N}=I;l.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let Y=await G(m),V=["prompting","Usingcustomprompt."];l.setMessage(V[0],V[1]);let h=Qa(b,Z,c,d,N)(Y),H=(await TF(h,100,t=>{l.setMessage(V[0],`${V[1]} (${(t/1e3).toFixed(2)}s)`)},t=>{l.setMessage("finished",`Took ${(t/1e3).toFixed(2)}s.`)})).content,p=(">"+H).replace(/\n/g,`
> `),n={[W]:H,[`${W}-quoted`]:p};return setTimeout(()=>l.hide(),5e3),n}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}var DF=class{constructor(I,G){this.maxRequests=I;this.intervalMs=G;this.queue=[];this.pendingPromises=[]}add(I){return new Promise((G,l)=>{this.queue.push(async()=>{try{G(await I())}catch(Z){l(Z)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let I=this.queue.shift();if(!I)return;let G=I();this.pendingPromises.push(G),G.finally(()=>{this.pendingPromises=this.pendingPromises.filter(l=>l!==G),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function lu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ha(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,promptTemplate:m,text:N,modelOptions:Y}=I;l.setMessage("chunking","Creatingpromptchunkswithtextandprompttemplate");let V=I.chunkSeparator||/\n/g,a=N.split(V),h=el(d,c),R=await G(m,{chunk:""}),H=el(R,c),p=f0(c.name)/2-h,n=I.shouldMerge??!0,t=[],s=p-H;if(n){let i=[],A="",j=0;for(let k of a){let T=el(k,c)+1;if(T>s)throw new Error(`The chunk "${k.slice(0,25)}..." is too large to fit in a single prompt.`);j+T<s?(A+=k,j+=T):(i.push(A),A=k,j=T)}A!==""&&i.push(A);for(let k of i){let T=await G(m,{chunk:k});t.push(T)}}else for(let i of a){let A=el(i,c);if(A>p)throw new Error(`Chunk size (${A}) is larger than the maximum chunk size (${p}). Please check your chunk separator.`);let j=await G(m,{chunk:i});t.push(j)}let X=Qa(b,Z,c,d,Y),v=["prompting",`${t.length} prompts being sent.`];l.setMessage(v[0],v[1]);let z=new DF(5,1e3*30),w=Promise.all(t.map(i=>z.add(()=>X(i)))),_=(await TF(w,100,i=>{l.setMessage(v[0],`${v[1]} (${(i/1e3).toFixed(2)}s)`)},i=>{l.setMessage("finished",`Took ${(i/1e3).toFixed(2)}s.`)})).map(i=>i.content).join(I.resultJoiner),bI=(">"+_).replace(/\n/g,`
> `),C={[W]:_,[`${W}-quoted`]:bI};return setTimeout(()=>l.hide(),5e3),C}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}var na=class{static filterFiles(I,G,l){return Object.keys(G).length===0?I:I.filter(Z=>!(G.folder&&!this.matchesFolder(Z,G.folder)||G.tags&&G.tags.length>0&&!this.matchesTags(Z,G.tags,l)))}static matchesFolder(I,G){let l=this.normalizePath(G),Z=this.normalizePath(I.path);return Z.startsWith(l+"/")||Z.substring(0,Z.lastIndexOf("/"))===l}static matchesTags(I,G,l){let Z=l(I);if(!Z||!Z.tags)return!1;let c=Z.tags.map(W=>W.tag.startsWith("#")?W.tag.substring(1):W.tag);return G.every(W=>c.includes(W))}static normalizePath(I){return I.replace(/^\/+|\/+$/g,"")}};var cY=class cY{static parseInlineFields(I){let G=new Map,l=this.removeCodeBlocksAndFrontmatter(I),Z;for(;(Z=cY.INLINE_FIELD_REGEX.exec(l))!==null;){let c=Z[1].trim(),W=Z[2].trim();W&&(G.has(c)||G.set(c,new Set),W.includes(",")?W.split(",").map(m=>m.trim()).filter(m=>m.length>0).forEach(m=>G.get(c)?.add(m)):G.get(c)?.add(W))}return cY.INLINE_FIELD_REGEX.lastIndex=0,G}static removeCodeBlocksAndFrontmatter(I){let G=/^---\r?\n[\s\S]*?\r?\n---\r?\n/;I=I.replace(G,"");let l=/```[\s\S]*?```|`[^`]*`/g;return I=I.replace(l,""),I}static getFieldValues(I,G){return this.parseInlineFields(I).get(G)||new Set}};cY.INLINE_FIELD_REGEX=/(?:^|[\n\r])[ \t]*(?![-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu;var BW=cY;var $b=class b{constructor(){this.cache=new Map;this.TTL=5*60*1e3;this.MAX_CACHE_ENTRIES=100;this.MAX_VALUES_PER_ENTRY=1e3;this.cleanupInterval=null}static getInstance(){return b.instance||(b.instance=new b),b.instance}startAutomaticCleanup(I){if(this.cleanupInterval===null&&typeof window<"u"){let G=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=I(G)}}get(I,G){let l=this.makeKey(I,G),Z=this.cache.get(l);return Z?Date.now()-Z.timestamp>this.TTL?(this.cache.delete(l),null):new Set(Z.values):null}set(I,G,l){let Z=this.makeKey(I,l),c=new Set,W=0;for(let d of G){if(W>=this.MAX_VALUES_PER_ENTRY)break;c.add(d),W++}this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(Z)&&this.evictOldestEntries(1),this.cache.set(Z,{values:c,timestamp:Date.now()})}evictOldestEntries(I){let G=Array.from(this.cache.entries()).sort(([,l],[,Z])=>l.timestamp-Z.timestamp).slice(0,I);for(let[l]of G)this.cache.delete(l)}clear(I){if(I){let G=[];for(let l of this.cache.keys())(l.startsWith(`${I}:`)||l===I)&&G.push(l);for(let l of G)this.cache.delete(l)}else this.cache.clear()}cleanExpired(){let I=Date.now(),G=[];for(let[l,Z]of this.cache.entries())I-Z.timestamp>this.TTL&&G.push(l);for(let l of G)this.cache.delete(l)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.cache.clear()}makeKey(I,G){return G?`${I}:${G}`:I}};var OW=class{static GetApi(I,G,l){return{inputPrompt:(Z,c,W)=>this.inputPrompt(I,Z,c,W),wideInputPrompt:(Z,c,W)=>this.wideInputPrompt(I,Z,c,W),yesNoPrompt:(Z,c)=>this.yesNoPrompt(I,Z,c),infoDialog:(Z,c)=>this.infoDialog(I,Z,c),suggester:(Z,c,W,d=!1)=>this.suggester(I,Z,c,W,d),checkboxPrompt:(Z,c)=>this.checkboxPrompt(I,Z,c),executeChoice:async(Z,c)=>{let W=G.getChoiceByName(Z);W||jI(new Error(`Choice named '${Z}' not found`),"APIexecuteChoiceerror"),c&&Object.keys(c).forEach(d=>{l.variables.set(d,c[d])}),await l.execute(W),l.variables.clear()},format:async(Z,c,W=!0)=>{c&&Object.keys(c).forEach(m=>{l.variables.set(m,c[m])});let d=await new Wb(I,G,l).formatFileContent(Z);return W&&l.variables.clear(),d},ai:{prompt:async(Z,c,W)=>{let d=lI.getState(),m=d.ai;if(d.disableOnlineFeatures)throw new Error("Rejectingrequestto`prompt`viaAPIAImodule.Onlinefeaturesaredisabledinsettings.");let N=this.GetApi(I,G,l).format,Y;if(typeof c=="string"){let h=cb(c);if(!h)throw new Error(`Model '${c}' not found.`);Y=h}else Y=c;let V=sc(Y.name);if(!V)throw new Error(`Model '${Y.name}' not found in any provider`);let a=await Gu(I,{model:Y,prompt:Z,apiKey:V.apiKey,modelOptions:W?.modelOptions??{},outputVariableName:W?.variableName??"output",showAs
`,shouldMerge:d?.shouldMerge??!0},(H,p)=>{let n={...m,...p};return V(H,n,!1)});return R?(d?.shouldAssignVariables&&Object.assign(l.variables,R),R):(jI(new Error("AIAssistantreturnednull"),"ChunkedAIPrompterror"),{})},getModels:()=>Jb(),getMaxTokens:Z=>{let c=cb(Z);if(!c)throw new Error(`Model ${Z} not found.`);return c.maxTokens},countTokens(Z,c){return el(Z,c)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async Z=>await navigator.clipboard.writeText(Z),getSelectedText:()=>{let Z=I.workspace.getActiveViewOfType(bu.MarkdownView);if(!Z){jI(new Error("Noactiveview"),"Couldnotgetselectedtext");return}if(!Z.editor.somethingSelected()){jI(new Error("Notextselected"),"Couldnotgetselectedtext");return}return Z.editor.getSelection()}},date:{now:(Z,c)=>Db({format:Z,offset:c}),tomorrow:Z=>Db({format:Z,offset:1}),yesterday:Z=>Db({format:Z,offset:-1})},fieldSuggestions:{getFieldValues:async(Z,c)=>{let W={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1},d=I.vault.getMarkdownFiles();d=na.filterFiles(d,W,N=>I.metadataCache.getFileCache(N));let m=new Set;for(let N of d){let V=I.metadataCache.getFileCache(N)?.frontmatter?.[Z];if(V!=null){if(Array.isArray(V))V.forEach(a=>{let h=a.toString().trim();h&&m.add(h)});else if(typeof V!="object"){let a=V.toString().trim();a&&m.add(a)}}if(W.inline){let a=await I.vault.read(N);BW.getFieldValues(a,Z).forEach(R=>m.add(R))}}return Array.from(m).sort()},clearCache:Z=>{$b.getInstance().clear(Z)}}}}static async inputPrompt(I,G,l,Z){try{return await $I.Prompt(I,G,l,Z)}catch{return}}static async wideInputPrompt(I,G,l,Z){try{return await ec.Prompt(I,G,l,Z)}catch{return}}static async yesNoPrompt(I,G,l){try{return await Bl.Prompt(I,G,l)}catch{return}}static async infoDialog(I,G,l){try{return await bY.Show(I,G,l)}catch{return}}static async suggester(I,G,l,Z,c=!1){try{let W;return typeof G=="function"?W=l.map(G):W=G,c?await Ol.Suggest(I,W,l,Z?{placeholder:Z}:{}):await jG.Suggest(I,W,l,Z)}catch{return}}static async checkboxPrompt(I,G,l){try{return await ZY.Open(I,G,l)}catch{return}}};var MW=class extends yW{};var rG=[];for(let b=0;b<256;++b)rG.push((b+256).toString(16).slice(1));function Zu(b,I=0){return(rG[b[I+0]]+rG[b[I+1]]+rG[b[I+2]]+rG[b[I+3]]+"-"+rG[b[I+4]]+rG[b[I+5]]+"-"+rG[b[I+6]]+rG[b[I+7]]+"-"+rG[b[I+8]]+rG[b[I+9]]+"-"+rG[b[I+10]]+rG[b[I+11]]+rG[b[I+12]]+rG[b[I+13]]+rG[b[I+14]]+rG[b[I+15]]).toLowerCase()}var SF,Z5=new Uint8Array(16);function qF(){if(!SF){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues()notsupported.Seehttps://github.com/uuidjs/uuid#getrandomvalues-not-supported");SF=crypto.getRandomValues.bind(crypto)}return SF(Z5)}var c5=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),fF={randomUUID:c5};function W5(b,I,G){if(fF.randomUUID&&!I&&!b)return fF.randomUUID();b=b||{};let l=b.random??b.rng?.()??qF();if(l.length<16)throw new Error("Random bytes length must be >= 16");if(l[6]=l[6]&15|64,l[8]=l[8]&63|128,I){if(G=G||0,G<0||G+16>I.length)throw new RangeError(`UUID byte range ${G}:${G+15} is out of buffer bounds`);for(let Z=0;Z<16;++Z)I[G+Z]=l[Z];return I}return Zu(l)}var jl=W5;var KG=class{constructor(I,G){this.name=I,this.type=G,this.id=jl()}};var cu=require("obsidian");var dG=class extends KG{constructor(I){super(I,"EditorCommand"),this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){let G=I.workspace.getActiveViewOfType(cu.MarkdownView);if(!G)throw B.logError("no active markdown view."),new Error("no active markdown view.");return G}};var jW=class extends dG{constructor(){super("Cut")}static async run(I){let G=dG.getSelectedText(I),l=dG.getActiveMarkdownView(I);if(!G){B.logError("nothing selected.");return}await navigator.clipboard.writeText(G),l.editor.replaceSelection("")}};var KW=class extends dG{constructor(){super("Copy")}static async run(I){let G=dG.getSelectedText(I);await navigator.clipboard.writeText(G)}};var DW=class extends dG{constructor(){super("Paste")}static async run
`)}var mu=require("obsidian"),yb=class extends MW{constructor(I,G,l,Z,c){super(I),this.choice=l,this.plugin=G,this.macro=l?.macro,this.choiceExecutor=Z,this.params={app:this.app,quickAddApi:OW.GetApi(I,G,Z),variables:{},obsidian:d5},c?.forEach((W,d)=>{this.params.variables[d]=W})}async run(){if(!this.macro||!this.macro.commands){B.logError(`Nocommandsinthemacroforchoice'${this.choice.name}'`);return}await this.executeCommands(this.macro.commands)}getOutput(){return this.output}async executeCommands(I){for(let G of I)G?.type==="Obsidian"&&this.executeObsidianCommand(G),G?.type==="UserScript"&&await this.executeUserScript(G),G?.type==="Choice"&&await this.executeChoice(G),G?.type==="Wait"&&await du(G.time),G?.type==="NestedChoice"&&await this.executeNestedChoice(G),G?.type==="EditorCommand"&&await this.executeEditorCommand(G),G?.type==="AIAssistant"&&await this.executeAIAssistant(G),G?.type==="OpenFile"&&await this.executeOpenFile(G),Object.keys(this.params.variables).forEach(l=>{this.choiceExecutor.variables.set(l,this.params.variables[l])})}async executeUserScript(I){let G=await SV(I,this.app);if(!G){B.logError(`failedtoloaduserscript${I.path}.`);return}G.settings&&(this.userScriptCommand=I);try{await this.userScriptDelegator(G)}catch(l){jI(l,`Failedtorunuserscript${I.name}`)}this.userScriptCommand&&(this.userScriptCommand=null)}async runScriptWithSettings(I,G){if(typeof I!="function"&&I.entry&&typeof I.entry=="function")return await this.onExportIsFunction(I.entry,G.settings);if(typeof I=="function")return await this.onExportIsFunction(I,G.settings)}async userScriptDelegator(I){switch(typeof I){case"function":this.userScriptCommand?await this.runScriptWithSettings(I,this.userScriptCommand):await this.onExportIsFunction(I);break;case"object":await this.onExportIsObject(I);break;case"bigint":case"boolean":case"number":case"string":this.output=I.toString();break;default:B.logError(`userscriptinmacrofor'${this.choice.name}'isinvalid`)}}async onExportIsFunction(I,G){this.output=await I(this.params,G||{})}async onExportIsObject(I){if(Object.keys(I).length===0)throw new Error(`userscriptinmacrofor'${this.choice.name}'isanemptyobject`);if(this.userScriptCommand&&I.entry!==null){await this.runScriptWithSettings(I,this.userScriptCommand);return}try{let G=Object.keys(I),l=await jG.Suggest(this.app,G,G);await this.userScriptDelegator(I[l])}catch(G){jI(G,"Error in script object handling","LOG")}}executeObsidianCommand(I){this.app.commands.executeCommandById(I.commandId)}async executeChoice(I){let G=this.plugin.getChoiceById(I.choiceId);if(!G){B.logError("choice could not be found.");return}await this.choiceExecutor.execute(G)}async executeNestedChoice(I){let G=I.choice;if(!G){B.logError(`choicein${I.name}isinvalid`);return}await this.choiceExecutor.execute(G)}async executeEditorCommand(I){switch(I.editorCommandType){case"Cut":await jW.run(this.app);break;case"Copy":await KW.run(this.app);break;case"Paste":await DW.run(this.app);break;case"Paste with format":await TW.run(this.app);break;case"Select active line":SW.run(this.app);break;case"Select link on active line":qW.run(this.app);break}}async executeAIAssistant(I){if(lI.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=lI.getState().ai,l=Jb(),Z=I.model==="Ask me"?await jG.Suggest(this.app,l,l):I.model,c=cb(Z);if(!c)throw new Error(`Model${Z}notfoundwithanyprovider.`);let W=new Wb(this.app,zI.instance,this.choiceExecutor),d=sc(c.name);if(!d)throw new Error(`Model${c.name}notfoundintheAIproviderssettings.`);let m=await Iu(this.app,{apiKey:d.apiKey,model:c,outputVariableName:I.outputVariableName,promptTemplate:I.promptTemplate,promptTemplateFolder:G.promptTemplatesFolderPath,systemPrompt:I.systemPrompt,showAssistantMessages:G.showAssistant,modelOptions:I.modelParameters},async N=>W.formatFileContent(N));for(let N in m)this.choiceExecutor.variables.set(N,m[N])}async executeOpenFile(I){try{let Z=(await new Wb(this.app,zI.instance,this.choiceExecutor).formatF
Suggestedvaluesfor${l}:${V.slice(0,3).join(", ")}`)}return await $I.Prompt(this.app,`Entervaluefor${l}`,Y)}let N=`Entervaluefor${l}`;return m.hasDefaultValue&&(N=`Entervaluefor${l}(default:${Z.defaultValue})`),await Ol.Suggest(this.app,m.values,m.values,{placeholder:N})}generateCacheKey(G){let l=[];return G.folder&&l.push(`folder:${G.folder}`),G.tags&&l.push(`tags:${G.tags.join(",")}`),G.inline&&l.push("inline:true"),G.caseSensitive&&l.push("case-sensitive:true"),G.excludeFolders&&l.push(`exclude-folders:${G.excludeFolders.join(",")}`),G.excludeTags&&l.push(`exclude-tags:${G.excludeTags.join(",")}`),G.excludeFiles&&l.push(`exclude-files:${G.excludeFiles.join(",")}`),G.defaultValue&&l.push(`default:${G.defaultValue}`),G.defaultEmpty&&l.push("default-empty:true"),G.defaultAlways&&l.push("default-always:true"),l.join("|")}async getMacroValue(G){let l=new ua(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),Z=await l.runAndGetOutput(G)??"";return l.getVariables().forEach((c,W)=>{this.variables.set(W,c)}),Z}async getTemplateContent(G){return await new sZ(this.app,this.plugin,G,this.choiceExecutor).run()}async getSelectedText(){let G=this.app.workspace.getActiveViewOfType(jt.MarkdownView);return G?G.editor.getSelection():""}async getClipboardContent(){try{return await navigator.clipboard.readText()}catch{return""}}async replaceInlineJavascriptInString(G){let l=G;for(;Ld.test(l);){let c=Ld.exec(l)?.at(1)?.trim();if(c){let W=new ta(this.app,this.plugin,this.choiceExecutor,this.variables),d=await W.runAndGetOutput(c);for(let m in W.params.variables)this.variables.set(m,W.params.variables[m]);l=typeof d=="string"?this.replacer(l,Ld,d):this.replacer(l,Ld,"")}}return l}async collectValuesManually(G,l){let Z=new Set,c=this.app.vault.getMarkdownFiles();c=qa.filterFiles(c,l,d=>this.app.metadataCache.getFileCache(d));let W=50;for(let d=0;d<c.length;d+=W){let N=c.slice(d,d+W).map(async V=>{let a=new Set;try{let R=this.app.metadataCache.getFileCache(V)?.frontmatter?.[G];if(R!=null){if(Array.isArray(R))R.forEach(H=>{let p=String(H).trim();p&&a.add(p)});else if(typeof R!="object"){let H=String(R).trim();H&&a.add(H)}}if(l.inline)try{let H=await this.app.vault.read(V);BW.getFieldValues(H,G).forEach(n=>a.add(n))}catch(H){B.logWarning(`Couldnotreadfile${V.path}forinlinefieldparsing:${H}`)}}catch(h){B.logWarning(`Couldnotprocessmetadataforfile${V.path}:${h}`)}return a}),Y=await Promise.all(N);for(let V of Y)for(let a of V)Z.add(a)}return Z}};var Kt=require("obsidian");var Nd=class extends yW{constructor(G,l,Z){super(G);this.plugin=l;this.templater=jV(G),this.formatter=new Wb(G,l,Z)}async getOrCreateFolder(G){let l;if(G.length>1){if(l=await jG.Suggest(this.app,G,G),!l)throw new Error("No folder selected.")}else l=G[0];return l?await this.createFolder(l):l="",l}async getFormattedFilePath(G,l,Z){let c=await this.formatter.formatFileName(l,Z);return this.normalizeMarkdownFilePath(G,c)}getTemplateExtension(G){return id.test(G)?".canvas":".md"}normalizeTemplateFilePath(G,l,Z){let c=G?`${G}/`:"",W=this.getTemplateExtension(Z),d=l.replace(Ad,"").replace(id,"");return`${c}${d}${W}`}async incrementFileName(G){let l=lV.exec(G),Z=l&&typeof l.at=="function"?l?.at(1):void 0,c=await this.app.vault.adapter.exists(G),W=G,d=id.test(G)?".canvas":".md";if(c&&Z){let N=parseInt(Z);if(!N)throw new Error("detected numbers but couldn't get them.");W=W.replace(lV,`${N+1}${d}`)}else c&&(W=W.replace(lV,`1${d}`));return await this.app.vault.adapter.exists(W)&&(W=await this.incrementFileName(W)),W}async createFileWithTemplate(G,l){try{let Z=await this.getTemplateContent(l),c=G.split("/").pop()?.replace(/\.md$/,"")||"";this.formatter.setTitle(c);let W=await this.formatter.formatFileContent(Z),d=await this.createFileWithInput(G,W);return await hc(this.app,d),d}catch(Z){return jI(Z,"Could not create file with template"),null}}async overwriteFileWithTemplate(G,l){try{let Z=await this.getTemplateContent(l),c=G.basename;this.formatter.setTitle(c);let W=await this.formatter.formatFileContent(Z);return await this.ap
${m}`:`${m}
${d}`;returnawaitthis.app.vault.modify(G,N),awaithc(this.app,G),G}catch(c){returnjI(c,"Could not append to file with template"),null}}asyncgetTemplateContent(G){letl=G;!Ad.test(G)&&!id.test(G)&&(l+=".md");letZ=this.app.vault.getAbstractFileByPath(l);if(!(ZinstanceofKt.TFile))thrownewError(`Template file not found at path "${l}".`);returnawaitthis.app.vault.cachedRead(Z)}};varsZ=classextendsNd{constructor(G,l,Z,c){super(G,l,c);this.templatePath=Z}asyncrun(){letG=awaitthis.getTemplateContent(this.templatePath);returnG||B.logError(`Template ${this.templatePath} not found.`),G=awaitthis.formatter.formatFileContent(G),G}};varEl=classextendsQZ{constructor(G,l,Z){super();this.app=G;this.plugin=l;this.dateParser=Z||Kb}asyncformat(G){letl=G;try{l=this.replaceDateInString(l),l=this.replaceTimeInString(l),l=awaitthis.replaceValueInString(l),l=awaitthis.replaceSelectedInString(l),l=awaitthis.replaceClipboardInString(l),l=awaitthis.replaceDateVariableInString(l),l=awaitthis.replaceVariableInString(l),l=awaitthis.replaceLinkToCurrentFileInString(l),l=awaitthis.replaceMacrosInString(l),l=awaitthis.replaceTemplateInString(l),l=awaitthis.replaceFieldVarInString(l),l=this.replaceRandomInString(l),l=this.replaceLinebreakInString(l)}catch{returnG}returnl}promptForValue(G){returnG||"user input"}getVariableValue(G){returnqV(G)}getCurrentFileLink(){return$V(this.app.workspace.getActiveFile())}suggestForValue(G){return_V(G)}getMacroValue(G){returnfV(G)}promptForMathValue(){returnPromise.resolve("calculation_result")}promptForVariable(G,l){returnPromise.resolve(PV(G))}asyncgetTemplateContent(G){try{returnawaitnewsZ(this.app,this.plugin,G,void0).run()}catch{return`Template (not found): ${G}`}}asyncgetSelectedText(){return"selected_text"}asyncgetClipboardContent(){return"clipboard_content"}asyncsuggestForField(G){returnPromise.resolve(`${G}_field_value`)}asyncreplaceDateVariableInString(G){letl=G;returnl=l.replace(newRegExp(MZ.source,"gi"),(Z,c,W,d)=>{letm=c?.trim(),N=W?.trim(),Y=d?.trim();if(!m||!N)returnZ;letV=newDate,a;try{a=wb.generate(N,V)}catch{a=`[${N} format]`}returnY&&(a+=` (default: ${Y})`),a}),l}replaceRandomInString(G){letl=G;returnl=l.replace(/{{RANDOM:(\d+)}}/gi,(Z,c)=>{letW=parseInt(c);if(W<=0||W>100)returnZ;letd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",m="";for(letN=0;N<Math.min(W,8);N++)m+=d.charAt(Math.floor(Math.random()*d.length));returnW>8&&(m+=`... (${W} chars)`),m}),l}};functionRg(b){returntypeofb=="object"&&b!==null&&"enabled"inb&&"placement"inb}functionvZ(b){returnRg(b)?b:{enabled:b,placement:"replaceSelection"}}varbl=classextendshl{constructor(G,l,Z,c=!1){super(G,l);this.app=G;this.inputEl=l;this.plugin=Z;this.suggestForFileNames=c;this.lastInput="";this.lastInputStart=0;this.tokenDefinitions=[{regex:ZQ,token:1,suggestion:"{{DATE:}}",cursorOffset:2},{regex:bQ,token:0,suggestion:N2},{regex:pQ,token:10,suggestion:Tp},{regex:cQ,token:4,suggestion:Y2},{regex:WQ,token:3,suggestion:OZ},{regex:aQ,token:9,suggestion:Sp},{regex:RQ,token:11,suggestion:Pp},{regex:FQ,token:12,suggestion:_p},{regex:XQ,token:13,suggestion:"{{RANDOM:}}",cursorOffset:2},{regex:dQ,token:5,suggestion:"{{VALUE:}}",cursorOffset:2},{regex:mQ,token:2,suggestion:"{{VDATE:}}",cursorOffset:2}];this.contextualTokens=[{regex:NQ,token:6,suggestion:qp},{regex:hQ,token:14,suggestion:fp},{regex:YQ,token:8,suggestion:"{{TEMPLATE:"},{regex:VQ,token:7,suggestion:"{{MACRO:"}];this.macroNames=Tb(this.plugin.settings.choices).filter(W=>W.type==="Macro").map(W=>W.name),this.templatePaths=this.plugin.getTemplateFiles().map(W=>W.path)}asyncgetSuggestions(G){if(this.inputEl.selectionStart===null)return[];letl=this.inputEl.selectionStart,Z=G.lastIndexOf("{{",l-1);if(Z===-1)return[];letc=G.slice(Z,l);if(c.includes("}}"))return[];if(c.includes(":"))return[];letW=[],d=[...this.tokenDefinitions,...this.suggestForFileNames?[]:this.contextualTokens];for(letmofd){letN=m.regex.exec(c);N&&N.index+N[0].length===c.length&&(this.lastInput=N[0],this.lastInputType=m.token,this.lastIn
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function yg(){throw new TypeError(`Invalidattempttodestructurenon-iterableinstance.
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function yY(b,I){var G=typeof Symbol<"u"&&b[Symbol.iterator]||b["@@iterator"];if(!G){if(Array.isArray(b)||(G=DX(b))||I&&b&&typeof b.length=="number"){G&&(b=G);var l=0,Z=function(){};return{s:Z,n:function(){return l>=b.length?{done:!0}:{done:!1,value:b[l++]}},e:function(m){throw m},f:Z}}throw new TypeError(`Invalidattempttoiteratenon-iterableinstance.
${G?"Deleting this choice will delete all ("+b.choices.length+") choices inside it!":""}
${l?"Deleting this choice will delete its macro commands!":""}
`)}asyncfunctionre(b,I,G){if(b.type==="Multi"){letZ=await$I.Prompt(I,`Rename ${b.name}`,"",b.name);returnZ?{...b,name:Z}:void0}letl=ZA(b,I,G);if(!l)thrownewError("Invalid choice type");returnawaitl.waitForClose}functionze(b){return{...b,command:!b.command}}varEh=class{constructor(I){this.plugin=I}enableCommand(I){this.plugin.addCommandForChoice(I)}disableCommand(I){this.plugin.removeCommandForChoice(I)}updateCommand(I,G){this.plugin.removeCommandForChoice(I),this.plugin.addCommandForChoice(G)}};varrb=require("obsidian");varnG=require("obsidian");varxe=require("obsidian");varJh=null,cA=24*60*60*1e3;asyncfunctionkY(){if(Jh&&Date.now()-Jh.fetchedAt<cA)returnJh.data;if(lI.getState().disableOnlineFeatures)thrownewError("Fetching models directory is disabled: Online features are turned off.");letI=await(await(0,xe.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;returnJh={data:I,fetchedAt:Date.now()},I}functionWA(b){letI=b.toLowerCase();returnI.includes("openai.com")?"openai":I.includes("openrouter.ai")?"openrouter":I.includes("generativelanguage.googleapis.com")?"google":I.includes("anthropic.com")||I.includes("anthropic")?"anthropic":I.includes("groq.com")?"groq":I.includes("together.ai")?"togetherai":I.includes("huggingface.co")||I.includes("huggingface")?"huggingface":I.includes("github")&&I.includes("models")?"github-models":I.includes("bedrock")||I.includes("aws")?"amazon-bedrock":I.includes("modelscope")?"modelscope":I.includes("dashscope")?"alibaba":I.includes("fireworks.ai")?"fireworks-ai":I.includes("vercel")?"vercel":I.includes("inference.net")?"inference":I.includes("z.ai")||I.includes("zhipu")?"zhipuai":I.includes("deepseek.com")?"deepseek":I.includes("cerebras")?"cerebras":I.includes("venice.ai")?"venice":I.includes("upstage.ai")?"upstage":I.includes("llama.com")||I.includes("api.llama.com")?"llama":I.includes("morphllm")?"morph":I.includes("inceptionlabs.ai")?"inception":I.includes("deepinfra")?"deepinfra":I.includes("gateway.opencode.ai")?"opencode":I.includes("router.huggingface.co")?"huggingface":I.includes("inference.wandb.ai")?"wandb":I.includes("api.githubcopilot.com")?"github-copilot":I.includes("api.openai.com")?"openai":null}asyncfunctionyh(b){letI=awaitkY(),G=WA(b.endpoint);if(!G||!(GinI))thrownewError(`Could not determine models.dev provider for endpoint: ${b.endpoint}`);letl=I[G];returnObject.values(l.models)}functionCh(b){returnb.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}functionmp(b,I){letG=newSet(b.map(Z=>Z.name)),l=I.filter(Z=>!G.has(Z.name));returnb.concat(l)}varkb=require("obsidian");vargh=classextendskb.Modal{constructor(G,l){super(G);this.allModels=[];this.filtered=[];this.selectedIds=newSet;this.mode="add";this.provider=l,this.waitForClose=newPromise((Z,c)=>{this.resolvePromise=Z,this.rejectPromise=c}),this.open(),this.loadData().then(()=>this.display())}asyncloadData(){try{awaitkY(),this.allModels=awaityh(this.provider),this.filtered=this.allModels.slice()}catch(G){newkb.Notice(`Failed to load model directory: ${G.message??G}`)}}display(){this.contentEl.empty(),this.modalEl.style.width="min(100vw - 32px, 980px)",this.modalEl.style.maxWidth="980px",this.contentEl.style.maxHeight="min(85vh, 800px)",this.contentEl.style.overflowY="auto",this.contentEl.createEl("h2",{text:`Browse models for ${this.provider.name}`}).style.textAlign="center",newkb.Setting(this.contentEl).setName("Search").addText(l=>{l.setPlaceholder("Filter by name or id").onChange(Z=>{letc=Z.trim().toLowerCase();this.filtered=this.allModels.filter(W=>W.id.toLowerCase().includes(c)||(W.name??"").toLowerCase().includes(c)),this.renderList()})}).addExtraButton(l=>{l.setIcon("check"),l.setTooltip("Select all"),l.onClick(()=>{this.filtered.forEach(Z=>this.selectedIds.add(Z.id)),this.renderList()})}).addExtraButton(l=>{l.setIcon("x"),l.setTooltip("Clear selection"),l.onClick(()=>{this.selectedIds.clear(),this.renderList()})}),newkb.Setting(this.contentEl).setName("Import mode").setDesc("Add will append new mod
`)}}).join(`
`)}}var Gw=b=>b.join(""),CA=b=>b.split(/\b/),gA=Iw("<<<<<<<YOURCHANGES","=======",">>>>>>>APPAUTHORSCHANGES",Gw),oA={splitFunction:CA,joinFunction:Gw,conflictFunction:gA};function tp(b,I,G,l={}){l=Object.assign({},oA,l);let[Z,c,W]=[b,I,G].map(N=>l.splitFunction.call(l,N)),d=UY.merge(Z,c,W);return BY.collateMerge(d,l.joinFunction,l.conflictFunction)}var lw=tp;var cw=require("obsidian");function bw(b,I){return b.line===I.line}function AA(b){let I=[];return b.forEach((G,l)=>{let Z=G.match(/^(#+)[\s]+(.*)$/);Z&&I.push({level:Z[1].length,text:Z[2],line:l})}),I}function Dh(b,I,G=!1){let l=AA(b),Z=l.find(N=>N.line===I),c=!!Z;if(!c&&G)throw new Error(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!c&&!G){let N=Zw(b,I,Y=>Y.trim()==="");return N!==null&&N>I?N-1:I}let W=b.length-1,d=iA(Z,l,b,G),m=rA(b,d,N=>N.trim()!=="");if(m!==null){if(m<I)return I;let N=b[m+1].trim()==="";return m+1===W&&!N?d:m===0?m+1:m}return d}function iA(b,I,G,l){let Z=I.findIndex(Y=>bw(Y,b)),c=Z===I.length-1,W=G.length-1;if(c)return W;let[d,m]=LA(b,I);if(m&&d===I.length)return W;if(m&&l)return I[d].line-1;if(m&&!l)return I[Z+1].line;if(!l&&!m){let Y=kA(b.line,I);return Y===null?W:Y}return W}function LA(b,I){let G=I.findIndex(Z=>bw(Z,b)),l=Zw(I,G,Z=>Z.level<=b.level);return l===null?[-1,!1]:[l,!0]}function kA(b,I){let G=I.findIndex(l=>l.line>b);return G===-1?null:G}function rA(b,I,G){for(let l=I-1;l>=0;l--)if(G(b[l]))return l;return null}function Zw(b,I,G){for(let l=I+1;l<b.length;l++)if(G(b[l]))return l;return null}var Th=class extends Wb{constructor(){super(...arguments);this.file=null;this.fileContent="";this.templaterProcessed=!1}async formatContentWithFile(G,l,Z,c){if(this.choice=l,this.file=c,this.fileContent=Z,!l||!c||Z===null)return G;let W=l.insertAfter.enabled||l.prepend||!l.captureToActiveFile;return await this.formatFileContent(G,W)}async formatContent(G,l){return this.choice=l,l?await this.formatFileContent(G):G}async formatFileContent(G,l=!0){let Z=await super.formatFileContent(G);if(Z=this.replaceLinebreakInString(Z),l&&this.file&&!this.templaterProcessed){let d=await KV(this.app,Z,this.file);d&&(Z=d),this.templaterProcessed=!0}if(Z.trim()==="")return this.fileContent;if(this.choice.prepend){let d=!this.choice.task;return`${this.fileContent}${d?`
${Z}`;if(this.choice.insertAfter?.createIfNotFoundLocation===ZV)try{let c=this.app.workspace.getActiveViewOfType(cw.MarkdownView);if(!c)throw new Error("Noactiveview.");let d=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Triedtogetsectionswithoutfile.");let N=PF(this.fileContent);d=Dh(N,d,!!this.choice.insertAfter.considerSubsections)??N.length-1}return this.insertTextAfterPositionInBody(Z,this.fileContent,d)}catch(c){jI(c,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}}getFrontmatterEndPosition(G){let l=this.app.metadataCache.getFileCache(G);return!l||!l.frontmatter?(B.logMessage("couldnotgetfrontmatter.Maybethereisn't any."),-1):l.frontmatterPosition?l.frontmatterPosition.end.line:-1}insertTextAfterPositionInBody(G,l,Z){if(Z===-1){let m=!this.choice.task;return`${G}${m?`
${G}${d}`}};function Ww(b){return b.captureToActiveFile&&!b.prepend&&!b.insertAfter.enabled?"currentLine":b.insertAfter.enabled?"insertAfter":b.prepend?"prepend":"append"}var dw=4e3,Sh=class extends MW{constructor(G,l,Z,c){super(G);this.choiceExecutor=c;this.choice=Z,this.plugin=l,this.formatter=new Th(G,l,c)}showSuccessNotice(G,{wasNewFile:l,action:Z}){let c=`'${G.basename}'`;if(l){new ep.Notice(`Created and captured to ${c}`,dw);return}let W="";switch(Z){case"currentLine":W=`Captured to current line in ${c}`;break;case"prepend":W=`Captured to top of ${c}`;break;case"append":W=`Captured to ${c}`;break;case"insertAfter":{let d=this.choice.insertAfter.after;W=d?`Captured to ${c} under '${d}'`:`Captured to ${c}`;break}}new ep.Notice(W,dw)}async run(){try{let G=await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile),l=this.getCaptureContent(),Z,c=await this.fileExists(G);if(c)Z=this.onFileExists.bind(this);else if(this.choice?.createFileIfItDoesntExist?.enabled)Z=this.onCreateFileIfItDoesntExist.bind(this);else{B.logWarning(`The file ${G} does not exist and "Create file if it doesn'texist" is disabled.`);return}let{file:W,newFileContent:d,captureContent:m}=await Z(G,l);if(this.choice.captureToActiveFile&&!this.choice.prepend&&!this.choice.insertAfter.enabled){let Y=await KV(this.app,m,W);G0(Y,this.app)}else await this.app.vault.modify(W,d),await hc(this.app,W);if(this.plugin.settings.showCaptureNotification){let Y=Ww(this.choice);this.showSuccessNotice(W,{wasNewFile:!c,action:Y})}let N=vZ(this.choice.appendLink);N.enabled&&DV(this.app,this.app.fileManager.generateMarkdownLink(W,""),N.placement),this.choice.openFile&&W&&(TV(this.app,W)||await vW(this.app,W,this.choice.fileOpening))}catch(G){jI(G,`Error running capture choice "${this.choice.name}"`)}}getCaptureContent(){let G;return this.choice.format.enabled?G=this.choice.format.format:G=OZ,this.choice.task&&(G=`- [ ] ${G}
`),G}async getFormattedPathToCaptureTo(G){if(G){let N=this.app.workspace.getActiveFile();return tl(N,"Cannotcapturetoactivefile-noactivefile."),N.path}let l=this.choice.captureTo,Z=await this.formatFilePath(l),c=Z.replace(/^\/$|\/\.md$|^\.md$/,""),W=c==="",d=W||Z0(this.app,c),m=Z.startsWith("#");if(d)return this.selectFileInFolder(c,W);if(m){let N=Z.replace(/\.md$/,"");return this.selectFileWithTag(N)}return Z}async selectFileInFolder(G,l){let Z=G.endsWith("/")||l?G:`${G}/`,c=EW(this.app,Z);tl(c.length>0,`Folder ${Z} is empty.`);let W=c.map(N=>N.path),d=await Ol.Suggest(this.app,W.map(N=>N.replace(Z,"")),W);tl(!!d&&d.length>0,"Nofileselectedforcapture.");let m=d.startsWith(`${Z}`)?d:`${Z}/${d}`;return await this.formatFilePath(m)}async selectFileWithTag(G){let l=G.startsWith("#")?G:`#${G}`,Z=c0(this.app,l);tl(Z.length>0,`No files with tag ${G}.`);let c=Z.map(d=>d.path),W=await Ol.Suggest(this.app,c,c);return tl(!!W&&W.length>0,"Nofileselectedforcapture."),await this.formatFilePath(W)}async onFileExists(G,l){let Z=this.getFileByPath(G);if(!Z)throw new Error("Filenotfound");this.formatter.setTitle(Z.basename);let c=await this.formatter.formatContentOnly(l),W=await this.app.vault.read(Z),d=await this.formatter.formatContentWithFile(c,this.choice,W,Z),m=await this.app.vault.read(Z),N=d;if(m!==W){let Y=lw(m,W,d);tl(!Y.isSuccess,()=>`The file ${G} has been modified since the last read.
QuickAdd will now revert to backup.`),b.settings=l}}b.saveSettings()}var pw=qA;var Jd=require("obsidian");async function fA(b,I,G){let l=await fetch(`https://api.github.com/repos/${b}/${I}/releases`),Z=await l.json();if(!l.ok&&"message"in Z||!Array.isArray(Z))throw new Error(`Failed to fetch releases: ${Z.message??"Unknown error"}`);let c=Z.findIndex(W=>W.tag_name===G);if(c===-1)throw new Error(`Could not find release with tag ${G}`);return Z.slice(0,c).filter(W=>!W.draft&&!W.prerelease)}function PA(b,I=1){let G=b.split(`
`)}var _h=class extends Jd.Modal{constructor(I,G){super(I),this.previousVersion=G,this.releaseNotesPromise=fA("chhoumann","quickadd",G),this.releaseNotesPromise.then(l=>{if(this.releases=l,this.releases.length===0){this.close();return}this.display()}).catch(l=>{B.logError(`Failed to fetch release notes: ${l}`)})}onOpen(){let{contentEl:I}=this;I.empty(),I.createEl("h1",{text:"Fetching release notes..."})}onClose(){let{contentEl:I}=this;I.empty()}display(){let{contentEl:I}=this;I.empty(),I.classList.add("quickadd-update-modal-container");let G=`### New in QuickAdd v${this.releases[0].tag_name}
`,l="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'llbeabletocontributemoretomyexistingprojects,startnewones,andbemoreresponsivetoissues&featurerequests.",Z='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 144px !important;" ></a></div>',c=I.createDiv("quickadd-update-modal"),W=this.releases.map(Y=>Y.body).join(`
${PA(W)}`;Jd.MarkdownRenderer.renderMarkdown(N,c,this.app.vault.getRoot().path,new Jd.Component)}};var tG=require("obsidian");var $h=class extends tG.Modal{constructor(G,l){super(G);this.showAdvancedSettings=!1;this.settings=l,this.waitForClose=new Promise((Z,c)=>{this.rejectPromise=c,this.resolvePromise=Z}),this.open(),this.display()}get systemPromptTokenLength(){let G=cb(this.settings.model);return G?el(this.settings.systemPrompt,G):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let G=this.contentEl.createEl("h2",{text:`${this.settings.name}Settings`});G.style.textAlign="center",G.style.cursor="pointer",G.style.userSelect="none",G.addEventListener("click",async()=>{try{let l=await $I.Prompt(this.app,"New name",this.settings.name,this.settings.name);l&&l!==this.settings.name&&(this.settings.name=l,this.reload())}catch{}}),this.addResultJoinerSetting(this.contentEl),this.addChunkSeparatorSetting(this.contentEl),this.addMaxTokensSetting(this.contentEl),this.addMergeChunksSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),this.addTemperatureSetting(this.contentEl),this.addTopPSetting(this.contentEl),this.addFrequencyPenaltySetting(this.contentEl),this.addPresencePenaltySetting(this.contentEl)),this.addSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addModelSetting(G){new tG.Setting(G).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(l=>{let Z=Jb();for(let c of Z)l.addOption(c,c);l.addOption("Ask me","Ask me"),l.setValue(this.settings.model),l.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(G){new tG.Setting(G).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(l=>{l.setValue(this.settings.outputVariableName).onChange(Z=>{this.settings.outputVariableName=Z})})}addSystemPromptSetting(G){new tG.Setting(G).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let l=this.contentEl.createEl("div"),Z=l.createEl("span");Z.style.color="var(--text-muted-color)",l.appendChild(Z);let c=new tG.TextAreaComponent(G);c.setValue(this.settings.systemPrompt).onChange(async N=>{this.settings.systemPrompt=N,d.innerText=await W.format(N),m()}),new bl(this.app,c.inputEl,zI.instance);let W=new El(this.app,zI.instance);c.inputEl.style.width="100%",c.inputEl.style.height="100px",c.inputEl.style.minHeight="100px",c.inputEl.style.marginBottom="1em";let d=this.contentEl.createEl("span"),m=(0,tG.debounce)(()=>{Z.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);m(),(async()=>d.innerText=await W.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(G){new tG.Setting(G).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(l=>{l.setValue(this.showAdvancedSettings),l.onChange(Z=>{this.showAdvancedSettings=Z,this.reload()})})}addTemperatureSetting(G){new tG.Setting(G).setName("Temperature").setDesc("Sampling temperature. Higher values like 0.8 makes the output more random, whereas lower values like 0.2 will make it more focused and deterministic. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.temperature??1),l.onChange(Z=>{this.settings.modelParameters.temperature=Z})})}addTopPSetting(G){new tG.Setting(G).setName("Top P").setDesc("Nucleus sampling - consider this an alternative to temperature. The model considers the results of the tokens with top_p probability mass. 0.1 means only tokens compromising the top 10% probability mass are considered. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.top_p??1),l.onChange(Z=>{this.settings.modelParameters.top_p=Z})})}addFrequencyPenaltySetting(G){new tG.Setting(