diff --git a/silverbullet-ai.plug.js b/silverbullet-ai.plug.js index b8dfee1..c690e68 100644 --- a/silverbullet-ai.plug.js +++ b/silverbullet-ai.plug.js @@ -1,38 +1,38 @@ -var Pn=Object.defineProperty;var U=(e,t)=>{for(var r in t)Pn(e,r,{get:t[r],enumerable:!0})};var ot=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var nt=new Map,rt=0;function Te(e){self.postMessage(e)}ot&&(globalThis.syscall=async(e,...t)=>await new Promise((r,n)=>{rt++,nt.set(rt,{resolve:r,reject:n}),Te({type:"sys",id:rt,name:e,args:t})}));function rr(e,t){ot&&(self.addEventListener("message",r=>{(async()=>{let n=r.data;switch(n.type){case"inv":{let o=e[n.name];if(!o)throw new Error(`Function not loaded: ${n.name}`);try{let i=await Promise.resolve(o(...n.args||[]));Te({type:"invr",id:n.id,result:i})}catch(i){console.error("An exception was thrown as a result of invoking function",n.name,"error:",i.message),Te({type:"invr",id:n.id,error:i.message})}}break;case"sysr":{let o=n.id,i=nt.get(o);if(!i)throw Error("Invalid request id");nt.delete(o),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}break}})().catch(console.error)}),Te({type:"manifest",manifest:t}))}function An(e){let t=atob(e),r=t.length,n=new Uint8Array(r);for(let o=0;o0?nr(r):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:n},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function vn(){globalThis.fetch=async function(e,t){let r=t&&t.body?nr(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,n=await Sn(e,t&&{method:t.method,headers:t.headers,base64Body:r});return new Response(n.base64Body?An(n.base64Body):null,{status:n.status,headers:n.headers})}}ot&&vn();function it(e){if(e.children)for(let t of e.children){if(t.parent)return;t.parent=e,it(t)}}function En(e,t){return st(e,r=>r.type===t)}function st(e,t){if(t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...st(n,t)];return r}async function or(e,t){if(await t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...await or(n,t)];return r}async function at(e,t){if(e.children){let r=e.children.slice();for(let n of r){let o=await t(n);if(o!==void 0){let i=e.children.indexOf(n);o?e.children.splice(i,1,o):e.children.splice(i,1)}else await at(n,t)}}}function ct(e,t){return st(e,r=>r.type===t)[0]}async function Ce(e,t){await or(e,t)}function R(e){if(!e)return"";let t=[];if(e.text!==void 0)return e.text;for(let r of e.children)t.push(R(r));return t.join("")}function lt(e,t=!0){if(En(e,"\u26A0").length>0)throw new Error(`Parse error in: ${R(e)}`);if(e.text!==void 0)return e.text;let n=[e.type];for(let o of e.children)o.type&&!o.type.endsWith("Mark")&&n.push(lt(o,t)),o.text&&(t&&o.text.trim()||!t)&&n.push(o.text);return n}function Tn(e){return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0?e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0"):e.toISOString()}function ce(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(ce);if(e instanceof Date)return Tn(e);let t={};for(let r of Object.keys(e)){let n=r.split("."),o=t;for(let i=0;ito,copyToClipboard:()=>mo,deleteLine:()=>fo,dispatch:()=>Zn,downloadFile:()=>Bn,filterBox:()=>Hn,flashNotification:()=>Gn,fold:()=>oo,foldAll:()=>ao,getCurrentPage:()=>Cn,getCursor:()=>On,getSelection:()=>kn,getText:()=>Mn,getUiOption:()=>ro,goHistory:()=>qn,hidePanel:()=>Wn,insertAtCursor:()=>Xn,insertAtPos:()=>Qn,moveCursor:()=>zn,moveCursorToLine:()=>Jn,navigate:()=>Rn,openCommandPalette:()=>$n,openPageNavigator:()=>Ln,openSearchPanel:()=>po,openUrl:()=>jn,prompt:()=>eo,redo:()=>uo,reloadConfigAndCommands:()=>Un,reloadPage:()=>_n,reloadUI:()=>Dn,replaceRange:()=>Vn,save:()=>Fn,setSelection:()=>Nn,setText:()=>In,setUiOption:()=>no,showPanel:()=>Yn,toggleFold:()=>so,undo:()=>lo,unfold:()=>io,unfoldAll:()=>co,uploadFile:()=>Kn,vimEx:()=>go});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function l(e,...t){return globalThis.syscall(e,...t)}function Cn(){return l("editor.getCurrentPage")}function Mn(){return l("editor.getText")}function In(e){return l("editor.setText",e)}function On(){return l("editor.getCursor")}function kn(){return l("editor.getSelection")}function Nn(e,t){return l("editor.setSelection",e,t)}function Fn(){return l("editor.save")}function Rn(e,t=!1,r=!1){return l("editor.navigate",e,t,r)}function Ln(e="page"){return l("editor.openPageNavigator",e)}function $n(){return l("editor.openCommandPalette")}function _n(){return l("editor.reloadPage")}function Dn(){return l("editor.reloadUI")}function Un(){return l("editor.reloadConfigAndCommands")}function jn(e,t=!1){return l("editor.openUrl",e,t)}function qn(e){return l("editor.goHistory",e)}function Bn(e,t){return l("editor.downloadFile",e,t)}function Kn(e,t){return l("editor.uploadFile",e,t)}function Gn(e,t="info"){return l("editor.flashNotification",e,t)}function Hn(e,t,r="",n=""){return l("editor.filterBox",e,t,r,n)}function Yn(e,t,r,n=""){return l("editor.showPanel",e,t,r,n)}function Wn(e){return l("editor.hidePanel",e)}function Qn(e,t){return l("editor.insertAtPos",e,t)}function Vn(e,t,r){return l("editor.replaceRange",e,t,r)}function zn(e,t=!1){return l("editor.moveCursor",e,t)}function Jn(e,t=1,r=!1){return l("editor.moveCursorToLine",e,t,r)}function Xn(e){return l("editor.insertAtCursor",e)}function Zn(e){return l("editor.dispatch",e)}function eo(e,t=""){return l("editor.prompt",e,t)}function to(e){return l("editor.confirm",e)}function ro(e){return l("editor.getUiOption",e)}function no(e,t){return l("editor.setUiOption",e,t)}function oo(){return l("editor.fold")}function io(){return l("editor.unfold")}function so(){return l("editor.toggleFold")}function ao(){return l("editor.foldAll")}function co(){return l("editor.unfoldAll")}function lo(){return l("editor.undo")}function uo(){return l("editor.redo")}function po(){return l("editor.openSearchPanel")}function mo(e){return l("editor.copyToClipboard",e)}function fo(){return l("editor.deleteLine")}function go(e){return l("editor.vimEx",e)}var N={};U(N,{parseMarkdown:()=>ho,renderParseTree:()=>yo});function ho(e){return l("markdown.parseMarkdown",e)}function yo(e){return l("markdown.renderParseTree",e)}var $={};U($,{deleteAttachment:()=>Mo,deleteFile:()=>Fo,deletePage:()=>Ao,fileExists:()=>Ro,getAttachmentMeta:()=>Eo,getFileMeta:()=>ko,getPageMeta:()=>bo,listAttachments:()=>vo,listFiles:()=>Io,listPages:()=>xo,listPlugs:()=>So,readAttachment:()=>To,readFile:()=>Oo,readPage:()=>wo,writeAttachment:()=>Co,writeFile:()=>No,writePage:()=>Po});function xo(){return l("space.listPages")}function bo(e){return l("space.getPageMeta",e)}function wo(e){return l("space.readPage",e)}function Po(e,t){return l("space.writePage",e,t)}function Ao(e){return l("space.deletePage",e)}function So(){return l("space.listPlugs")}function vo(){return l("space.listAttachments")}function Eo(e){return l("space.getAttachmentMeta",e)}function To(e){return l("space.readAttachment",e)}function Co(e,t){return l("space.writeAttachment",e,t)}function Mo(e){return l("space.deleteAttachment",e)}function Io(){return l("space.listFiles")}function Oo(e){return l("space.readFile",e)}function ko(e){return l("space.getFileMeta",e)}function No(e,t){return l("space.writeFile",e,t)}function Fo(e){return l("space.deleteFile",e)}function Ro(e){return l("space.fileExists",e)}var S={};U(S,{applyAttributeExtractors:()=>jo,getEnv:()=>Go,getMode:()=>Ho,getSpaceConfig:()=>qo,getVersion:()=>Yo,invokeCommand:()=>$o,invokeFunction:()=>Lo,invokeSpaceFunction:()=>Uo,listCommands:()=>_o,listSyscalls:()=>Do,reloadConfig:()=>Ko,reloadPlugs:()=>Bo});function Lo(e,...t){return l("system.invokeFunction",e,...t)}function $o(e,t){return l("system.invokeCommand",e,t)}function _o(){return l("system.listCommands")}function Do(){return l("system.listSyscalls")}function Uo(e,...t){return l("system.invokeSpaceFunction",e,...t)}function jo(e,t,r){return l("system.applyAttributeExtractors",e,t,r)}async function qo(e,t){return await l("system.getSpaceConfig",e)??t}function Bo(){return l("system.reloadPlugs")}function Ko(){return l("system.reloadConfig")}function Go(){return l("system.getEnv")}function Ho(){return l("system.getMode")}function Yo(){return l("system.getVersion")}var Q={};U(Q,{del:()=>Vo,get:()=>Qo,set:()=>Wo});function Wo(e,t){return l("clientStore.set",e,t)}function Qo(e){return l("clientStore.get",e)}function Vo(e){return l("clientStore.delete",e)}var Me={};U(Me,{listLanguages:()=>Zo,parseLanguage:()=>Xo});function Xo(e,t){return l("language.parseLanguage",e,t)}function Zo(){return l("language.listLanguages")}var ne={};U(ne,{parseTemplate:()=>ti,renderTemplate:()=>ei});function ei(e,t,r={}){return l("template.renderTemplate",e,t,r)}function ti(e){return l("template.parseTemplate",e)}var he={};U(he,{dispatchEvent:()=>oi,listEvents:()=>ii});function oi(e,t,r){return new Promise((n,o)=>{let i=-1;r&&(i=setTimeout(()=>{console.log("Timeout!"),o("timeout")},r)),l("event.dispatch",e,t).then(s=>{i!==-1&&clearTimeout(i),n(s)}).catch(o)})}function ii(){return l("event.list")}var B={};U(B,{parse:()=>ai,stringify:()=>ci});function ai(e){return l("yaml.parse",e)}function ci(e){return l("yaml.stringify",e)}var oe={};U(oe,{ack:()=>pi,batchAck:()=>mi,batchSend:()=>ui,getQueueStats:()=>di,send:()=>li});function li(e,t){return l("mq.send",e,t)}function ui(e,t){return l("mq.batchSend",e,t)}function pi(e,t){return l("mq.ack",e,t)}function mi(e,t){return l("mq.batchAck",e,t)}function di(e){return l("mq.getQueueStats",e)}async function V(e,t={}){let r={tags:[]},n=[];it(e),await at(e,async o=>{if(o.type==="Paragraph"&&o.parent?.type==="Document"){let i=!0,s=new Set;for(let c of o.children)if(c.text){if(c.text.startsWith(` +var Pn=Object.defineProperty;var U=(e,t)=>{for(var r in t)Pn(e,r,{get:t[r],enumerable:!0})};var ot=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var nt=new Map,rt=0;function Te(e){self.postMessage(e)}ot&&(globalThis.syscall=async(e,...t)=>await new Promise((r,n)=>{rt++,nt.set(rt,{resolve:r,reject:n}),Te({type:"sys",id:rt,name:e,args:t})}));function nr(e,t){ot&&(self.addEventListener("message",r=>{(async()=>{let n=r.data;switch(n.type){case"inv":{let o=e[n.name];if(!o)throw new Error(`Function not loaded: ${n.name}`);try{let i=await Promise.resolve(o(...n.args||[]));Te({type:"invr",id:n.id,result:i})}catch(i){console.error("An exception was thrown as a result of invoking function",n.name,"error:",i.message),Te({type:"invr",id:n.id,error:i.message})}}break;case"sysr":{let o=n.id,i=nt.get(o);if(!i)throw Error("Invalid request id");nt.delete(o),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}break}})().catch(console.error)}),Te({type:"manifest",manifest:t}))}function An(e){let t=atob(e),r=t.length,n=new Uint8Array(r);for(let o=0;o0?or(r):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:n},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function vn(){globalThis.fetch=async function(e,t){let r=t&&t.body?or(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,n=await Sn(e,t&&{method:t.method,headers:t.headers,base64Body:r});return new Response(n.base64Body?An(n.base64Body):null,{status:n.status,headers:n.headers})}}ot&&vn();function it(e){if(e.children)for(let t of e.children){if(t.parent)return;t.parent=e,it(t)}}function En(e,t){return st(e,r=>r.type===t)}function st(e,t){if(t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...st(n,t)];return r}async function ir(e,t){if(await t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...await ir(n,t)];return r}async function at(e,t){if(e.children){let r=e.children.slice();for(let n of r){let o=await t(n);if(o!==void 0){let i=e.children.indexOf(n);o?e.children.splice(i,1,o):e.children.splice(i,1)}else await at(n,t)}}}function ct(e,t){return st(e,r=>r.type===t)[0]}async function Ce(e,t){await ir(e,t)}function R(e){if(!e)return"";let t=[];if(e.text!==void 0)return e.text;for(let r of e.children)t.push(R(r));return t.join("")}function lt(e,t=!0){if(En(e,"\u26A0").length>0)throw new Error(`Parse error in: ${R(e)}`);if(e.text!==void 0)return e.text;let n=[e.type];for(let o of e.children)o.type&&!o.type.endsWith("Mark")&&n.push(lt(o,t)),o.text&&(t&&o.text.trim()||!t)&&n.push(o.text);return n}function Tn(e){return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0?e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0"):e.toISOString()}function ce(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(ce);if(e instanceof Date)return Tn(e);let t={};for(let r of Object.keys(e)){let n=r.split("."),o=t;for(let i=0;ito,copyToClipboard:()=>mo,deleteLine:()=>fo,dispatch:()=>Zn,downloadFile:()=>Bn,filterBox:()=>Hn,flashNotification:()=>Gn,fold:()=>oo,foldAll:()=>ao,getCurrentPage:()=>Cn,getCursor:()=>On,getSelection:()=>kn,getText:()=>Mn,getUiOption:()=>ro,goHistory:()=>qn,hidePanel:()=>Wn,insertAtCursor:()=>Xn,insertAtPos:()=>Qn,moveCursor:()=>zn,moveCursorToLine:()=>Jn,navigate:()=>Rn,openCommandPalette:()=>$n,openPageNavigator:()=>Ln,openSearchPanel:()=>po,openUrl:()=>jn,prompt:()=>eo,redo:()=>uo,reloadConfigAndCommands:()=>Un,reloadPage:()=>_n,reloadUI:()=>Dn,replaceRange:()=>Vn,save:()=>Fn,setSelection:()=>Nn,setText:()=>In,setUiOption:()=>no,showPanel:()=>Yn,toggleFold:()=>so,undo:()=>lo,unfold:()=>io,unfoldAll:()=>co,uploadFile:()=>Kn,vimEx:()=>go});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function l(e,...t){return globalThis.syscall(e,...t)}function Cn(){return l("editor.getCurrentPage")}function Mn(){return l("editor.getText")}function In(e){return l("editor.setText",e)}function On(){return l("editor.getCursor")}function kn(){return l("editor.getSelection")}function Nn(e,t){return l("editor.setSelection",e,t)}function Fn(){return l("editor.save")}function Rn(e,t=!1,r=!1){return l("editor.navigate",e,t,r)}function Ln(e="page"){return l("editor.openPageNavigator",e)}function $n(){return l("editor.openCommandPalette")}function _n(){return l("editor.reloadPage")}function Dn(){return l("editor.reloadUI")}function Un(){return l("editor.reloadConfigAndCommands")}function jn(e,t=!1){return l("editor.openUrl",e,t)}function qn(e){return l("editor.goHistory",e)}function Bn(e,t){return l("editor.downloadFile",e,t)}function Kn(e,t){return l("editor.uploadFile",e,t)}function Gn(e,t="info"){return l("editor.flashNotification",e,t)}function Hn(e,t,r="",n=""){return l("editor.filterBox",e,t,r,n)}function Yn(e,t,r,n=""){return l("editor.showPanel",e,t,r,n)}function Wn(e){return l("editor.hidePanel",e)}function Qn(e,t){return l("editor.insertAtPos",e,t)}function Vn(e,t,r){return l("editor.replaceRange",e,t,r)}function zn(e,t=!1){return l("editor.moveCursor",e,t)}function Jn(e,t=1,r=!1){return l("editor.moveCursorToLine",e,t,r)}function Xn(e){return l("editor.insertAtCursor",e)}function Zn(e){return l("editor.dispatch",e)}function eo(e,t=""){return l("editor.prompt",e,t)}function to(e){return l("editor.confirm",e)}function ro(e){return l("editor.getUiOption",e)}function no(e,t){return l("editor.setUiOption",e,t)}function oo(){return l("editor.fold")}function io(){return l("editor.unfold")}function so(){return l("editor.toggleFold")}function ao(){return l("editor.foldAll")}function co(){return l("editor.unfoldAll")}function lo(){return l("editor.undo")}function uo(){return l("editor.redo")}function po(){return l("editor.openSearchPanel")}function mo(e){return l("editor.copyToClipboard",e)}function fo(){return l("editor.deleteLine")}function go(e){return l("editor.vimEx",e)}var N={};U(N,{parseMarkdown:()=>ho,renderParseTree:()=>yo});function ho(e){return l("markdown.parseMarkdown",e)}function yo(e){return l("markdown.renderParseTree",e)}var $={};U($,{deleteAttachment:()=>Mo,deleteFile:()=>Fo,deletePage:()=>Ao,fileExists:()=>Ro,getAttachmentMeta:()=>Eo,getFileMeta:()=>ko,getPageMeta:()=>bo,listAttachments:()=>vo,listFiles:()=>Io,listPages:()=>xo,listPlugs:()=>So,readAttachment:()=>To,readFile:()=>Oo,readPage:()=>wo,writeAttachment:()=>Co,writeFile:()=>No,writePage:()=>Po});function xo(){return l("space.listPages")}function bo(e){return l("space.getPageMeta",e)}function wo(e){return l("space.readPage",e)}function Po(e,t){return l("space.writePage",e,t)}function Ao(e){return l("space.deletePage",e)}function So(){return l("space.listPlugs")}function vo(){return l("space.listAttachments")}function Eo(e){return l("space.getAttachmentMeta",e)}function To(e){return l("space.readAttachment",e)}function Co(e,t){return l("space.writeAttachment",e,t)}function Mo(e){return l("space.deleteAttachment",e)}function Io(){return l("space.listFiles")}function Oo(e){return l("space.readFile",e)}function ko(e){return l("space.getFileMeta",e)}function No(e,t){return l("space.writeFile",e,t)}function Fo(e){return l("space.deleteFile",e)}function Ro(e){return l("space.fileExists",e)}var S={};U(S,{applyAttributeExtractors:()=>jo,getEnv:()=>Go,getMode:()=>Ho,getSpaceConfig:()=>qo,getVersion:()=>Yo,invokeCommand:()=>$o,invokeFunction:()=>Lo,invokeSpaceFunction:()=>Uo,listCommands:()=>_o,listSyscalls:()=>Do,reloadConfig:()=>Ko,reloadPlugs:()=>Bo});function Lo(e,...t){return l("system.invokeFunction",e,...t)}function $o(e,t){return l("system.invokeCommand",e,t)}function _o(){return l("system.listCommands")}function Do(){return l("system.listSyscalls")}function Uo(e,...t){return l("system.invokeSpaceFunction",e,...t)}function jo(e,t,r){return l("system.applyAttributeExtractors",e,t,r)}async function qo(e,t){return await l("system.getSpaceConfig",e)??t}function Bo(){return l("system.reloadPlugs")}function Ko(){return l("system.reloadConfig")}function Go(){return l("system.getEnv")}function Ho(){return l("system.getMode")}function Yo(){return l("system.getVersion")}var Q={};U(Q,{del:()=>Vo,get:()=>Qo,set:()=>Wo});function Wo(e,t){return l("clientStore.set",e,t)}function Qo(e){return l("clientStore.get",e)}function Vo(e){return l("clientStore.delete",e)}var Me={};U(Me,{listLanguages:()=>Zo,parseLanguage:()=>Xo});function Xo(e,t){return l("language.parseLanguage",e,t)}function Zo(){return l("language.listLanguages")}var ne={};U(ne,{parseTemplate:()=>ti,renderTemplate:()=>ei});function ei(e,t,r={}){return l("template.renderTemplate",e,t,r)}function ti(e){return l("template.parseTemplate",e)}var ge={};U(ge,{dispatchEvent:()=>oi,listEvents:()=>ii});function oi(e,t,r){return new Promise((n,o)=>{let i=-1;r&&(i=setTimeout(()=>{console.log("Timeout!"),o("timeout")},r)),l("event.dispatch",e,t).then(s=>{i!==-1&&clearTimeout(i),n(s)}).catch(o)})}function ii(){return l("event.list")}var B={};U(B,{parse:()=>ai,stringify:()=>ci});function ai(e){return l("yaml.parse",e)}function ci(e){return l("yaml.stringify",e)}var oe={};U(oe,{ack:()=>pi,batchAck:()=>mi,batchSend:()=>ui,getQueueStats:()=>di,send:()=>li});function li(e,t){return l("mq.send",e,t)}function ui(e,t){return l("mq.batchSend",e,t)}function pi(e,t){return l("mq.ack",e,t)}function mi(e,t){return l("mq.batchAck",e,t)}function di(e){return l("mq.getQueueStats",e)}async function V(e,t={}){let r={tags:[]},n=[];it(e),await at(e,async o=>{if(o.type==="Paragraph"&&o.parent?.type==="Document"){let i=!0,s=new Set;for(let c of o.children)if(c.text){if(c.text.startsWith(` `)&&c.text!==` `)break;if(c.text.trim()){i=!1;break}}else if(c.type==="Hashtag"){let a=c.children[0].text.substring(1);s.add(a),(t.removeTags===!0||t.removeTags?.includes(a))&&(c.children[0].text="")}else if(c.type){i=!1;break}i&&n.push(...s)}if(o.type==="FrontMatter"){let i=o.children[1].children[0],s=R(i);try{let c=await B.parse(s),a={...c};if(r={...r,...c},r.tags||(r.tags=[]),typeof r.tags=="string"&&n.push(...r.tags.split(/,\s*|\s+/)),Array.isArray(r.tags)&&n.push(...r.tags),t.removeKeys&&t.removeKeys.length>0){let p=!1;for(let m of t.removeKeys)m in a&&(delete a[m],p=!0);p&&(i.text=await B.stringify(a))}if(Object.keys(a).length===0||t.removeFrontmatterSection)return null}catch{}}});try{r.tags=[...new Set([...n.map(o=>String(o).replace(/^#/,""))])]}catch(o){console.error("Error while processing tags",o)}return r=ce(r),r}async function ut(e,t){let r=null;if(await Ce(e,async n=>{if(n.type==="FrontMatter"){let o=n.children[1].children[0],i=R(o);try{let s="";if(typeof t=="string")s=i+t+` `;else{let a={...await B.parse(i),...t};s=await B.stringify(a)}r={changes:{from:o.from,to:o.to,insert:s}}}catch(s){console.error("Error parsing YAML",s)}return!0}return!1}),!r){let n="";typeof t=="string"?n=t+` `:n=await B.stringify(t),r={changes:{from:0,to:0,insert:`--- `+n+`--- -`}}}return r}function ir(e){let t={querySource:""},[r,n,...o]=e;if(r!=="Query")throw new Error(`Expected query type, got ${r}`);t.querySource=n[1];for(let i of o){let[s]=i;switch(s){case"WhereClause":{t.filter?t.filter=["and",t.filter,M(i[2])]:t.filter=M(i[2]);break}case"OrderClause":{t.orderBy||(t.orderBy=[]);for(let c of i.slice(2))if(c[0]==="OrderBy"){let a=c[1][1];c[2]?t.orderBy.push({expr:M(a),desc:c[2][1][1]==="desc"}):t.orderBy.push({expr:M(a),desc:!1})}break}case"LimitClause":{t.limit=M(i[2][1]);break}case"SelectClause":{for(let c of i.slice(2))c[0]==="Select"&&(t.select||(t.select=[]),c.length===2?t.select.push({name:ye(c[1][1])}):t.select.push({name:ye(c[3][1]),expr:M(c[1])}));break}case"RenderClause":{let c=i.find(a=>a[0]==="PageRef");t.render=c[1].slice(2,-2),t.renderAll=!!i.find(a=>a[0]==="all");break}default:throw new Error(`Unknown clause type: ${s}`)}}return t}function ye(e){return e.startsWith("`")&&e.endsWith("`")?e.slice(1,-1):e}function M(e){if(["LVal","Expression","Value"].includes(e[0]))return M(e[1]);switch(e[0]){case"Attribute":return["attr",M(e[1]),ye(e[3][1])];case"Identifier":return["attr",ye(e[1])];case"String":return["string",e[1].slice(1,-1)];case"Number":return["number",+e[1]];case"Bool":return["boolean",e[1][1]==="true"];case"null":return["null"];case"Regex":return["regexp",e[1].slice(1,-1),"i"];case"List":{let t=[];for(let r of e.slice(2))r[0]==="Expression"&&t.push(r);return["array",t.map(M)]}case"Object":{let t=[];for(let r of e.slice(2)){if(typeof r=="string")continue;let[n,o,i,s]=r;t.push([o[1].slice(1,-1),M(s)])}return["object",t]}case"BinExpression":{let t=M(e[1]),r=e[2][0]==="InKW"?"in":e[2].trim(),n=M(e[3]);return[r,t,n]}case"LogicalExpression":{let t=M(e[1]),r=e[2],n=M(e[3]);return[r[1],t,n]}case"ParenthesizedExpression":return M(e[2]);case"Call":{let t=ye(e[1][1]),r=[];for(let n of e.slice(2))n[0]==="Expression"&&r.push(n);return["call",t,r.map(M)]}case"UnaryExpression":{if(e[1][0]==="NotKW"||e[1][0]==="!")return["not",M(e[2])];if(e[1][0]==="-")return["-",M(e[2])];throw new Error(`Unknown unary expression: ${e[1][0]}`)}case"TopLevelVal":return["attr"];case"GlobalIdentifier":return["global",e[1].substring(1)];case"TernaryExpression":{let[t,r,n,o,i,s]=e;return["?",M(r),M(o),M(s)]}case"QueryExpression":return["query",ir(e[2])];case"PageRef":return["pageref",e[1].slice(2,-2)];default:throw new Error(`Not supported: ${e[0]}`)}}async function sr(e){let t=lt(await Me.parseLanguage("query",e));return ir(t[1])}async function ar(e,t){let r={};await Ce(t,async i=>{if(t!==i&&i.type==="ListItem")return!0;if(i.type==="Attribute"){let s=ct(i,"AttributeName"),c=ct(i,"AttributeValue");if(s&&c){let a=s.children[0].text,p=c.children[0].text;try{r[a]=ce(await B.parse(p))}catch(m){console.error("Error parsing attribute value as YAML",p,m)}}return!0}return!1});let n=R(t),o=await S.applyAttributeExtractors(e,n,t);return r={...r,...o},r}function pt(e,t){if(t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...pt(n,t)];return r}function mt(e,t){return pt(e,r=>r.type===t)[0]}function cr(e,t){pt(e,t)}typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function w(e,...t){return globalThis.syscall(e,...t)}var Ie={};U(Ie,{parseMarkdown:()=>yi,renderParseTree:()=>xi});function yi(e){return w("markdown.parseMarkdown",e)}function xi(e){return w("markdown.renderParseTree",e)}var Oe={};U(Oe,{deleteAttachment:()=>Ii,deleteFile:()=>Ri,deletePage:()=>Si,fileExists:()=>Li,getAttachmentMeta:()=>Ti,getFileMeta:()=>Ni,getPageMeta:()=>wi,listAttachments:()=>Ei,listFiles:()=>Oi,listPages:()=>bi,listPlugs:()=>vi,readAttachment:()=>Ci,readFile:()=>ki,readPage:()=>Pi,writeAttachment:()=>Mi,writeFile:()=>Fi,writePage:()=>Ai});function bi(){return w("space.listPages")}function wi(e){return w("space.getPageMeta",e)}function Pi(e){return w("space.readPage",e)}function Ai(e,t){return w("space.writePage",e,t)}function Si(e){return w("space.deletePage",e)}function vi(){return w("space.listPlugs")}function Ei(){return w("space.listAttachments")}function Ti(e){return w("space.getAttachmentMeta",e)}function Ci(e){return w("space.readAttachment",e)}function Mi(e,t){return w("space.writeAttachment",e,t)}function Ii(e){return w("space.deleteAttachment",e)}function Oi(){return w("space.listFiles")}function ki(e){return w("space.readFile",e)}function Ni(e){return w("space.getFileMeta",e)}function Fi(e,t){return w("space.writeFile",e,t)}function Ri(e){return w("space.deleteFile",e)}function Li(e){return w("space.fileExists",e)}var ke={};U(ke,{parse:()=>Yi,stringify:()=>Wi});function Yi(e){return w("yaml.parse",e)}function Wi(e){return w("yaml.stringify",e)}async function Ji(e,t){let r=await Oe.readPage(e),n=await Ie.parseMarkdown(r),o;return cr(n,i=>{if(i.type!=="FencedCode")return!1;let s=mt(i,"CodeInfo");if(t&&!s||t&&!t.includes(s.children[0].text))return!1;let c=mt(i,"CodeText");return c?(o=c.children[0].text,!0):!1}),o}async function lr(e,t=["yaml"]){let r=await Ji(e,t);if(r!==void 0)try{return ke.parse(r)}catch(n){throw console.error("YAML Page parser error",n),new Error(`YAML Error: ${n.message}`)}}async function Ne(e){try{let r=(await lr("SECRETS",["yaml","secrets"]))[e];if(r===void 0)throw new Error(`No such secret: ${e}`);return r}catch(t){throw t.message==="Not found"?new Error(`No such secret: ${e}`):t}}var le=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,n,o,i=!0){this.apiKey=t,this.baseUrl=r,this.name=n,this.modelName=o,this.requireAuth=i}};var Fe=class extends le{constructor(t,r,n){super(t,n,"DALL-E",r)}async generateImage(t){try{T||await z();let r=await nativeFetch(`${this.baseUrl}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.modelName,prompt:t.prompt,n:t.numImages,size:t.size,quality:t.quality,response_format:"b64_json"})});if(!r.ok)throw new Error(`HTTP error, status: ${r.status}`);let n=await r.json();if(!n||n.length===0)throw new Error("Invalid response from DALL-E.");return n}catch(r){throw console.error("Error calling DALL\xB7E image generation endpoint:",r),r}}};var ie=function(e,t){if(!(this instanceof ie))return new ie(e,t);this.INITIALIZING=-1,this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.url=e,t=t||{},this.headers=t.headers||{},this.payload=t.payload!==void 0?t.payload:"",this.method=t.method||this.payload&&"POST"||"GET",this.withCredentials=!!t.withCredentials,this.debug=!!t.debug,this.FIELD_SEPARATOR=":",this.listeners={},this.xhr=null,this.readyState=this.INITIALIZING,this.progress=0,this.chunk="",this.addEventListener=function(r,n){this.listeners[r]===void 0&&(this.listeners[r]=[]),this.listeners[r].indexOf(n)===-1&&this.listeners[r].push(n)},this.removeEventListener=function(r,n){if(this.listeners[r]!==void 0){var o=[];this.listeners[r].forEach(function(i){i!==n&&o.push(i)}),o.length===0?delete this.listeners[r]:this.listeners[r]=o}},this.dispatchEvent=function(r){if(!r)return!0;this.debug&&console.debug(r),r.source=this;var n="on"+r.type;return this.hasOwnProperty(n)&&(this[n].call(this,r),r.defaultPrevented)?!1:this.listeners[r.type]?this.listeners[r.type].every(function(o){return o(r),!r.defaultPrevented}):!0},this._setReadyState=function(r){var n=new CustomEvent("readystatechange");n.readyState=r,this.readyState=r,this.dispatchEvent(n)},this._onStreamFailure=function(r){var n=new CustomEvent("error");n.data=r.currentTarget.response,this.dispatchEvent(n),this.close()},this._onStreamAbort=function(r){this.dispatchEvent(new CustomEvent("abort")),this.close()},this._onStreamProgress=function(r){if(this.xhr){if(this.xhr.status!==200){this._onStreamFailure(r);return}this.readyState==this.CONNECTING&&(this.dispatchEvent(new CustomEvent("open")),this._setReadyState(this.OPEN));var n=this.xhr.responseText.substring(this.progress);this.progress+=n.length;var o=(this.chunk+n).split(/(\r\n\r\n|\r\r|\n\n)/g),i=o.pop();o.forEach(function(s){s.trim().length>0&&this.dispatchEvent(this._parseEventChunk(s))}.bind(this)),this.chunk=i}},this._onStreamLoaded=function(r){this._onStreamProgress(r),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=""},this._parseEventChunk=function(r){if(!r||r.length===0)return null;this.debug&&console.debug(r);var n={id:null,retry:null,data:null,event:null};r.split(/\n|\r\n|\r/).forEach(function(i){var s=i.indexOf(this.FIELD_SEPARATOR),c,a;if(s>0){var p=i[s+1]===" "?2:1;c=i.substring(0,s),a=i.substring(s+p)}else if(s<0)c=i,a="";else return;c in n&&(c==="data"&&n[c]!==null?n.data+=` -`+a:n[c]=a)}.bind(this));var o=new CustomEvent(n.event||"message");return o.data=n.data||"",o.id=n.id,o},this._checkStreamClosed=function(){this.xhr&&this.xhr.readyState===XMLHttpRequest.DONE&&this._setReadyState(this.CLOSED)},this.stream=function(){if(!this.xhr){this._setReadyState(this.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener("progress",this._onStreamProgress.bind(this)),this.xhr.addEventListener("load",this._onStreamLoaded.bind(this)),this.xhr.addEventListener("readystatechange",this._checkStreamClosed.bind(this)),this.xhr.addEventListener("error",this._onStreamFailure.bind(this)),this.xhr.addEventListener("abort",this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url);for(var r in this.headers)this.xhr.setRequestHeader(r,this.headers[r]);this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)}},this.close=function(){this.readyState!==this.CLOSED&&(this.xhr.abort(),this.xhr=null,this._setReadyState(this.CLOSED))},(t.start===void 0||t.start)&&this.stream()};typeof exports<"u"&&(exports.SSE=ie);var ur={};function Re(e,t){ur[e]=t}function Le(e){return ur[e]}async function $e(...e){let t=e.join(""),r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var H=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,n,o,i=!0){this.apiKey=t,this.baseUrl=r,this.name=n,this.modelName=o,this.requireAuth=i}async generateEmbeddings(t){let r=await $e(this.modelName,t.text),n=Le(r);if(n)return n;let o=await this._generateEmbeddings(t);return Re(r,o),o}};async function dt(){let e=await u.getSelection(),t="";return e.from===e.to?t="":t=(await u.getText()).slice(e.from,e.to),{from:e.from,to:e.to,text:t}}async function _e(){let e=await dt(),t=await u.getText();if(e.text==="")return{from:0,to:t.length,text:t,isWholeNote:!0};let r=e.from===0&&e.to===t.length;return{...e,isWholeNote:r}}async function se(){return(await u.getText()).length}function ft(e,t){let r=e.split(` +`}}}return r}function sr(e){let t={querySource:""},[r,n,...o]=e;if(r!=="Query")throw new Error(`Expected query type, got ${r}`);t.querySource=n[1];for(let i of o){let[s]=i;switch(s){case"WhereClause":{t.filter?t.filter=["and",t.filter,M(i[2])]:t.filter=M(i[2]);break}case"OrderClause":{t.orderBy||(t.orderBy=[]);for(let c of i.slice(2))if(c[0]==="OrderBy"){let a=c[1][1];c[2]?t.orderBy.push({expr:M(a),desc:c[2][1][1]==="desc"}):t.orderBy.push({expr:M(a),desc:!1})}break}case"LimitClause":{t.limit=M(i[2][1]);break}case"SelectClause":{for(let c of i.slice(2))c[0]==="Select"&&(t.select||(t.select=[]),c.length===2?t.select.push({name:he(c[1][1])}):t.select.push({name:he(c[3][1]),expr:M(c[1])}));break}case"RenderClause":{let c=i.find(a=>a[0]==="PageRef");t.render=c[1].slice(2,-2),t.renderAll=!!i.find(a=>a[0]==="all");break}default:throw new Error(`Unknown clause type: ${s}`)}}return t}function he(e){return e.startsWith("`")&&e.endsWith("`")?e.slice(1,-1):e}function M(e){if(["LVal","Expression","Value"].includes(e[0]))return M(e[1]);switch(e[0]){case"Attribute":return["attr",M(e[1]),he(e[3][1])];case"Identifier":return["attr",he(e[1])];case"String":return["string",e[1].slice(1,-1)];case"Number":return["number",+e[1]];case"Bool":return["boolean",e[1][1]==="true"];case"null":return["null"];case"Regex":return["regexp",e[1].slice(1,-1),"i"];case"List":{let t=[];for(let r of e.slice(2))r[0]==="Expression"&&t.push(r);return["array",t.map(M)]}case"Object":{let t=[];for(let r of e.slice(2)){if(typeof r=="string")continue;let[n,o,i,s]=r;t.push([o[1].slice(1,-1),M(s)])}return["object",t]}case"BinExpression":{let t=M(e[1]),r=e[2][0]==="InKW"?"in":e[2].trim(),n=M(e[3]);return[r,t,n]}case"LogicalExpression":{let t=M(e[1]),r=e[2],n=M(e[3]);return[r[1],t,n]}case"ParenthesizedExpression":return M(e[2]);case"Call":{let t=he(e[1][1]),r=[];for(let n of e.slice(2))n[0]==="Expression"&&r.push(n);return["call",t,r.map(M)]}case"UnaryExpression":{if(e[1][0]==="NotKW"||e[1][0]==="!")return["not",M(e[2])];if(e[1][0]==="-")return["-",M(e[2])];throw new Error(`Unknown unary expression: ${e[1][0]}`)}case"TopLevelVal":return["attr"];case"GlobalIdentifier":return["global",e[1].substring(1)];case"TernaryExpression":{let[t,r,n,o,i,s]=e;return["?",M(r),M(o),M(s)]}case"QueryExpression":return["query",sr(e[2])];case"PageRef":return["pageref",e[1].slice(2,-2)];default:throw new Error(`Not supported: ${e[0]}`)}}async function ar(e){let t=lt(await Me.parseLanguage("query",e));return sr(t[1])}async function cr(e,t){let r={};await Ce(t,async i=>{if(t!==i&&i.type==="ListItem")return!0;if(i.type==="Attribute"){let s=ct(i,"AttributeName"),c=ct(i,"AttributeValue");if(s&&c){let a=s.children[0].text,p=c.children[0].text;try{r[a]=ce(await B.parse(p))}catch(m){console.error("Error parsing attribute value as YAML",p,m)}}return!0}return!1});let n=R(t),o=await S.applyAttributeExtractors(e,n,t);return r={...r,...o},r}function pt(e,t){if(t(e))return[e];let r=[];if(e.children)for(let n of e.children)r=[...r,...pt(n,t)];return r}function mt(e,t){return pt(e,r=>r.type===t)[0]}function lr(e,t){pt(e,t)}typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function w(e,...t){return globalThis.syscall(e,...t)}var Ie={};U(Ie,{parseMarkdown:()=>yi,renderParseTree:()=>xi});function yi(e){return w("markdown.parseMarkdown",e)}function xi(e){return w("markdown.renderParseTree",e)}var Oe={};U(Oe,{deleteAttachment:()=>Ii,deleteFile:()=>Ri,deletePage:()=>Si,fileExists:()=>Li,getAttachmentMeta:()=>Ti,getFileMeta:()=>Ni,getPageMeta:()=>wi,listAttachments:()=>Ei,listFiles:()=>Oi,listPages:()=>bi,listPlugs:()=>vi,readAttachment:()=>Ci,readFile:()=>ki,readPage:()=>Pi,writeAttachment:()=>Mi,writeFile:()=>Fi,writePage:()=>Ai});function bi(){return w("space.listPages")}function wi(e){return w("space.getPageMeta",e)}function Pi(e){return w("space.readPage",e)}function Ai(e,t){return w("space.writePage",e,t)}function Si(e){return w("space.deletePage",e)}function vi(){return w("space.listPlugs")}function Ei(){return w("space.listAttachments")}function Ti(e){return w("space.getAttachmentMeta",e)}function Ci(e){return w("space.readAttachment",e)}function Mi(e,t){return w("space.writeAttachment",e,t)}function Ii(e){return w("space.deleteAttachment",e)}function Oi(){return w("space.listFiles")}function ki(e){return w("space.readFile",e)}function Ni(e){return w("space.getFileMeta",e)}function Fi(e,t){return w("space.writeFile",e,t)}function Ri(e){return w("space.deleteFile",e)}function Li(e){return w("space.fileExists",e)}var ke={};U(ke,{parse:()=>Yi,stringify:()=>Wi});function Yi(e){return w("yaml.parse",e)}function Wi(e){return w("yaml.stringify",e)}async function Ji(e,t){let r=await Oe.readPage(e),n=await Ie.parseMarkdown(r),o;return lr(n,i=>{if(i.type!=="FencedCode")return!1;let s=mt(i,"CodeInfo");if(t&&!s||t&&!t.includes(s.children[0].text))return!1;let c=mt(i,"CodeText");return c?(o=c.children[0].text,!0):!1}),o}async function ur(e,t=["yaml"]){let r=await Ji(e,t);if(r!==void 0)try{return ke.parse(r)}catch(n){throw console.error("YAML Page parser error",n),new Error(`YAML Error: ${n.message}`)}}async function Ne(e){try{let r=(await ur("SECRETS",["yaml","secrets"]))[e];if(r===void 0)throw new Error(`No such secret: ${e}`);return r}catch(t){throw t.message==="Not found"?new Error(`No such secret: ${e}`):t}}var le=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,n,o,i=!0){this.apiKey=t,this.baseUrl=r,this.name=n,this.modelName=o,this.requireAuth=i}};var Fe=class extends le{constructor(t,r,n){super(t,n,"DALL-E",r)}async generateImage(t){try{T||await z();let r=await nativeFetch(`${this.baseUrl}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.modelName,prompt:t.prompt,n:t.numImages,size:t.size,quality:t.quality,response_format:"b64_json"})});if(!r.ok)throw new Error(`HTTP error, status: ${r.status}`);let n=await r.json();if(!n||n.length===0)throw new Error("Invalid response from DALL-E.");return n}catch(r){throw console.error("Error calling DALL\xB7E image generation endpoint:",r),r}}};var ie=function(e,t){if(!(this instanceof ie))return new ie(e,t);this.INITIALIZING=-1,this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.url=e,t=t||{},this.headers=t.headers||{},this.payload=t.payload!==void 0?t.payload:"",this.method=t.method||this.payload&&"POST"||"GET",this.withCredentials=!!t.withCredentials,this.debug=!!t.debug,this.FIELD_SEPARATOR=":",this.listeners={},this.xhr=null,this.readyState=this.INITIALIZING,this.progress=0,this.chunk="",this.addEventListener=function(r,n){this.listeners[r]===void 0&&(this.listeners[r]=[]),this.listeners[r].indexOf(n)===-1&&this.listeners[r].push(n)},this.removeEventListener=function(r,n){if(this.listeners[r]!==void 0){var o=[];this.listeners[r].forEach(function(i){i!==n&&o.push(i)}),o.length===0?delete this.listeners[r]:this.listeners[r]=o}},this.dispatchEvent=function(r){if(!r)return!0;this.debug&&console.debug(r),r.source=this;var n="on"+r.type;return this.hasOwnProperty(n)&&(this[n].call(this,r),r.defaultPrevented)?!1:this.listeners[r.type]?this.listeners[r.type].every(function(o){return o(r),!r.defaultPrevented}):!0},this._setReadyState=function(r){var n=new CustomEvent("readystatechange");n.readyState=r,this.readyState=r,this.dispatchEvent(n)},this._onStreamFailure=function(r){var n=new CustomEvent("error");n.data=r.currentTarget.response,this.dispatchEvent(n),this.close()},this._onStreamAbort=function(r){this.dispatchEvent(new CustomEvent("abort")),this.close()},this._onStreamProgress=function(r){if(this.xhr){if(this.xhr.status!==200){this._onStreamFailure(r);return}this.readyState==this.CONNECTING&&(this.dispatchEvent(new CustomEvent("open")),this._setReadyState(this.OPEN));var n=this.xhr.responseText.substring(this.progress);this.progress+=n.length;var o=(this.chunk+n).split(/(\r\n\r\n|\r\r|\n\n)/g),i=o.pop();o.forEach(function(s){s.trim().length>0&&this.dispatchEvent(this._parseEventChunk(s))}.bind(this)),this.chunk=i}},this._onStreamLoaded=function(r){this._onStreamProgress(r),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=""},this._parseEventChunk=function(r){if(!r||r.length===0)return null;this.debug&&console.debug(r);var n={id:null,retry:null,data:null,event:null};r.split(/\n|\r\n|\r/).forEach(function(i){var s=i.indexOf(this.FIELD_SEPARATOR),c,a;if(s>0){var p=i[s+1]===" "?2:1;c=i.substring(0,s),a=i.substring(s+p)}else if(s<0)c=i,a="";else return;c in n&&(c==="data"&&n[c]!==null?n.data+=` +`+a:n[c]=a)}.bind(this));var o=new CustomEvent(n.event||"message");return o.data=n.data||"",o.id=n.id,o},this._checkStreamClosed=function(){this.xhr&&this.xhr.readyState===XMLHttpRequest.DONE&&this._setReadyState(this.CLOSED)},this.stream=function(){if(!this.xhr){this._setReadyState(this.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener("progress",this._onStreamProgress.bind(this)),this.xhr.addEventListener("load",this._onStreamLoaded.bind(this)),this.xhr.addEventListener("readystatechange",this._checkStreamClosed.bind(this)),this.xhr.addEventListener("error",this._onStreamFailure.bind(this)),this.xhr.addEventListener("abort",this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url);for(var r in this.headers)this.xhr.setRequestHeader(r,this.headers[r]);this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)}},this.close=function(){this.readyState!==this.CLOSED&&(this.xhr.abort(),this.xhr=null,this._setReadyState(this.CLOSED))},(t.start===void 0||t.start)&&this.stream()};typeof exports<"u"&&(exports.SSE=ie);var pr={};function Re(e,t){pr[e]=t}function Le(e){return pr[e]}async function $e(...e){let t=e.join(""),r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var H=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,n,o,i=!0){this.apiKey=t,this.baseUrl=r,this.name=n,this.modelName=o,this.requireAuth=i}async generateEmbeddings(t){let r=await $e(this.modelName,t.text),n=Le(r);if(n)return n;let o=await this._generateEmbeddings(t);return Re(r,o),o}};async function dt(){let e=await u.getSelection(),t="";return e.from===e.to?t="":t=(await u.getText()).slice(e.from,e.to),{from:e.from,to:e.to,text:t}}async function _e(){let e=await dt(),t=await u.getText();if(e.text==="")return{from:0,to:t.length,text:t,isWholeNote:!0};let r=e.from===0&&e.to===t.length;return{...e,isWholeNote:r}}async function se(){return(await u.getText()).length}function ft(e,t){let r=e.split(` `),n=0;for(let o=0;o=r.length?"":r[t]}function mr(e,t){let r=ft(e,t);return gt(e,r)}function dr(e,t){let r=ft(e,t);return gt(e,r-1)}function fr(e,t){let r=ft(e,t);return gt(e,r+1)}function gr(e,t){let r=e.split(` +`);return t<0||t>=r.length?"":r[t]}function dr(e,t){let r=ft(e,t);return gt(e,r)}function fr(e,t){let r=ft(e,t);return gt(e,r-1)}function gr(e,t){let r=ft(e,t);return gt(e,r+1)}function hr(e,t){let r=e.split(` `),n=0,o=0,i=e.length;for(let s=0;s=0;a--)if(a===0||r[a-1].trim()===""){o=a===0?0:r.slice(0,a).join(` `).length+1;break}console.log("Looking forwards for the end of the paragraph");for(let a=s;a{try{if(!g){console.log("No data received from LLM");return}a?(["`","-","*"].includes(g.charAt(0))&&(g=` -`+g),u.replaceRange(c,c+s.length,g),a=!1):u.insertAtPos(g,c),c+=g.length,n&&n(g)}catch(y){console.error("Error handling chat stream data:",y),u.flashNotification("An error occurred while processing chat data.","error")}},d=async g=>{console.log("Response complete:",g);let y=p+g.length;console.log("Start of response:",p),console.log("End of response:",y),console.log("Full response:",g),console.log("Post-processors:",i);let x=g;if(i){let P=await u.getText(),b={response:g,lineBefore:dr(P,p),lineCurrent:mr(P,p),lineAfter:fr(P,y)};for(let k of i)console.log("Applying post-processor:",k),x=await S.invokeSpaceFunction(k,b);console.log("Data changed by post-processors, updating editor"),u.replaceRange(p,y,x)}o&&o(g)};await this.chatWithAI({...t,onDataReceived:m,onResponseComplete:d})}async singleMessageChat(t,r,n=!1){let o=[{role:"user",content:t}];return r&&o.unshift({role:"system",content:r}),n&&(o=await ue(o)),await this.chatWithAI({messages:o,stream:!1})}};var De=class extends Y{name="Gemini";constructor(t,r){super("Gemini",t,"https://generativelanguage.googleapis.com",r)}async listModels(){let t=`${this.baseUrl}/v1beta/models?key=${this.apiKey}`;try{let r=await fetch(t);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return(await r.json()).models||[]}catch(r){throw console.error("Failed to fetch models:",r),r}}async chatWithAI({messages:t,stream:r,onDataReceived:n}){return r?await this.streamChat({messages:t,stream:r,onDataReceived:n}):await this.nonStreamingChat(t)}mapRolesForGemini(t){let r=[],n="";return t.forEach(o=>{let i="user";o.role==="system"||o.role==="user"?i="user":o.role==="assistant"&&(i="model"),i==="model"&&(r.length===0||n==="model")||(i==="user"&&n==="user"?r[r.length-1].parts[0].text+=" "+o.content:r.push({role:i,parts:[{text:o.content}]})),n=i}),r}streamChat(t){let{messages:r,onDataReceived:n}=t;try{let o=`${this.baseUrl}/v1beta/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}&alt=sse`,i={"Content-Type":"application/json"},s=this.mapRolesForGemini(r),c={method:"POST",headers:i,payload:JSON.stringify({contents:s}),withCredentials:!1},a=new ie(o,c),p="";a.addEventListener("message",m=>{try{if(m.data=="[DONE]")return a.close(),p;if(!m.data)console.error("Received empty message from Gemini"),console.log("source: ",a);else{let d=JSON.parse(m.data),g=d.candidates[0].content.parts[0].text||d.text||"";p+=g,n&&n(g)}}catch(d){console.error("Error processing message event:",d,m.data)}}),a.addEventListener("end",()=>(a.close(),p)),a.addEventListener("error",m=>{console.error("SSE error:",m),a.close()}),a.stream()}catch(o){throw console.error("Error streaming from Gemini chat endpoint:",o),o}}async nonStreamingChat(t){let r=this.mapRolesForGemini(t),n=await nativeFetch(`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:r})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return(await n.json()).candidates[0].content.parts[0].text}},Ue=class extends H{constructor(t,r,n="https://generativelanguage.googleapis.com",o=!0){super(t,n,"Gemini",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,content:{parts:[{text:t.text}]}}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/v1beta/models/${this.modelName}:embedContent?key=${this.apiKey}`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.embedding||!i.embedding.values)throw new Error("Invalid response from Gemini.");return i.embedding.values}};var pe=class extends Y{name="OpenAI";requireAuth;constructor(t,r,n,o){super("OpenAI",t,n,r),this.requireAuth=o}async chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o}){return r?await this.streamChat({messages:t,onDataReceived:n,onResponseComplete:o}):await this.nonStreamingChat(t)}async streamChat(t){let{messages:r,onDataReceived:n,onResponseComplete:o}=t;try{let i=`${this.baseUrl}/chat/completions`,s={"Content-Type":"application/json"};this.requireAuth&&(s.Authorization=`Bearer ${this.apiKey}`);let c={method:"POST",headers:s,payload:JSON.stringify({model:this.modelName,stream:!0,messages:r}),withCredentials:!1},a=new ie(i,c),p="";a.addEventListener("message",function(m){try{if(m.data=="[DONE]")return a.close(),o&&o(p),p;{let g=JSON.parse(m.data).choices[0]?.delta?.content||"";p+=g,n&&n(g)}}catch(d){console.error("Error processing message event:",d,m.data)}}),a.addEventListener("end",function(){return a.close(),o&&o(p),p}),a.addEventListener("error",m=>{console.error("SSE error:",m),a.close()}),a.stream()}catch(i){throw console.error("Error streaming from OpenAI chat endpoint:",i),await u.flashNotification("Error streaming from OpenAI chat endpoint.","error"),i}return""}async nonStreamingChat(t){try{let r=JSON.stringify({model:this.modelName,messages:t}),n={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=await nativeFetch(this.baseUrl+"/chat/completions",{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("http response: ",o),console.error("http response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.choices||i.choices.length===0)throw new Error("Invalid response from OpenAI.");return i.choices[0].message.content}catch(r){throw console.error("Error calling OpenAI chat endpoint:",r),await u.flashNotification("Error calling OpenAI chat endpoint.","error"),r}}},je=class extends H{constructor(t,r,n,o=!0){super(t,n,"OpenAI",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,input:t.text,encoding_format:"float"}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/embeddings`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.data||i.data.length===0)throw new Error("Invalid response from OpenAI.");return i.data[0].embedding}};var qe=class extends Y{name="Ollama";requireAuth;openaiProvider;constructor(t,r,n,o){super("Ollama",t,n,r),this.requireAuth=o,this.openaiProvider=new pe(t,r,n,o)}async chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o}){return await this.openaiProvider.chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o})}},Be=class extends H{constructor(t,r,n,o=!1){super(t,n,"Ollama",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,prompt:t.text}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.embedding||i.embedding.length===0)throw new Error("Invalid response from Ollama.");return i.embedding}};var Ke=class extends Y{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}async chatWithAI(t){let r="This is a mock response from the AI.";if(t.onDataReceived)for(let n of r)await new Promise(o=>setTimeout(o,50)),t.onDataReceived(n);return r}},Ge=class extends le{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}generateImage(t){return new Promise(r=>{setTimeout(()=>{r("https://example.com/mock-image.jpg")},5)})}},He=class extends H{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}_generateEmbeddings(t){return new Promise(r=>{setTimeout(()=>{let n=Array(1536).fill(0).map(()=>Math.random());r(n)},5)})}};var T,f,xe,O,Ye,j,ht,Xi,be;async function C(){let e=await hr();(!T||!O||!f||!ht||JSON.stringify(e)!==JSON.stringify(ht))&&await z(!0)}async function hr(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedTextModel")}catch{return}}async function Zi(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedImageModel")}catch{return}}async function es(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedEmbeddingModel")}catch{return}}async function yt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedImageModel",e)}async function xt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedTextModel",e)}async function bt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedEmbeddingModel",e)}async function ts(){let e=await hr()||f.textModels[0];if(!e)throw new Error("No text model selected or available as default.");await we(e)}async function rs(){let e=await Zi()||f.imageModels[0];if(!e)throw new Error("No image model selected or available as default.");await wt(e)}async function ns(){let e=await es()||f.embeddingModels[0];if(!e)throw new Error("No embedding model selected or available as default.");await Pt(e)}function os(e){let t=e.provider.toLowerCase();switch(_("client","Provider name",t),t){case"dalle":Ye=new Fe(T,e.modelName,e.baseUrl||f.dallEBaseUrl);break;case"mock":Ye=new Ge(T,e.modelName);break;default:throw new Error(`Unsupported image provider: ${e.provider}. Please configure a supported provider.`)}}function is(e){switch(e.provider.toLowerCase()){case"openai":O=new pe(T,e.modelName,e.baseUrl||f.openAIBaseUrl,e.requireAuth||f.requireAuth);break;case"gemini":O=new De(T,e.modelName);break;case"ollama":O=new qe(T,e.modelName,e.baseUrl||"http://localhost:11434/v1",e.requireAuth);break;case"mock":O=new Ke(T,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported AI provider: ${e.provider}. Please configure a supported provider.`)}return O}function ss(e){switch(e.provider.toLowerCase()){case"openai":j=new je(T,e.modelName,e.baseUrl||f.openAIBaseUrl);break;case"gemini":j=new Ue(T,e.modelName);break;case"ollama":j=new Be(T,e.modelName,e.baseUrl||"http://localhost:11434",e.requireAuth);break;case"mock":j=new He(T,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported embedding provider: ${e.provider}. Please configure a supported provider.`)}}async function we(e){if(_("client","configureSelectedModel called with:",e),!e)throw new Error("No model provided to configure");if(e.requireAuth=e.requireAuth??f.requireAuth,e.requireAuth)try{let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated"))}catch(t){throw console.error("Error reading secret:",t),new Error("Failed to read the AI API key. Please check the SECRETS page.")}if(e.requireAuth&&!T)throw new Error("AI API key is missing. Please set it in the secrets page.");return ht=e,is(e)}async function wt(e){if(_("client","configureSelectedImageModel called with:",e),!e)throw new Error("No image model provided to configure");if(e.requireAuth){let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated for image model"))}if(e.requireAuth&&!T)throw new Error("AI API key is missing for image model. Please set it in the secrets page.");Xi=e,os(e)}async function Pt(e){if(_("client","configureSelectedEmbeddingModel called with:",e),!e)throw new Error("No embedding model provided to configure");if(e.requireAuth){let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated for embedding model"))}if(e.requireAuth&&!T)throw new Error("AI API key is missing for embedding model. Please set it in the secrets page.");be=e,ss(e)}async function as(){let e={openAIBaseUrl:"https://api.openai.com/v1",dallEBaseUrl:"https://api.openai.com/v1",requireAuth:!0,secretName:"OPENAI_API_KEY",provider:"OpenAI",chat:{},promptInstructions:{},imageModels:[],embeddingModels:[],textModels:[],indexEmbeddings:!1,indexSummary:!1,indexSummaryModelName:"",indexEmbeddingsExcludePages:[],indexEmbeddingsExcludeStrings:["**user**:"]},t={userInformation:"",userInstructions:"",parseWikiLinks:!0,bakeMessages:!0,customEnrichFunctions:[],searchEmbeddings:!1},r={pageRenameSystem:"",pageRenameRules:"",tagRules:"",indexSummaryPrompt:"",enhanceFrontMatterPrompt:""},n=await S.getSpaceConfig("ai",{}),o={...e,...n};return o.chat={...t,...n.chat||{}},o.promptInstructions={...r,...n.promptInstructions||{}},o}async function z(e=!0){let t=await as();!f||JSON.stringify(f)!==JSON.stringify(t)?(_("client","aiSettings updating from",f),f=t,_("client","aiSettings updated to",f)):_("client","aiSettings unchanged",f),f.textModels.length===1&&await xt(f.textModels[0]),f.imageModels.length===1&&await yt(f.imageModels[0]),f.embeddingModels.length===1&&await bt(f.embeddingModels[0]),e&&(f.textModels.length>0&&await ts(),f.imageModels.length>0&&await rs(),f.embeddingModels.length>0&&await ns()),xe={role:"system",content:"This is an interactive chat session with a user in a markdown-based note-taking tool called SilverBullet."},f.chat.userInformation&&(xe.content+=` -The user has provided the following information about themselves: ${f.chat.userInformation}`),f.chat.userInstructions&&(xe.content+=` -The user has provided the following instructions for the chat, follow them as closely as possible: ${f.chat.userInstructions}`)}var At="\u{1F916} ";function Pe(e){return!(["SETTINGS","SECRETS",...f.indexEmbeddingsExcludePages].includes(e)||e.startsWith("_")||e.startsWith("Library/")||/\.conflicted\.\d+$/.test(e))}async function yr(){return await C(),f.indexEmbeddings&&j!==void 0&&be!==void 0&&f.embeddingModels.length>0&&await S.getEnv()==="server"}async function xr(){return await C(),f.indexEmbeddings&&f.indexSummary&&j!==void 0&&be!==void 0&&f.embeddingModels.length>0&&await S.getEnv()==="server"}async function cs(e){if(!await yr()||!Pe(e))return;let t=await $.readPage(e),r=await N.parseMarkdown(t);if(!r.children)return;let n=r.children.filter(a=>a.type==="Paragraph"),o=[],i=Date.now();for(let a of n){let p=R(a).trim();if(!p||p.length<10||f.indexEmbeddingsExcludeStrings.some(y=>p.includes(y)))continue;let m=await j.generateEmbeddings({text:p}),d=a.from??0,g={ref:`${e}@${d}`,page:e,pos:d,embedding:m,text:p,tag:"embedding"};o.push(g)}await Ct(e,o);let c=(Date.now()-i)/1e3;_("any",`AI: Indexed ${o.length} embedding objects for page ${e} in ${c} seconds`)}async function ls(e){if(!await xr()||!Pe(e))return;let t=await $.readPage(e),r=await N.parseMarkdown(t);if(!r.children)return;let n=Date.now(),o=R(r),i=f.textModels.find(x=>x.name===f.indexSummaryModelName);if(!i)throw new Error(`Could not find summary model ${f.indexSummaryModelName}`);let s=await we(i),c;f.promptInstructions.indexSummaryPrompt!==""?c=f.promptInstructions.indexSummaryPrompt:c=`Provide a concise and informative summary of the above page. The summary should capture the key points and be useful for search purposes. Avoid any formatting or extraneous text. No more than one paragraph. Summary: +`+g),u.replaceRange(c,c+s.length,g),a=!1):u.insertAtPos(g,c),c+=g.length,n&&n(g)}catch(y){console.error("Error handling chat stream data:",y),u.flashNotification("An error occurred while processing chat data.","error")}},d=async g=>{console.log("Response complete:",g);let y=p+g.length;console.log("Start of response:",p),console.log("End of response:",y),console.log("Full response:",g),console.log("Post-processors:",i);let x=g;if(i){let P=await u.getText(),b={response:g,lineBefore:fr(P,p),lineCurrent:dr(P,p),lineAfter:gr(P,y)};for(let k of i)console.log("Applying post-processor:",k),x=await S.invokeSpaceFunction(k,b);console.log("Data changed by post-processors, updating editor"),u.replaceRange(p,y,x)}o&&o(g)};await this.chatWithAI({...t,onDataReceived:m,onResponseComplete:d})}async singleMessageChat(t,r,n=!1){let o=[{role:"user",content:t}];return r&&o.unshift({role:"system",content:r}),n&&(o=await ue(o)),await this.chatWithAI({messages:o,stream:!1})}};var De=class extends Y{name="Gemini";constructor(t,r){super("Gemini",t,"https://generativelanguage.googleapis.com",r)}async listModels(){let t=`${this.baseUrl}/v1beta/models?key=${this.apiKey}`;try{let r=await fetch(t);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return(await r.json()).models||[]}catch(r){throw console.error("Failed to fetch models:",r),r}}async chatWithAI({messages:t,stream:r,onDataReceived:n}){return r?await this.streamChat({messages:t,stream:r,onDataReceived:n}):await this.nonStreamingChat(t)}mapRolesForGemini(t){let r=[],n="";return t.forEach(o=>{let i="user";o.role==="system"||o.role==="user"?i="user":o.role==="assistant"&&(i="model"),i==="model"&&(r.length===0||n==="model")||(i==="user"&&n==="user"?r[r.length-1].parts[0].text+=" "+o.content:r.push({role:i,parts:[{text:o.content}]})),n=i}),r}streamChat(t){let{messages:r,onDataReceived:n}=t;try{let o=`${this.baseUrl}/v1beta/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}&alt=sse`,i={"Content-Type":"application/json"},s=this.mapRolesForGemini(r),c={method:"POST",headers:i,payload:JSON.stringify({contents:s}),withCredentials:!1},a=new ie(o,c),p="";a.addEventListener("message",m=>{try{if(m.data=="[DONE]")return a.close(),p;if(!m.data)console.error("Received empty message from Gemini"),console.log("source: ",a);else{let d=JSON.parse(m.data),g=d.candidates[0].content.parts[0].text||d.text||"";p+=g,n&&n(g)}}catch(d){console.error("Error processing message event:",d,m.data)}}),a.addEventListener("end",()=>(a.close(),p)),a.addEventListener("error",m=>{console.error("SSE error:",m),a.close()}),a.stream()}catch(o){throw console.error("Error streaming from Gemini chat endpoint:",o),o}}async nonStreamingChat(t){let r=this.mapRolesForGemini(t),n=await nativeFetch(`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:r})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return(await n.json()).candidates[0].content.parts[0].text}},Ue=class extends H{constructor(t,r,n="https://generativelanguage.googleapis.com",o=!0){super(t,n,"Gemini",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,content:{parts:[{text:t.text}]}}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/v1beta/models/${this.modelName}:embedContent?key=${this.apiKey}`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.embedding||!i.embedding.values)throw new Error("Invalid response from Gemini.");return i.embedding.values}};var pe=class extends Y{name="OpenAI";requireAuth;constructor(t,r,n,o){super("OpenAI",t,n,r),this.requireAuth=o}async chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o}){return r?await this.streamChat({messages:t,onDataReceived:n,onResponseComplete:o}):await this.nonStreamingChat(t)}async streamChat(t){let{messages:r,onDataReceived:n,onResponseComplete:o}=t;try{let i=`${this.baseUrl}/chat/completions`,s={"Content-Type":"application/json"};this.requireAuth&&(s.Authorization=`Bearer ${this.apiKey}`);let c={method:"POST",headers:s,payload:JSON.stringify({model:this.modelName,stream:!0,messages:r}),withCredentials:!1},a=new ie(i,c),p="";a.addEventListener("message",function(m){try{if(m.data=="[DONE]")return a.close(),o&&o(p),p;{let g=JSON.parse(m.data).choices[0]?.delta?.content||"";p+=g,n&&n(g)}}catch(d){console.error("Error processing message event:",d,m.data)}}),a.addEventListener("end",function(){return a.close(),o&&o(p),p}),a.addEventListener("error",m=>{console.error("SSE error:",m),a.close()}),a.stream()}catch(i){throw console.error("Error streaming from OpenAI chat endpoint:",i),await u.flashNotification("Error streaming from OpenAI chat endpoint.","error"),i}return""}async nonStreamingChat(t){try{let r=JSON.stringify({model:this.modelName,messages:t}),n={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=await nativeFetch(this.baseUrl+"/chat/completions",{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("http response: ",o),console.error("http response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.choices||i.choices.length===0)throw new Error("Invalid response from OpenAI.");return i.choices[0].message.content}catch(r){throw console.error("Error calling OpenAI chat endpoint:",r),await u.flashNotification("Error calling OpenAI chat endpoint.","error"),r}}},je=class extends H{constructor(t,r,n,o=!0){super(t,n,"OpenAI",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,input:t.text,encoding_format:"float"}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/embeddings`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.data||i.data.length===0)throw new Error("Invalid response from OpenAI.");return i.data[0].embedding}};var qe=class extends Y{name="Ollama";requireAuth;openaiProvider;constructor(t,r,n,o){super("Ollama",t,n,r),this.requireAuth=o,this.openaiProvider=new pe(t,r,n,o)}async chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o}){return await this.openaiProvider.chatWithAI({messages:t,stream:r,onDataReceived:n,onResponseComplete:o})}},Be=class extends H{constructor(t,r,n,o=!1){super(t,n,"Ollama",r,o)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,prompt:t.text}),n={"Content-Type":"application/json"};this.requireAuth&&(n.Authorization=`Bearer ${this.apiKey}`);let o=await nativeFetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:n,body:r});if(!o.ok)throw console.error("HTTP response: ",o),console.error("HTTP response body: ",await o.json()),new Error(`HTTP error, status: ${o.status}`);let i=await o.json();if(!i||!i.embedding||i.embedding.length===0)throw new Error("Invalid response from Ollama.");return i.embedding}};var Ke=class extends Y{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}async chatWithAI(t){let r="This is a mock response from the AI.";if(t.onDataReceived)for(let n of r)await new Promise(o=>setTimeout(o,50)),t.onDataReceived(n);return r}},Ge=class extends le{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}generateImage(t){return new Promise(r=>{setTimeout(()=>{r("https://example.com/mock-image.jpg")},5)})}},He=class extends H{constructor(t,r,n="http://localhost"){super(t,n,"mock",r)}_generateEmbeddings(t){return new Promise(r=>{setTimeout(()=>{let n=Array(1536).fill(0).map(()=>Math.random());r(n)},5)})}};var T,f,ye,O,Ye,j,ht,Xi,xe;async function C(){let e=await yr();(!T||!O||!f||!ht||JSON.stringify(e)!==JSON.stringify(ht))&&await z(!0)}async function yr(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedTextModel")}catch{return}}async function Zi(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedImageModel")}catch{return}}async function es(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedEmbeddingModel")}catch{return}}async function yt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedImageModel",e)}async function xt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedTextModel",e)}async function bt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedEmbeddingModel",e)}async function ts(){let e=await yr()||f.textModels[0];if(!e)throw new Error("No text model selected or available as default.");await be(e)}async function rs(){let e=await Zi()||f.imageModels[0];if(!e)throw new Error("No image model selected or available as default.");await wt(e)}async function ns(){let e=await es()||f.embeddingModels[0];if(!e)throw new Error("No embedding model selected or available as default.");await Pt(e)}function os(e){let t=e.provider.toLowerCase();switch(_("client","Provider name",t),t){case"dalle":Ye=new Fe(T,e.modelName,e.baseUrl||f.dallEBaseUrl);break;case"mock":Ye=new Ge(T,e.modelName);break;default:throw new Error(`Unsupported image provider: ${e.provider}. Please configure a supported provider.`)}}function is(e){switch(e.provider.toLowerCase()){case"openai":O=new pe(T,e.modelName,e.baseUrl||f.openAIBaseUrl,e.requireAuth||f.requireAuth);break;case"gemini":O=new De(T,e.modelName);break;case"ollama":O=new qe(T,e.modelName,e.baseUrl||"http://localhost:11434/v1",e.requireAuth);break;case"mock":O=new Ke(T,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported AI provider: ${e.provider}. Please configure a supported provider.`)}return O}function ss(e){switch(e.provider.toLowerCase()){case"openai":j=new je(T,e.modelName,e.baseUrl||f.openAIBaseUrl);break;case"gemini":j=new Ue(T,e.modelName);break;case"ollama":j=new Be(T,e.modelName,e.baseUrl||"http://localhost:11434",e.requireAuth);break;case"mock":j=new He(T,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported embedding provider: ${e.provider}. Please configure a supported provider.`)}}async function be(e){if(_("client","configureSelectedModel called with:",e),!e)throw new Error("No model provided to configure");if(e.requireAuth=e.requireAuth??f.requireAuth,e.requireAuth)try{let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated"))}catch(t){throw console.error("Error reading secret:",t),new Error("Failed to read the AI API key. Please check the SECRETS page.")}if(e.requireAuth&&!T)throw new Error("AI API key is missing. Please set it in the secrets page.");return ht=e,is(e)}async function wt(e){if(_("client","configureSelectedImageModel called with:",e),!e)throw new Error("No image model provided to configure");if(e.requireAuth){let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated for image model"))}if(e.requireAuth&&!T)throw new Error("AI API key is missing for image model. Please set it in the secrets page.");Xi=e,os(e)}async function Pt(e){if(_("client","configureSelectedEmbeddingModel called with:",e),!e)throw new Error("No embedding model provided to configure");if(e.requireAuth){let t=await Ne(e.secretName||"OPENAI_API_KEY");t!==T&&(T=t,_("client","API key updated for embedding model"))}if(e.requireAuth&&!T)throw new Error("AI API key is missing for embedding model. Please set it in the secrets page.");xe=e,ss(e)}async function as(){let e={openAIBaseUrl:"https://api.openai.com/v1",dallEBaseUrl:"https://api.openai.com/v1",requireAuth:!0,secretName:"OPENAI_API_KEY",provider:"OpenAI",chat:{},promptInstructions:{},imageModels:[],embeddingModels:[],textModels:[],indexEmbeddings:!1,indexSummary:!1,indexSummaryModelName:"",indexEmbeddingsExcludePages:[],indexEmbeddingsExcludeStrings:["**user**:"]},t={userInformation:"",userInstructions:"",parseWikiLinks:!0,bakeMessages:!0,customEnrichFunctions:[],searchEmbeddings:!1},r={pageRenameSystem:"",pageRenameRules:"",tagRules:"",indexSummaryPrompt:"",enhanceFrontMatterPrompt:""},n=await S.getSpaceConfig("ai",{}),o={...e,...n};return o.chat={...t,...n.chat||{}},o.promptInstructions={...r,...n.promptInstructions||{}},o}async function z(e=!0){let t=await as();!f||JSON.stringify(f)!==JSON.stringify(t)?(_("client","aiSettings updating from",f),f=t,_("client","aiSettings updated to",f)):_("client","aiSettings unchanged",f),f.textModels.length===1&&await xt(f.textModels[0]),f.imageModels.length===1&&await yt(f.imageModels[0]),f.embeddingModels.length===1&&await bt(f.embeddingModels[0]),e&&(f.textModels.length>0&&await ts(),f.imageModels.length>0&&await rs(),f.embeddingModels.length>0&&await ns()),ye={role:"system",content:"This is an interactive chat session with a user in a markdown-based note-taking tool called SilverBullet."},f.chat.userInformation&&(ye.content+=` +The user has provided the following information about themselves: ${f.chat.userInformation}`),f.chat.userInstructions&&(ye.content+=` +The user has provided the following instructions for the chat, follow them as closely as possible: ${f.chat.userInstructions}`)}var At="\u{1F916} ";function we(e){return!(["SETTINGS","SECRETS",...f.indexEmbeddingsExcludePages].includes(e)||e.startsWith("_")||e.startsWith("Library/")||/\.conflicted\.\d+$/.test(e))}async function xr(){return await C(),f.indexEmbeddings&&j!==void 0&&xe!==void 0&&f.embeddingModels.length>0&&await S.getEnv()==="server"}async function br(){return await C(),f.indexEmbeddings&&f.indexSummary&&j!==void 0&&xe!==void 0&&f.embeddingModels.length>0&&await S.getEnv()==="server"}async function cs(e){if(!await xr()||!we(e))return;let t=await $.readPage(e),r=await N.parseMarkdown(t);if(!r.children)return;let n=r.children.filter(a=>a.type==="Paragraph"),o=[],i=Date.now();for(let a of n){let p=R(a).trim();if(!p||p.length<10||f.indexEmbeddingsExcludeStrings.some(y=>p.includes(y)))continue;let m=await j.generateEmbeddings({text:p}),d=a.from??0,g={ref:`${e}@${d}`,page:e,pos:d,embedding:m,text:p,tag:"embedding"};o.push(g)}await Mt(e,o);let c=(Date.now()-i)/1e3;_("any",`AI: Indexed ${o.length} embedding objects for page ${e} in ${c} seconds`)}async function ls(e){if(!await br()||!we(e))return;let t=await $.readPage(e),r=await N.parseMarkdown(t);if(!r.children)return;let n=Date.now(),o=R(r),i=f.textModels.find(x=>x.name===f.indexSummaryModelName);if(!i)throw new Error(`Could not find summary model ${f.indexSummaryModelName}`);let s=await be(i),c;f.promptInstructions.indexSummaryPrompt!==""?c=f.promptInstructions.indexSummaryPrompt:c=`Provide a concise and informative summary of the above page. The summary should capture the key points and be useful for search purposes. Avoid any formatting or extraneous text. No more than one paragraph. Summary: `;let a=await $e(i.name,o,c),p=Le(a);p||(p=await s.singleMessageChat("Contents of "+e+`: `+o+` -`+c),Re(a,p));let m=await j.generateEmbeddings({text:p}),d={ref:`${e}@0`,page:e,embedding:m,text:p,tag:"aiSummary"};await Ct(e,[d]);let y=(Date.now()-n)/1e3;_("any",`AI: Indexed summary for page ${e} in ${y} seconds`)}async function br({name:e,tree:t}){await C(),Pe(e)&&t.children&&(await yr()&&await oe.send("aiEmbeddingsQueue",e),await xr()&&await oe.send("aiSummaryQueue",e))}async function wr(e){await C();for(let r of e){let n=r.body;console.log(`AI: Generating and indexing embeddings for file ${n}`),await cs(n)}let t=await oe.getQueueStats("aiEmbeddingsQueue");console.log(`AI: Embeddings queue stats: ${JSON.stringify(t)}`)}async function Pr(e){await C();for(let r of e){let n=r.body;console.log(`AI: Generating and indexing summary for ${n}`),await ls(n)}let t=await oe.getQueueStats("aiSummaryQueue");console.log(`AI: Summary queue stats: ${JSON.stringify(t)}`)}async function vt(){return await Mt()?await l("system.invokeFunctionOnServer","index.queryObjects","embedding",{}):await me("embedding",{})}async function Ar(){return await Mt()?await l("system.invokeFunctionOnServer","index.queryObjects","aiSummary",{}):await me("aiSummary",{})}async function Sr(e){if(await C(),!j||!be)throw new Error("No embedding provider found");return await j.generateEmbeddings({text:e})}async function Ae(e){return await l("system.invokeFunctionOnServer","silverbullet-ai.generateEmbeddings",e)}function St(e,t){let r=e.reduce((i,s,c)=>i+s*t[c],0),n=Math.sqrt(e.reduce((i,s)=>i+s*s,0)),o=Math.sqrt(t.reduce((i,s)=>i+s*s,0));return r/(n*o)}async function Et(e,t=10,r=!1){await C(),await S.getEnv()==="server"&&(r=!1);let n=Date.now(),o=typeof e=="string"?await Ae(e):e,i=Date.now();console.log(`searchEmbeddings: Query embedding generation took ${i-n} ms`);let s=Date.now(),c=await vt(),a=Date.now();console.log(`Retrieved ${c.length} embeddings in ${a-s} ms`);let p="",m=0;r&&(p=`Retrieved ${c.length} embeddings in ${a-s} ms +`+c),Re(a,p));let m=await j.generateEmbeddings({text:p}),d={ref:`${e}@0`,page:e,embedding:m,text:p,tag:"aiSummary"};await Mt(e,[d]);let y=(Date.now()-n)/1e3;_("any",`AI: Indexed summary for page ${e} in ${y} seconds`)}async function wr({name:e,tree:t}){await C(),we(e)&&t.children&&(await xr()&&await oe.send("aiEmbeddingsQueue",e),await br()&&await oe.send("aiSummaryQueue",e))}async function Pr(e){await C();for(let r of e){let n=r.body;console.log(`AI: Generating and indexing embeddings for file ${n}`),await cs(n)}let t=await oe.getQueueStats("aiEmbeddingsQueue");console.log(`AI: Embeddings queue stats: ${JSON.stringify(t)}`)}async function Ar(e){await C();for(let r of e){let n=r.body;console.log(`AI: Generating and indexing summary for ${n}`),await ls(n)}let t=await oe.getQueueStats("aiSummaryQueue");console.log(`AI: Summary queue stats: ${JSON.stringify(t)}`)}async function vt(){return await It()?await l("system.invokeFunctionOnServer","index.queryObjects","embedding",{}):await Ct("embedding",{})}async function Sr(){return await It()?await l("system.invokeFunctionOnServer","index.queryObjects","aiSummary",{}):await Ct("aiSummary",{})}async function vr(e){if(await C(),!j||!xe)throw new Error("No embedding provider found");return await j.generateEmbeddings({text:e})}async function Pe(e){return await l("system.invokeFunctionOnServer","silverbullet-ai.generateEmbeddings",e)}function St(e,t){let r=e.reduce((i,s,c)=>i+s*t[c],0),n=Math.sqrt(e.reduce((i,s)=>i+s*s,0)),o=Math.sqrt(t.reduce((i,s)=>i+s*s,0));return r/(n*o)}async function Et(e,t=10,r=!1){await C(),await S.getEnv()==="server"&&(r=!1);let n=Date.now(),o=typeof e=="string"?await Pe(e):e,i=Date.now();console.log(`searchEmbeddings: Query embedding generation took ${i-n} ms`);let s=Date.now(),c=await vt(),a=Date.now();console.log(`Retrieved ${c.length} embeddings in ${a-s} ms`);let p="",m=0;r&&(p=`Retrieved ${c.length} embeddings in ${a-s} ms -`,m=(await u.getText()).length,await u.replaceRange(m,m,p));let d=[],g=Date.now();for(let y=0;y=100)){let P=m+p.length;p=` +`,m=(await u.getText()).length,await u.replaceRange(m,m,p));let d=[],g=Date.now();for(let y=0;y=100)){let P=m+p.length;p=` Processed ${y+1} of ${c.length} embeddings... -`,await u.replaceRange(m,P,p),g=Date.now()}if(r&&y>=c.length-1){let P=m+p.length;await u.replaceRange(m,P,"")}}}if(console.log(`Finished searching embeddings in ${Date.now()-s} ms`),f.indexSummary){let y=Date.now(),x=await Ar(),P=Date.now();console.log(`Retrieved ${x.length} summaries in ${P-y} ms`);let b="",k=0;r&&(b=`Retrieved ${x.length} summaries in ${P-y} ms +`,await u.replaceRange(m,P,p),g=Date.now()}if(r&&y>=c.length-1){let P=m+p.length;await u.replaceRange(m,P,"")}}}if(console.log(`Finished searching embeddings in ${Date.now()-s} ms`),f.indexSummary){let y=Date.now(),x=await Sr(),P=Date.now();console.log(`Retrieved ${x.length} summaries in ${P-y} ms`);let b="",k=0;r&&(b=`Retrieved ${x.length} summaries in ${P-y} ms -`,k=(await u.getText()).length,await u.replaceRange(k,k,b));let J=[],v=Date.now();for(let F=0;F=100)){let E=k+b.length;b=` +`,k=(await u.getText()).length,await u.replaceRange(k,k,b));let J=[],v=Date.now();for(let F=0;F=100)){let E=k+b.length;b=` Processed ${F+1} of ${x.length} summaries... -`,await u.replaceRange(k,E,b),v=Date.now()}if(r&&F>=x.length-1){let E=k+b.length;await u.replaceRange(k,E,"")}}}console.log(`Finished searching summaries in ${Date.now()-y} ms`),d.push(...J)}return d.sort((y,x)=>x.similarity-y.similarity).slice(0,t)}async function vr(e,t=10){await C();let r=await Ae(e);return(await Ar()).map(i=>({page:i.page,ref:i.ref,text:i.text,similarity:St(r,i.embedding)})).sort((i,s)=>s.similarity-i.similarity).slice(0,t)}async function We(e,t=10,r=.15,n=!1){let o;o=await Et(e,-1,n);let i={};for(let c of o)c.similarityp.similarity-a.similarity).slice(0,t);return Object.values(i).sort((c,a)=>a.score-c.score).slice(0,t)}async function Qe(e,t=10){try{let r=await We(e,t),n="";if(r.length>0)for(let o of r){n+=`>>${o.page}<< +`,await u.replaceRange(k,E,b),v=Date.now()}if(r&&F>=x.length-1){let E=k+b.length;await u.replaceRange(k,E,"")}}}console.log(`Finished searching summaries in ${Date.now()-y} ms`),d.push(...J)}return d.sort((y,x)=>x.similarity-y.similarity).slice(0,t)}async function Er(e,t=10){await C();let r=await Pe(e);return(await Sr()).map(i=>({page:i.page,ref:i.ref,text:i.text,similarity:St(r,i.embedding)})).sort((i,s)=>s.similarity-i.similarity).slice(0,t)}async function We(e,t=10,r=.15,n=!1){let o;o=await Et(e,-1,n);let i={};for(let c of o)c.similarityp.similarity-a.similarity).slice(0,t);return Object.values(i).sort((c,a)=>a.score-c.score).slice(0,t)}async function Qe(e,t=10){try{let r=await We(e,t),n="";if(r.length>0)for(let o of r){n+=`>>${o.page}<< `;for(let i of o.children)n+=`> ${i.text} -`}else return"No relevant pages found.";return n}catch(r){return console.error("Error in searchEmbeddingsForChat:",r),"An error occurred during the search."}}function Er(e){return{data:new TextEncoder().encode(""),meta:{name:e,contentType:"text/markdown",size:0,created:0,lastModified:0,perm:"ro"}}}function Tt(e){return{name:e,contentType:"text/markdown",size:-1,created:0,lastModified:0,perm:"ro"}}function Tr(e){return Tt(e)}async function Cr(){let e=await u.getCurrentPage();if(e.startsWith(At)){await C();let t=e.substring(At.length),r=`# Search results for "${t}"`,n=r+` +`}else return"No relevant pages found.";return n}catch(r){return console.error("Error in searchEmbeddingsForChat:",r),"An error occurred during the search."}}function Tr(e){return{data:new TextEncoder().encode(""),meta:{name:e,contentType:"text/markdown",size:0,created:0,lastModified:0,perm:"ro"}}}function Tt(e){return{name:e,contentType:"text/markdown",size:-1,created:0,lastModified:0,perm:"ro"}}function Cr(e){return Tt(e)}async function Mr(){let e=await u.getCurrentPage();if(e.startsWith(At)){await C();let t=e.substring(At.length),r=`# Search results for "${t}"`,n=r+` `;if(!f.indexEmbeddings){n+=`> **warning** Embeddings generation is disabled. `,n+=`> You can enable it in the AI settings. @@ -41,7 +41,7 @@ Processed ${F+1} of ${x.length} summaries... `,await u.setText(n);return}let o=`${r} Searching for "${t}"...`;o+=` -Generating query vector embeddings..`,await u.setText(o);let i=[];try{i=await Ae(t)}catch(a){console.error("Error generating query vector embeddings",a),o+=` +Generating query vector embeddings..`,await u.setText(o);let i=[];try{i=await Pe(t)}catch(a){console.error("Error generating query vector embeddings",a),o+=` > **error** \u26A0\uFE0F Failed to generate query vector embeddings. `,o+=`> ${a} @@ -58,13 +58,13 @@ Searching for similar embeddings...`,await u.setText(o);let s=[];try{s=await We( `);for(let a of s){n+=`## [[${a.page}]] `;for(let p of a.children){let d=p.ref.split("@")[1].padStart(4," ");n+=`> [[${p.ref}|${d}]] | ${p.text} -`}}await u.replaceRange(0,c,n)}}async function Mr(){let e=await u.prompt("Search for: ");e&&await u.navigate({page:`${At}${e}`})}function Ir(e){return e.split("/").slice(0,-1).join("/")}async function _(e,...t){(await S.getEnv()===e||e==="any")&&console.log(...t)}async function Or(e,t){let r=await sr(e);return us(r,t)}async function us(e,t){e.limit||(e.limit=["number",1e3]);let r=`query:${e.querySource}`,n={query:e};t&&(n.variables=t);let o=await he.dispatchEvent(r,n,30*1e3);if(o.length===0)throw new Error(`Unsupported query source '${e.querySource}'`);return o.flat()}async function me(e,t){return await S.invokeFunction("index.queryObjects",e,t)}async function Ct(e,t){return await S.invokeFunction("index.indexObjects",e,t)}async function Ve(e){e||(e=await u.getText());let t=await N.parseMarkdown(e);await V(t,{removeFrontmatterSection:!0}),e=R(t);let r=e.split(` +`}}await u.replaceRange(0,c,n)}}async function Ir(){let e=await u.prompt("Search for: ");e&&await u.navigate({page:`${At}${e}`})}function Or(e){return e.split("/").slice(0,-1).join("/")}async function _(e,...t){(await S.getEnv()===e||e==="any")&&console.log(...t)}async function Ae(e,t){let r=await ar(e);return us(r,t)}async function us(e,t){e.limit||(e.limit=["number",1e3]);let r=`query:${e.querySource}`,n={query:e};t&&(n.variables=t);let o=await ge.dispatchEvent(r,n,30*1e3);if(o.length===0)throw new Error(`Unsupported query source '${e.querySource}'`);return o.flat()}async function Ct(e,t){return await S.invokeFunction("index.queryObjects",e,t)}async function Mt(e,t){return await S.invokeFunction("index.indexObjects",e,t)}async function Ve(e){e||(e=await u.getText());let t=await N.parseMarkdown(e);await V(t,{removeFrontmatterSection:!0}),e=R(t);let r=e.split(` `),n=[],o="user",i="";return r.forEach(s=>{if(s.trim()==="")return;let c=s.match(/^\*\*(\w+)\*\*:/);if(c){let a=c[1].toLowerCase();o&&o!==a&&i.trim()!==""&&(n.push({role:o,content:i.trim()}),i=""),o=a,i+=s.replace(/^\*\*(\w+)\*\*:/,"").trim()+` `}else o&&(i+=s.trim()+` -`)}),i&&o&&n.push({role:o,content:i.trim()}),n}async function kr(){try{let e=await l("system.getVersion"),[t,r,n]=e.split(".").map(Number),[o,i,s]="0.7.2".split(".").map(Number);return t>o||t===o&&r>i||t===o&&r===i&&n>=s}catch{return!1}}async function Mt(){try{return(await S.listSyscalls()).some(t=>t.name==="system.invokeFunctionOnServer")}catch{return!1}}async function ue(e,t){let r=[],n,o;try{n=await u.getCurrentPage(),o=await $.getPageMeta(n)}catch(i){return console.error("Error fetching page metadata",i),await u.flashNotification("Error fetching page metadata","error"),[]}for(let i of e){if(i.role==="assistant"||i.role==="system"){r.push(i);continue}let s=await N.parseMarkdown(i.content),c=await ar([],s);if(i.content=i.content.replace(/\[enrich:\s*(false|true)\s*\]\s*/g,""),c.enrich!==void 0&&c.enrich===!1){console.log("Skipping message enrichment due to enrich=false attribute",c),r.push(i);continue}let a=i.content;if(i.role==="user"&&(o?(console.log("Rendering template",i.content,o),a=await ne.renderTemplate(i.content,o,{page:o,...t})):console.log("No page metadata found, skipping template rendering")),f.chat.searchEmbeddings&&f.indexEmbeddings){let g=await Qe(a);g!=="No relevant pages found."&&(a+=` +`)}),i&&o&&n.push({role:o,content:i.trim()}),n}async function kr(){try{let e=await l("system.getVersion"),[t,r,n]=e.split(".").map(Number),[o,i,s]="0.7.2".split(".").map(Number);return t>o||t===o&&r>i||t===o&&r===i&&n>=s}catch{return!1}}async function It(){try{return(await S.listSyscalls()).some(t=>t.name==="system.invokeFunctionOnServer")}catch{return!1}}async function ue(e,t){let r=[],n,o;try{n=await u.getCurrentPage(),o=await $.getPageMeta(n)}catch(i){return console.error("Error fetching page metadata",i),await u.flashNotification("Error fetching page metadata","error"),[]}for(let i of e){if(i.role==="assistant"||i.role==="system"){r.push(i);continue}let s=await N.parseMarkdown(i.content),c=await cr([],s);if(i.content=i.content.replace(/\[enrich:\s*(false|true)\s*\]\s*/g,""),c.enrich!==void 0&&c.enrich===!1){console.log("Skipping message enrichment due to enrich=false attribute",c),r.push(i);continue}let a=i.content;if(i.role==="user"&&(o?(console.log("Rendering template",i.content,o),a=await ne.renderTemplate(i.content,o,{page:o,...t})):console.log("No page metadata found, skipping template rendering")),f.chat.searchEmbeddings&&f.indexEmbeddings){let g=await Qe(a);g!=="No relevant pages found."&&(a+=` The following pages were found to be relevant to the question. You can use them as context to answer the question. Only partial content is shown. Ask for the whole page if needed. Page name is between >> and <<. -`,a+=g)}if(f.chat.parseWikiLinks&&(a=await ps(a)),f.chat.bakeMessages){let g=await N.parseMarkdown(a),y=await S.invokeFunction("markdown.expandCodeWidgets",g,"");a=R(y).trim()}let m=(await he.dispatchEvent("ai:enrichMessage",{enrichedContent:a,message:i})).flat().concat(f.chat.customEnrichFunctions),d=[...new Set(m)];console.log("Received custom enrich message functions",d);for(let g of d)a=await S.invokeSpaceFunction(g,a);r.push({...i,content:a})}return r}async function ps(e){let t=[],r=e,n=/\[\[([^\]]+)\]\]/g,o,i=!1;for(;(o=n.exec(e))!==null;){let s=o[1];if(!t.includes(s)){i||(r+=` +`,a+=g)}if(f.chat.parseWikiLinks&&(a=await ps(a)),f.chat.bakeMessages){let g=await N.parseMarkdown(a),y=await S.invokeFunction("markdown.expandCodeWidgets",g,"");a=R(y).trim()}let m=(await ge.dispatchEvent("ai:enrichMessage",{enrichedContent:a,message:i})).flat().concat(f.chat.customEnrichFunctions),d=[...new Set(m)];console.log("Received custom enrich message functions",d);for(let g of d)a=await S.invokeSpaceFunction(g,a);r.push({...i,content:a})}return r}async function ps(e){let t=[],r=e,n=/\[\[([^\]]+)\]\]/g,o,i=!1;for(;(o=n.exec(e))!==null;){let s=o[1];if(!t.includes(s)){i||(r+=` Base your answer on the content of the following referenced pages (referenced above using the >>page name<< format). In these listings ~~~ is used to mark the page's content start and end. If context is missing, always ask me to link directly to a page mentioned in the context.`,i=!0);try{let c=await $.readPage(s);t.push(s),r+=` @@ -72,34 +72,34 @@ Content of the [[${s}]] page: ~~~ ${c} ~~~ -`}catch(c){console.error(`Error fetching page '${s}':`,c)}}}return r=r.replace(n,">>$1<<"),r}async function Nr(e,t={},r={}){try{let n=await N.parseMarkdown(e),o=await V(n,{removeFrontmatterSection:!0,removeTags:["template"]});e=R(n).trimStart();let i;return o.frontmatter&&(typeof o.frontmatter=="string"?i=o.frontmatter:i=await B.stringify(o.frontmatter),i=await ne.renderTemplate(i,t,r)),{frontmatter:o,renderedFrontmatter:i,text:await ne.renderTemplate(e,t,r)}}catch(n){throw console.error("Error rendering template",n),n}}async function Fr(e){return kr()?{options:(await me("template",{filter:["attr",["attr","aiprompt"],"slashCommand"]},5)).map(r=>{let n=r.aiprompt;return{label:n.slashCommand,detail:n.description||r.description,order:n.order||0,templatePage:r.ref,pageName:e.pageName,invoke:"silverbullet-ai.insertAiPromptFromTemplate"}})}:void 0}async function Rr(e){let t;if(!e||!e.templatePage){let E=await me("template",{filter:["attr",["attr","aiprompt"],"description"]});t=await u.filterBox("Prompt Template",E.map(q=>{let Z=q.ref.split("/").pop();return{...q,description:q.aiprompt.description||q.ref,name:q.aiprompt.displayName||Z,systemPrompt:q.aiprompt.systemPrompt||"You are an AI note assistant. Please follow the prompt instructions.",insertAt:q.aiprompt.insertAt||"cursor",chat:q.aiprompt.chat||!1,enrichMessages:q.aiprompt.enrichMessages||!1,postProcessors:q.aiprompt.postProcessors||[]}}),"Select the template to use as the prompt. The prompt will be rendered and sent to the LLM model.")}else{console.log("selectedTemplate from slash completion: ",e);let E=await $.readPage(e.templatePage),q=await N.parseMarkdown(E),{aiprompt:Z}=await V(q);console.log("templatePage from slash completion: ",E),t={ref:e.templatePage,systemPrompt:Z.systemPrompt||Z.system||"You are an AI note assistant. Please follow the prompt instructions.",insertAt:Z.insertAt||"cursor",chat:Z.chat||!1,enrichMessages:Z.enrichMessages||!1,postProcessors:Z.postProcessors||[]}}if(!t){await u.flashNotification("No template selected");return}console.log("User selected prompt template: ",t);let r=["cursor","page-start","page-end","start-of-line","end-of-line","start-of-item","end-of-item","new-line-above","new-line-below","replace-line","replace-paragraph","replace-selection","replace-smart"];if(!r.includes(t.insertAt)){console.error(`Invalid insertAt value: ${t.insertAt}. It must be one of ${r.join(", ")}`),await u.flashNotification(`Invalid insertAt value: ${t.insertAt}. Please select a valid option.`,"error");return}await C();let n,o,i;try{n=await $.readPage(t.ref),o=await u.getCurrentPage(),i=await $.getPageMeta(o)}catch(E){console.error("Error fetching template details or page metadata",E),await u.flashNotification("Error fetching template details or page metadata","error");return}let s,c,a,p,m,d,g,y,x,P,b,k,J;try{s=await u.getText(),a=await u.getCursor();let E=s.split(` +`}catch(c){console.error(`Error fetching page '${s}':`,c)}}}return r=r.replace(n,">>$1<<"),r}async function Nr(e,t={},r={}){try{let n=await N.parseMarkdown(e),o=await V(n,{removeFrontmatterSection:!0,removeTags:["template"]});e=R(n).trimStart();let i;return o.frontmatter&&(typeof o.frontmatter=="string"?i=o.frontmatter:i=await B.stringify(o.frontmatter),i=await ne.renderTemplate(i,t,r)),{frontmatter:o,renderedFrontmatter:i,text:await ne.renderTemplate(e,t,r)}}catch(n){throw console.error("Error rendering template",n),n}}async function Fr(e){return kr()?{options:(await Ae("template where aiprompt and aiprompt.slashCommand")).map(r=>{let n=r.aiprompt;return{label:n.slashCommand,detail:n.description||r.description,order:n.order||0,templatePage:r.ref,pageName:e.pageName,invoke:"silverbullet-ai.insertAiPromptFromTemplate"}})}:void 0}async function Rr(e){let t;if(!e||!e.templatePage){let E=await Ae("template where aiprompt");t=await u.filterBox("Prompt Template",E.map(q=>{let Z=q.ref.split("/").pop();return{...q,description:q.aiprompt.description||q.ref,name:q.aiprompt.displayName||Z,systemPrompt:q.aiprompt.systemPrompt||"You are an AI note assistant. Please follow the prompt instructions.",insertAt:q.aiprompt.insertAt||"cursor",chat:q.aiprompt.chat||!1,enrichMessages:q.aiprompt.enrichMessages||!1,postProcessors:q.aiprompt.postProcessors||[]}}),"Select the template to use as the prompt. The prompt will be rendered and sent to the LLM model.")}else{console.log("selectedTemplate from slash completion: ",e);let E=await $.readPage(e.templatePage),q=await N.parseMarkdown(E),{aiprompt:Z}=await V(q);console.log("templatePage from slash completion: ",E),t={ref:e.templatePage,systemPrompt:Z.systemPrompt||Z.system||"You are an AI note assistant. Please follow the prompt instructions.",insertAt:Z.insertAt||"cursor",chat:Z.chat||!1,enrichMessages:Z.enrichMessages||!1,postProcessors:Z.postProcessors||[]}}if(!t){await u.flashNotification("No template selected");return}console.log("User selected prompt template: ",t);let r=["cursor","page-start","page-end","start-of-line","end-of-line","start-of-item","end-of-item","new-line-above","new-line-below","replace-line","replace-paragraph","replace-selection","replace-smart"];if(!r.includes(t.insertAt)){console.error(`Invalid insertAt value: ${t.insertAt}. It must be one of ${r.join(", ")}`),await u.flashNotification(`Invalid insertAt value: ${t.insertAt}. Please select a valid option.`,"error");return}await C();let n,o,i;try{n=await $.readPage(t.ref),o=await u.getCurrentPage(),i=await $.getPageMeta(o)}catch(E){console.error("Error fetching template details or page metadata",E),await u.flashNotification("Error fetching template details or page metadata","error");return}let s,c,a,p,m,d,g,y,x,P,b,k,J;try{s=await u.getText(),a=await u.getCursor();let E=s.split(` `);c=s.substring(0,a).split(` `).length,p=a-(s.substring(0,a).split(` -`).pop()?.length||0),m=p+E[c-1].length}catch(E){console.error("Error fetching current page text or cursor position",E),await u.flashNotification("Error fetching current page text or cursor position","error");return}try{(t.insertAt==="start-of-item"||t.insertAt==="end-of-item"||t.insertAt==="replace-smart")&&(d=await S.invokeFunction("editor.determineItemBounds",s,a,void 0,!0),g=s.slice(d.from,d.to),y=await S.invokeFunction("editor.determineItemBounds",s,a,0,!0),x=s.slice(y.from,y.to))}catch(E){console.error("Error fetching current item",E)}try{(t.insertAt==="replace-paragraph"||t.insertAt==="replace-smart")&&(P=gr(s,a))}catch(E){console.error("Error fetching current paragraph",E),await u.flashNotification("Error fetching current paragraph","error");return}try{(t.insertAt=="replace-selection"||t.insertAt=="replace-smart")&&(b=await dt())}catch(E){console.error("Error fetching selected text",E)}let v;switch(t.insertAt){case"page-start":v=0;break;case"page-end":v=await se();break;case"frontmatter":await u.flashNotification("rendering in frontmatter not supported yet","error");break;case"modal":break;case"replace":break;case"replace-line":v=p,await u.replaceRange(p,m,"");break;case"replace-selection":b?.text?(v=b.from,await u.replaceRange(b.from,b.to,"")):v=await u.getCursor();break;case"replace-paragraph":P?.text?(v=P.from,await u.replaceRange(P.from,P.to,"")):await u.flashNotification("Error: current paragraph is undefined","error");break;case"replace-smart":if(b?.text)k="selected-text",J=b.text,v=b.from,await u.replaceRange(b.from,b.to,"");else if(g&&d)k="current-item",J=g,v=d.from,await u.replaceRange(d.from,d.to,` +`).pop()?.length||0),m=p+E[c-1].length}catch(E){console.error("Error fetching current page text or cursor position",E),await u.flashNotification("Error fetching current page text or cursor position","error");return}try{(t.insertAt==="start-of-item"||t.insertAt==="end-of-item"||t.insertAt==="replace-smart")&&(d=await S.invokeFunction("editor.determineItemBounds",s,a,void 0,!0),g=s.slice(d.from,d.to),y=await S.invokeFunction("editor.determineItemBounds",s,a,0,!0),x=s.slice(y.from,y.to))}catch(E){console.error("Error fetching current item",E)}try{(t.insertAt==="replace-paragraph"||t.insertAt==="replace-smart")&&(P=hr(s,a))}catch(E){console.error("Error fetching current paragraph",E),await u.flashNotification("Error fetching current paragraph","error");return}try{(t.insertAt=="replace-selection"||t.insertAt=="replace-smart")&&(b=await dt())}catch(E){console.error("Error fetching selected text",E)}let v;switch(t.insertAt){case"page-start":v=0;break;case"page-end":v=await se();break;case"frontmatter":await u.flashNotification("rendering in frontmatter not supported yet","error");break;case"modal":break;case"replace":break;case"replace-line":v=p,await u.replaceRange(p,m,"");break;case"replace-selection":b?.text?(v=b.from,await u.replaceRange(b.from,b.to,"")):v=await u.getCursor();break;case"replace-paragraph":P?.text?(v=P.from,await u.replaceRange(P.from,P.to,"")):await u.flashNotification("Error: current paragraph is undefined","error");break;case"replace-smart":if(b?.text)k="selected-text",J=b.text,v=b.from,await u.replaceRange(b.from,b.to,"");else if(g&&d)k="current-item",J=g,v=d.from,await u.replaceRange(d.from,d.to,` `);else if(P?.text)k="current-paragraph",J=P.text,v=P.from,await u.replaceRange(P.from,P.to,"");else{await u.flashNotification("Error: replace-smart: no text selected, current paragraph, or current item","error");return}console.log("smartReplaceType: ",k),console.log("smartReplaceText: ",J);break;case"start-of-line":v=p;break;case"end-of-line":v=m;break;case"new-line-above":v=p,await u.insertAtPos(` `,v),v+=1;break;case"new-line-below":v=m,await u.insertAtPos(` `,v),v+=1;break;case"start-of-item":v=d.from;break;case"end-of-item":v=d.to;break;case"cursor":default:v=await u.getCursor()}v===void 0&&(v=await se()),console.log("templatetext: ",n);let F=[],X={page:i,currentItemText:g,currentLineNumber:c,lineStartPos:p,lineEndPos:m,currentPageText:s,parentItemText:x,selectedText:b?.text,currentParagraph:P?.text,smartReplaceType:k,smartReplaceText:J};if(t.chat)F=await Ve(n),t.systemPrompt&&F.unshift({role:"system",content:t.systemPrompt}),t.chat&&t.enrichMessages&&(F=await ue(F,X));else{let E=await Nr(n,i,X);console.log("Rendered template:",E),t.systemPrompt&&F.push({role:"system",content:t.systemPrompt}),F.push({role:"user",content:E.text})}console.log("Messages: ",F),await O.streamChatIntoEditor({messages:F,stream:!0,postProcessors:t.postProcessors},v)}var Ql=new TextEncoder;function Lr(e){let t=atob(e),r=t.length,n=new Uint8Array(r);for(let o=0;o0&&`\0\r \x85\u2028\u2029`.indexOf(this.buffer.charAt(o-1))===-1;)if(o-=1,this.position-o>r/2-1){n=" ... ",o+=5;break}let i="",s=this.position;for(;sr/2-1){i=" ... ",s-=5;break}let c=this.buffer.slice(o,s);return`${G(" ",t)}${n}${c}${i} ${G(" ",t+this.position-o+n.length)}^`}toString(t){let r,n="";return this.name&&(n+=`in "${this.name}" `),n+=`at line ${this.line+1}, column ${this.column+1}`,t||(r=this.getSnippet(),r&&(n+=`: -${r}`)),n}};function It(e,t,r){let n=[];for(let o of e.include)r=It(o,t,r);for(let o of e[t]){for(let i=0;i!n.includes(i))}function ms(...e){let t={fallback:{},mapping:{},scalar:{},sequence:{}};for(let r of e)for(let n of r)n.kind!==null&&(t[n.kind][n.tag]=t.fallback[n.tag]=n);return t}var K=class e{static SCHEMA_DEFAULT;implicit;explicit;include;compiledImplicit;compiledExplicit;compiledTypeMap;constructor(t){this.explicit=t.explicit||[],this.implicit=t.implicit||[],this.include=t.include||[];for(let r of this.implicit)if(r.loadKind&&r.loadKind!=="scalar")throw new ee("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");this.compiledImplicit=It(this,"implicit",[]),this.compiledExplicit=It(this,"explicit",[]),this.compiledTypeMap=ms(this.compiledImplicit,this.compiledExplicit)}extend(t){return new e({implicit:[...new Set([...this.implicit,...t?.implicit??[]])],explicit:[...new Set([...this.explicit,...t?.explicit??[]])],include:[...new Set([...this.include,...t?.include??[]])]})}static create(){}};var A=class{tag;kind=null;instanceOf;predicate;represent;defaultStyle;styleAliases;loadKind;constructor(t,r){this.tag=t,r&&(this.kind=r.kind,this.resolve=r.resolve||(()=>!0),this.construct=r.construct||(n=>n),this.instanceOf=r.instanceOf,this.predicate=r.predicate,this.represent=r.represent,this.defaultStyle=r.defaultStyle,this.styleAliases=r.styleAliases)}resolve=()=>!0;construct=t=>t};var Ot=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= -\r`;function ds(e){if(e===null)return!1;let t,r=0,n=e.length,o=Ot;for(let i=0;i64)){if(t<0)return!1;r+=6}return r%8===0}function fs(e){let t=e.replace(/[\r\n=]/g,""),r=t.length,n=Ot,o=[],i=0;for(let c=0;c>16&255),o.push(i>>8&255),o.push(i&255)),i=i<<6|n.indexOf(t.charAt(c));let s=r%4*6;return s===0?(o.push(i>>16&255),o.push(i>>8&255),o.push(i&255)):s===18?(o.push(i>>10&255),o.push(i>>2&255)):s===12&&o.push(i>>4&255),new Uint8Array(o)}function gs(e){let t=e.length,r=Ot,n="",o=0;for(let s=0;s>18&63],n+=r[o>>12&63],n+=r[o>>6&63],n+=r[o&63]),o=(o<<8)+e[s];let i=t%3;return i===0?(n+=r[o>>18&63],n+=r[o>>12&63],n+=r[o>>6&63],n+=r[o&63]):i===2?(n+=r[o>>10&63],n+=r[o>>4&63],n+=r[o<<2&63],n+=r[64]):i===1&&(n+=r[o>>2&63],n+=r[o<<4&63],n+=r[64],n+=r[64]),n}function hs(e){return e instanceof Uint8Array}var kt=new A("tag:yaml.org,2002:binary",{construct:fs,kind:"scalar",predicate:hs,represent:gs,resolve:ds});function ys(e){let t=e.length;return t===4&&(e==="true"||e==="True"||e==="TRUE")||t===5&&(e==="false"||e==="False"||e==="FALSE")}function xs(e){return e==="true"||e==="True"||e==="TRUE"}var Nt=new A("tag:yaml.org,2002:bool",{construct:xs,defaultStyle:"lowercase",kind:"scalar",predicate:$r,represent:{lowercase(e){return e?"true":"false"},uppercase(e){return e?"TRUE":"FALSE"},camelcase(e){return e?"True":"False"}},resolve:ys});var bs=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ws(e){return!(!bs.test(e)||e[e.length-1]==="_")}function Ps(e){let t=e.replace(/_/g,"").toLowerCase(),r=t[0]==="-"?-1:1,n=[];if("+-".indexOf(t[0])>=0&&(t=t.slice(1)),t===".inf")return r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;if(t.indexOf(":")>=0){t.split(":").forEach(s=>{n.unshift(parseFloat(s))});let o=0,i=1;return n.forEach(s=>{o+=s*i,i*=60}),r*o}return r*parseFloat(t)}var As=/^[-+]?[0-9]+e/;function Ss(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(Se(e))return"-0.0";let r=e.toString(10);return As.test(r)?r.replace("e",".e"):r}function vs(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||Se(e))}var Ft=new A("tag:yaml.org,2002:float",{construct:Ps,defaultStyle:"lowercase",kind:"scalar",predicate:vs,represent:Ss,resolve:ws});function Ur(e){let t=new Function(`return ${e}`)();if(!(t instanceof Function))throw new TypeError(`Expected function but got ${typeof t}: ${e}`);return t}var Es=new A("tag:yaml.org,2002:js/function",{kind:"scalar",resolve(e){if(e===null)return!1;try{return Ur(`${e}`),!0}catch{return!1}},construct(e){return Ur(e)},predicate(e){return e instanceof Function},represent(e){return e.toString()}});function Ts(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function Cs(e){return 48<=e&&e<=55}function Ms(e){return 48<=e&&e<=57}function Is(e){let t=e.length,r=0,n=!1;if(!t)return!1;let o=e[r];if((o==="-"||o==="+")&&(o=e[++r]),o==="0"){if(r+1===t)return!0;if(o=e[++r],o==="b"){for(r++;r{r.unshift(parseInt(c,10))});let i=0,s=1;return r.forEach(c=>{i+=c*s,s*=60}),n*i}return n*parseInt(t,10)}function ks(e){return Object.prototype.toString.call(e)==="[object Number]"&&e%1===0&&!Se(e)}var Rt=new A("tag:yaml.org,2002:int",{construct:Os,defaultStyle:"decimal",kind:"scalar",predicate:ks,represent:{binary(e){return e>=0?`0b${e.toString(2)}`:`-0b${e.toString(2).slice(1)}`},octal(e){return e>=0?`0${e.toString(8)}`:`-0${e.toString(8).slice(1)}`},decimal(e){return e.toString(10)},hexadecimal(e){return e>=0?`0x${e.toString(16).toUpperCase()}`:`-0x${e.toString(16).toUpperCase().slice(1)}`}},resolve:Is,styleAliases:{binary:[2,"bin"],decimal:[10,"dec"],hexadecimal:[16,"hex"],octal:[8,"oct"]}});var Lt=new A("tag:yaml.org,2002:map",{construct(e){return e!==null?e:{}},kind:"mapping"});function Ns(e){return e==="<<"||e===null}var $t=new A("tag:yaml.org,2002:merge",{kind:"scalar",resolve:Ns});function Fs(e){let t=e.length;return t===1&&e==="~"||t===4&&(e==="null"||e==="Null"||e==="NULL")}function Rs(){return null}function Ls(e){return e===null}var _t=new A("tag:yaml.org,2002:null",{construct:Rs,defaultStyle:"lowercase",kind:"scalar",predicate:Ls,represent:{canonical(){return"~"},lowercase(){return"null"},uppercase(){return"NULL"},camelcase(){return"Null"}},resolve:Fs});var{hasOwn:$s}=Object,_s=Object.prototype.toString;function Ds(e){let t=[],r="",n=!1;for(let o of e){if(n=!1,_s.call(o)!=="[object Object]")return!1;for(r in o)if($s(o,r))if(!n)n=!0;else return!1;if(!n)return!1;if(t.indexOf(r)===-1)t.push(r);else return!1}return!0}function Us(e){return e!==null?e:[]}var Dt=new A("tag:yaml.org,2002:omap",{construct:Us,kind:"sequence",resolve:Ds});var js=Object.prototype.toString;function qs(e){let t=Array.from({length:e.length});for(let r=0;r[\s\S]+)\/(?[gismuy]*)$/,qt=new A("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve(e){if(e===null||!e.length)return!1;let t=`${e}`;if(t.charAt(0)==="/"){if(!jt.test(e))return!1;let r=[...t.match(jt)?.groups?.modifiers??""];if(new Set(r).size"u"},represent(){return""}});var Wt=new K({explicit:[Gt,Bt,Lt]});var Qt=new K({implicit:[_t,Nt,Rt,Ft],include:[Wt]});var Vt=new K({include:[Qt]});var ve=new K({explicit:[kt,Dt,Ut,Kt],implicit:[Ht,$t],include:[Vt]});var Vs=new K({explicit:[qt,Yt],include:[ve]});var Ee=class{constructor(t=ve){this.schema=t}};var Je=class extends Ee{constructor(r,{filename:n,schema:o,onWarning:i,legacy:s=!1,json:c=!1,listener:a=null}){super(o);this.input=r;this.filename=n,this.onWarning=i,this.legacy=s,this.json=c,this.listener=a,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=r.length}documents=[];length;lineIndent=0;lineStart=0;position=0;line=0;filename;onWarning;legacy;json;listener;implicitTypes;typeMap;version;checkLineBreaks;tagMap;anchorMap;tag;anchor;kind;result=""};var{hasOwn:re}=Object,Xe=1,Qr=2,Vr=3,Ze=4,zt=1,zs=2,Br=3,Js=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Xs=/[\x85\u2028\u2029]/,Zs=/[,\[\]\{\}]/,zr=/^(?:!|!!|![a-z\-]+!)$/i,Jr=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Kr(e){return Object.prototype.toString.call(e)}function W(e){return e===10||e===13}function ae(e){return e===9||e===32}function D(e){return e===9||e===32||e===10||e===13}function de(e){return e===44||e===91||e===93||e===123||e===125}function ea(e){if(48<=e&&e<=57)return e-48;let t=e|32;return 97<=t&&t<=102?t-97+10:-1}function ta(e){return e===120?2:e===117?4:e===85?8:0}function ra(e){return 48<=e&&e<=57?e-48:-1}function Gr(e){return e===48?"\0":e===97?"\x07":e===98?"\b":e===116||e===9?" ":e===110?` -`:e===118?"\v":e===102?"\f":e===114?"\r":e===101?"\x1B":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"\x85":e===95?"\xA0":e===76?"\u2028":e===80?"\u2029":""}function na(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}var Xr=Array.from({length:256}),Zr=Array.from({length:256});for(let e=0;e<256;e++)Xr[e]=Gr(e)?1:0,Zr[e]=Gr(e);function en(e,t){return new ee(t,new ze(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function h(e,t){throw en(e,t)}function et(e,t){e.onWarning&&e.onWarning.call(null,en(e,t))}var Hr={YAML(e,t,...r){if(e.version!==null)return h(e,"duplication of %YAML directive");if(r.length!==1)return h(e,"YAML directive accepts exactly one argument");let n=/^([0-9]+)\.([0-9]+)$/.exec(r[0]);if(n===null)return h(e,"ill-formed argument of the YAML directive");let o=parseInt(n[1],10),i=parseInt(n[2],10);if(o!==1)return h(e,"unacceptable YAML version of the document");if(e.version=r[0],e.checkLineBreaks=i<2,i!==1&&i!==2)return et(e,"unsupported YAML version of the document")},TAG(e,t,...r){if(r.length!==2)return h(e,"TAG directive accepts exactly two arguments");let n=r[0],o=r[1];if(!zr.test(n))return h(e,"ill-formed tag handle (first argument) of the TAG directive");if(e.tagMap&&re(e.tagMap,n))return h(e,`there is a previously declared suffix for "${n}" tag handle`);if(!Jr.test(o))return h(e,"ill-formed tag prefix (second argument) of the TAG directive");typeof e.tagMap>"u"&&(e.tagMap=Object.create(null)),e.tagMap[n]=o}};function te(e,t,r,n){let o;if(t1&&(e.result+=G(` -`,t-1))}function oa(e,t,r){let n=e.kind,o=e.result,i=e.input.charCodeAt(e.position);if(D(i)||de(i)||i===35||i===38||i===42||i===33||i===124||i===62||i===39||i===34||i===37||i===64||i===96)return!1;let s;if((i===63||i===45)&&(s=e.input.charCodeAt(e.position+1),D(s)||r&&de(s)))return!1;e.kind="scalar",e.result="";let c,a=c=e.position,p=!1,m=0;for(;i!==0;){if(i===58){if(s=e.input.charCodeAt(e.position+1),D(s)||r&&de(s))break}else if(i===35){let d=e.input.charCodeAt(e.position-1);if(D(d))break}else{if(e.position===e.lineStart&&tt(e)||r&&de(i))break;if(W(i)){m=e.line;let d=e.lineStart,g=e.lineIndent;if(I(e,!1,-1),e.lineIndent>=t){p=!0,i=e.input.charCodeAt(e.position);continue}else{e.position=c,e.line=m,e.lineStart=d,e.lineIndent=g;break}}}p&&(te(e,a,c,!1),Xt(e,e.line-m),a=c=e.position,p=!1),ae(i)||(c=e.position+1),i=e.input.charCodeAt(++e.position)}return te(e,a,c,!1),e.result?!0:(e.kind=n,e.result=o,!1)}function ia(e,t){let r,n,o;if(r=e.input.charCodeAt(e.position),r!==39)return!1;for(e.kind="scalar",e.result="",e.position++,n=o=e.position;(r=e.input.charCodeAt(e.position))!==0;)if(r===39)if(te(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),r===39)n=e.position,e.position++,o=e.position;else return!0;else if(W(r))te(e,n,o,!0),Xt(e,I(e,!1,t)),n=o=e.position;else{if(e.position===e.lineStart&&tt(e))return h(e,"unexpected end of the document within a single quoted scalar");e.position++,o=e.position}return h(e,"unexpected end of the stream within a single quoted scalar")}function sa(e,t){let r=e.input.charCodeAt(e.position);if(r!==34)return!1;e.kind="scalar",e.result="",e.position++;let n,o=n=e.position,i;for(;(r=e.input.charCodeAt(e.position))!==0;){if(r===34)return te(e,o,e.position,!0),e.position++,!0;if(r===92){if(te(e,o,e.position,!0),r=e.input.charCodeAt(++e.position),W(r))I(e,!1,t);else if(r<256&&Xr[r])e.result+=Zr[r],e.position++;else if((i=ta(r))>0){let s=i,c=0;for(;s>0;s--)if(r=e.input.charCodeAt(++e.position),(i=ea(r))>=0)c=(c<<4)+i;else return h(e,"expected hexadecimal character");e.result+=na(c),e.position++}else return h(e,"unknown escape sequence");o=n=e.position}else if(W(r))te(e,o,n,!0),Xt(e,I(e,!1,t)),o=n=e.position;else{if(e.position===e.lineStart&&tt(e))return h(e,"unexpected end of the document within a double quoted scalar");e.position++,n=e.position}}return h(e,"unexpected end of the stream within a double quoted scalar")}function aa(e,t){let r=e.input.charCodeAt(e.position),n,o=!0,i={};if(r===91)n=93,o=!1,i=[];else if(r===123)n=125;else return!1;e.anchor!==null&&typeof e.anchor<"u"&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=i),r=e.input.charCodeAt(++e.position);let s=e.tag,c=e.anchor,a=!0,p,m,d=m=p=null,g,y=g=!1,x=0,P=0,b=Object.create(null);for(;r!==0;){if(I(e,!0,t),r=e.input.charCodeAt(e.position),r===n)return e.position++,e.tag=s,e.anchor=c,e.kind=o?"mapping":"sequence",e.result=i,!0;if(!a)return h(e,"missed comma between flow collection entries");d=m=p=null,y=g=!1,r===63&&(x=e.input.charCodeAt(e.position+1),D(x)&&(y=g=!0,e.position++,I(e,!0,t))),P=e.line,ge(e,t,Xe,!1,!0),d=e.tag||null,m=e.result,I(e,!0,t),r=e.input.charCodeAt(e.position),(g||e.line===P)&&r===58&&(y=!0,r=e.input.charCodeAt(++e.position),I(e,!0,t),ge(e,t,Xe,!1,!0),p=e.result),o?fe(e,i,b,d,m,p):y?i.push(fe(e,null,b,d,m,p)):i.push(m),I(e,!0,t),r=e.input.charCodeAt(e.position),r===44?(a=!0,r=e.input.charCodeAt(++e.position)):a=!1}return h(e,"unexpected end of the stream within a flow collection")}function ca(e,t){let r=zt,n=!1,o=!1,i=t,s=0,c=!1,a=e.input.charCodeAt(e.position),p=!1;if(a===124)p=!1;else if(a===62)p=!0;else return!1;e.kind="scalar",e.result="";let m=0;for(;a!==0;)if(a=e.input.charCodeAt(++e.position),a===43||a===45)if(zt===r)r=a===43?Br:zs;else return h(e,"repeat of a chomping mode identifier");else if((m=ra(a))>=0){if(m===0)return h(e,"bad explicit indentation width of a block scalar; it cannot be less than one");if(!o)i=t+m-1,o=!0;else return h(e,"repeat of an indentation width identifier")}else break;if(ae(a)){do a=e.input.charCodeAt(++e.position);while(ae(a));if(a===35)do a=e.input.charCodeAt(++e.position);while(!W(a)&&a!==0)}for(;a!==0;){for(Jt(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!o||e.lineIndenti&&(i=e.lineIndent),W(a)){s++;continue}if(e.lineIndent!n.includes(i))}function ms(...e){let t={fallback:{},mapping:{},scalar:{},sequence:{}};for(let r of e)for(let n of r)n.kind!==null&&(t[n.kind][n.tag]=t.fallback[n.tag]=n);return t}var K=class e{static SCHEMA_DEFAULT;implicit;explicit;include;compiledImplicit;compiledExplicit;compiledTypeMap;constructor(t){this.explicit=t.explicit||[],this.implicit=t.implicit||[],this.include=t.include||[];for(let r of this.implicit)if(r.loadKind&&r.loadKind!=="scalar")throw new ee("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");this.compiledImplicit=Ot(this,"implicit",[]),this.compiledExplicit=Ot(this,"explicit",[]),this.compiledTypeMap=ms(this.compiledImplicit,this.compiledExplicit)}extend(t){return new e({implicit:[...new Set([...this.implicit,...t?.implicit??[]])],explicit:[...new Set([...this.explicit,...t?.explicit??[]])],include:[...new Set([...this.include,...t?.include??[]])]})}static create(){}};var A=class{tag;kind=null;instanceOf;predicate;represent;defaultStyle;styleAliases;loadKind;constructor(t,r){this.tag=t,r&&(this.kind=r.kind,this.resolve=r.resolve||(()=>!0),this.construct=r.construct||(n=>n),this.instanceOf=r.instanceOf,this.predicate=r.predicate,this.represent=r.represent,this.defaultStyle=r.defaultStyle,this.styleAliases=r.styleAliases)}resolve=()=>!0;construct=t=>t};var kt=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= +\r`;function ds(e){if(e===null)return!1;let t,r=0,n=e.length,o=kt;for(let i=0;i64)){if(t<0)return!1;r+=6}return r%8===0}function fs(e){let t=e.replace(/[\r\n=]/g,""),r=t.length,n=kt,o=[],i=0;for(let c=0;c>16&255),o.push(i>>8&255),o.push(i&255)),i=i<<6|n.indexOf(t.charAt(c));let s=r%4*6;return s===0?(o.push(i>>16&255),o.push(i>>8&255),o.push(i&255)):s===18?(o.push(i>>10&255),o.push(i>>2&255)):s===12&&o.push(i>>4&255),new Uint8Array(o)}function gs(e){let t=e.length,r=kt,n="",o=0;for(let s=0;s>18&63],n+=r[o>>12&63],n+=r[o>>6&63],n+=r[o&63]),o=(o<<8)+e[s];let i=t%3;return i===0?(n+=r[o>>18&63],n+=r[o>>12&63],n+=r[o>>6&63],n+=r[o&63]):i===2?(n+=r[o>>10&63],n+=r[o>>4&63],n+=r[o<<2&63],n+=r[64]):i===1&&(n+=r[o>>2&63],n+=r[o<<4&63],n+=r[64],n+=r[64]),n}function hs(e){return e instanceof Uint8Array}var Nt=new A("tag:yaml.org,2002:binary",{construct:fs,kind:"scalar",predicate:hs,represent:gs,resolve:ds});function ys(e){let t=e.length;return t===4&&(e==="true"||e==="True"||e==="TRUE")||t===5&&(e==="false"||e==="False"||e==="FALSE")}function xs(e){return e==="true"||e==="True"||e==="TRUE"}var Ft=new A("tag:yaml.org,2002:bool",{construct:xs,defaultStyle:"lowercase",kind:"scalar",predicate:$r,represent:{lowercase(e){return e?"true":"false"},uppercase(e){return e?"TRUE":"FALSE"},camelcase(e){return e?"True":"False"}},resolve:ys});var bs=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ws(e){return!(!bs.test(e)||e[e.length-1]==="_")}function Ps(e){let t=e.replace(/_/g,"").toLowerCase(),r=t[0]==="-"?-1:1,n=[];if("+-".indexOf(t[0])>=0&&(t=t.slice(1)),t===".inf")return r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;if(t===".nan")return NaN;if(t.indexOf(":")>=0){t.split(":").forEach(s=>{n.unshift(parseFloat(s))});let o=0,i=1;return n.forEach(s=>{o+=s*i,i*=60}),r*o}return r*parseFloat(t)}var As=/^[-+]?[0-9]+e/;function Ss(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(Se(e))return"-0.0";let r=e.toString(10);return As.test(r)?r.replace("e",".e"):r}function vs(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||Se(e))}var Rt=new A("tag:yaml.org,2002:float",{construct:Ps,defaultStyle:"lowercase",kind:"scalar",predicate:vs,represent:Ss,resolve:ws});function Ur(e){let t=new Function(`return ${e}`)();if(!(t instanceof Function))throw new TypeError(`Expected function but got ${typeof t}: ${e}`);return t}var Es=new A("tag:yaml.org,2002:js/function",{kind:"scalar",resolve(e){if(e===null)return!1;try{return Ur(`${e}`),!0}catch{return!1}},construct(e){return Ur(e)},predicate(e){return e instanceof Function},represent(e){return e.toString()}});function Ts(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function Cs(e){return 48<=e&&e<=55}function Ms(e){return 48<=e&&e<=57}function Is(e){let t=e.length,r=0,n=!1;if(!t)return!1;let o=e[r];if((o==="-"||o==="+")&&(o=e[++r]),o==="0"){if(r+1===t)return!0;if(o=e[++r],o==="b"){for(r++;r{r.unshift(parseInt(c,10))});let i=0,s=1;return r.forEach(c=>{i+=c*s,s*=60}),n*i}return n*parseInt(t,10)}function ks(e){return Object.prototype.toString.call(e)==="[object Number]"&&e%1===0&&!Se(e)}var Lt=new A("tag:yaml.org,2002:int",{construct:Os,defaultStyle:"decimal",kind:"scalar",predicate:ks,represent:{binary(e){return e>=0?`0b${e.toString(2)}`:`-0b${e.toString(2).slice(1)}`},octal(e){return e>=0?`0${e.toString(8)}`:`-0${e.toString(8).slice(1)}`},decimal(e){return e.toString(10)},hexadecimal(e){return e>=0?`0x${e.toString(16).toUpperCase()}`:`-0x${e.toString(16).toUpperCase().slice(1)}`}},resolve:Is,styleAliases:{binary:[2,"bin"],decimal:[10,"dec"],hexadecimal:[16,"hex"],octal:[8,"oct"]}});var $t=new A("tag:yaml.org,2002:map",{construct(e){return e!==null?e:{}},kind:"mapping"});function Ns(e){return e==="<<"||e===null}var _t=new A("tag:yaml.org,2002:merge",{kind:"scalar",resolve:Ns});function Fs(e){let t=e.length;return t===1&&e==="~"||t===4&&(e==="null"||e==="Null"||e==="NULL")}function Rs(){return null}function Ls(e){return e===null}var Dt=new A("tag:yaml.org,2002:null",{construct:Rs,defaultStyle:"lowercase",kind:"scalar",predicate:Ls,represent:{canonical(){return"~"},lowercase(){return"null"},uppercase(){return"NULL"},camelcase(){return"Null"}},resolve:Fs});var{hasOwn:$s}=Object,_s=Object.prototype.toString;function Ds(e){let t=[],r="",n=!1;for(let o of e){if(n=!1,_s.call(o)!=="[object Object]")return!1;for(r in o)if($s(o,r))if(!n)n=!0;else return!1;if(!n)return!1;if(t.indexOf(r)===-1)t.push(r);else return!1}return!0}function Us(e){return e!==null?e:[]}var Ut=new A("tag:yaml.org,2002:omap",{construct:Us,kind:"sequence",resolve:Ds});var js=Object.prototype.toString;function qs(e){let t=Array.from({length:e.length});for(let r=0;r[\s\S]+)\/(?[gismuy]*)$/,Bt=new A("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve(e){if(e===null||!e.length)return!1;let t=`${e}`;if(t.charAt(0)==="/"){if(!qt.test(e))return!1;let r=[...t.match(qt)?.groups?.modifiers??""];if(new Set(r).size"u"},represent(){return""}});var Qt=new K({explicit:[Ht,Kt,$t]});var Vt=new K({implicit:[Dt,Ft,Lt,Rt],include:[Qt]});var zt=new K({include:[Vt]});var ve=new K({explicit:[Nt,Ut,jt,Gt],implicit:[Yt,_t],include:[zt]});var Vs=new K({explicit:[Bt,Wt],include:[ve]});var Ee=class{constructor(t=ve){this.schema=t}};var Je=class extends Ee{constructor(r,{filename:n,schema:o,onWarning:i,legacy:s=!1,json:c=!1,listener:a=null}){super(o);this.input=r;this.filename=n,this.onWarning=i,this.legacy=s,this.json=c,this.listener=a,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=r.length}documents=[];length;lineIndent=0;lineStart=0;position=0;line=0;filename;onWarning;legacy;json;listener;implicitTypes;typeMap;version;checkLineBreaks;tagMap;anchorMap;tag;anchor;kind;result=""};var{hasOwn:re}=Object,Xe=1,Qr=2,Vr=3,Ze=4,Jt=1,zs=2,Br=3,Js=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Xs=/[\x85\u2028\u2029]/,Zs=/[,\[\]\{\}]/,zr=/^(?:!|!!|![a-z\-]+!)$/i,Jr=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Kr(e){return Object.prototype.toString.call(e)}function W(e){return e===10||e===13}function ae(e){return e===9||e===32}function D(e){return e===9||e===32||e===10||e===13}function me(e){return e===44||e===91||e===93||e===123||e===125}function ea(e){if(48<=e&&e<=57)return e-48;let t=e|32;return 97<=t&&t<=102?t-97+10:-1}function ta(e){return e===120?2:e===117?4:e===85?8:0}function ra(e){return 48<=e&&e<=57?e-48:-1}function Gr(e){return e===48?"\0":e===97?"\x07":e===98?"\b":e===116||e===9?" ":e===110?` +`:e===118?"\v":e===102?"\f":e===114?"\r":e===101?"\x1B":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"\x85":e===95?"\xA0":e===76?"\u2028":e===80?"\u2029":""}function na(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}var Xr=Array.from({length:256}),Zr=Array.from({length:256});for(let e=0;e<256;e++)Xr[e]=Gr(e)?1:0,Zr[e]=Gr(e);function en(e,t){return new ee(t,new ze(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function h(e,t){throw en(e,t)}function et(e,t){e.onWarning&&e.onWarning.call(null,en(e,t))}var Hr={YAML(e,t,...r){if(e.version!==null)return h(e,"duplication of %YAML directive");if(r.length!==1)return h(e,"YAML directive accepts exactly one argument");let n=/^([0-9]+)\.([0-9]+)$/.exec(r[0]);if(n===null)return h(e,"ill-formed argument of the YAML directive");let o=parseInt(n[1],10),i=parseInt(n[2],10);if(o!==1)return h(e,"unacceptable YAML version of the document");if(e.version=r[0],e.checkLineBreaks=i<2,i!==1&&i!==2)return et(e,"unsupported YAML version of the document")},TAG(e,t,...r){if(r.length!==2)return h(e,"TAG directive accepts exactly two arguments");let n=r[0],o=r[1];if(!zr.test(n))return h(e,"ill-formed tag handle (first argument) of the TAG directive");if(e.tagMap&&re(e.tagMap,n))return h(e,`there is a previously declared suffix for "${n}" tag handle`);if(!Jr.test(o))return h(e,"ill-formed tag prefix (second argument) of the TAG directive");typeof e.tagMap>"u"&&(e.tagMap=Object.create(null)),e.tagMap[n]=o}};function te(e,t,r,n){let o;if(t1&&(e.result+=G(` +`,t-1))}function oa(e,t,r){let n=e.kind,o=e.result,i=e.input.charCodeAt(e.position);if(D(i)||me(i)||i===35||i===38||i===42||i===33||i===124||i===62||i===39||i===34||i===37||i===64||i===96)return!1;let s;if((i===63||i===45)&&(s=e.input.charCodeAt(e.position+1),D(s)||r&&me(s)))return!1;e.kind="scalar",e.result="";let c,a=c=e.position,p=!1,m=0;for(;i!==0;){if(i===58){if(s=e.input.charCodeAt(e.position+1),D(s)||r&&me(s))break}else if(i===35){let d=e.input.charCodeAt(e.position-1);if(D(d))break}else{if(e.position===e.lineStart&&tt(e)||r&&me(i))break;if(W(i)){m=e.line;let d=e.lineStart,g=e.lineIndent;if(I(e,!1,-1),e.lineIndent>=t){p=!0,i=e.input.charCodeAt(e.position);continue}else{e.position=c,e.line=m,e.lineStart=d,e.lineIndent=g;break}}}p&&(te(e,a,c,!1),Zt(e,e.line-m),a=c=e.position,p=!1),ae(i)||(c=e.position+1),i=e.input.charCodeAt(++e.position)}return te(e,a,c,!1),e.result?!0:(e.kind=n,e.result=o,!1)}function ia(e,t){let r,n,o;if(r=e.input.charCodeAt(e.position),r!==39)return!1;for(e.kind="scalar",e.result="",e.position++,n=o=e.position;(r=e.input.charCodeAt(e.position))!==0;)if(r===39)if(te(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),r===39)n=e.position,e.position++,o=e.position;else return!0;else if(W(r))te(e,n,o,!0),Zt(e,I(e,!1,t)),n=o=e.position;else{if(e.position===e.lineStart&&tt(e))return h(e,"unexpected end of the document within a single quoted scalar");e.position++,o=e.position}return h(e,"unexpected end of the stream within a single quoted scalar")}function sa(e,t){let r=e.input.charCodeAt(e.position);if(r!==34)return!1;e.kind="scalar",e.result="",e.position++;let n,o=n=e.position,i;for(;(r=e.input.charCodeAt(e.position))!==0;){if(r===34)return te(e,o,e.position,!0),e.position++,!0;if(r===92){if(te(e,o,e.position,!0),r=e.input.charCodeAt(++e.position),W(r))I(e,!1,t);else if(r<256&&Xr[r])e.result+=Zr[r],e.position++;else if((i=ta(r))>0){let s=i,c=0;for(;s>0;s--)if(r=e.input.charCodeAt(++e.position),(i=ea(r))>=0)c=(c<<4)+i;else return h(e,"expected hexadecimal character");e.result+=na(c),e.position++}else return h(e,"unknown escape sequence");o=n=e.position}else if(W(r))te(e,o,n,!0),Zt(e,I(e,!1,t)),o=n=e.position;else{if(e.position===e.lineStart&&tt(e))return h(e,"unexpected end of the document within a double quoted scalar");e.position++,n=e.position}}return h(e,"unexpected end of the stream within a double quoted scalar")}function aa(e,t){let r=e.input.charCodeAt(e.position),n,o=!0,i={};if(r===91)n=93,o=!1,i=[];else if(r===123)n=125;else return!1;e.anchor!==null&&typeof e.anchor<"u"&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=i),r=e.input.charCodeAt(++e.position);let s=e.tag,c=e.anchor,a=!0,p,m,d=m=p=null,g,y=g=!1,x=0,P=0,b=Object.create(null);for(;r!==0;){if(I(e,!0,t),r=e.input.charCodeAt(e.position),r===n)return e.position++,e.tag=s,e.anchor=c,e.kind=o?"mapping":"sequence",e.result=i,!0;if(!a)return h(e,"missed comma between flow collection entries");d=m=p=null,y=g=!1,r===63&&(x=e.input.charCodeAt(e.position+1),D(x)&&(y=g=!0,e.position++,I(e,!0,t))),P=e.line,fe(e,t,Xe,!1,!0),d=e.tag||null,m=e.result,I(e,!0,t),r=e.input.charCodeAt(e.position),(g||e.line===P)&&r===58&&(y=!0,r=e.input.charCodeAt(++e.position),I(e,!0,t),fe(e,t,Xe,!1,!0),p=e.result),o?de(e,i,b,d,m,p):y?i.push(de(e,null,b,d,m,p)):i.push(m),I(e,!0,t),r=e.input.charCodeAt(e.position),r===44?(a=!0,r=e.input.charCodeAt(++e.position)):a=!1}return h(e,"unexpected end of the stream within a flow collection")}function ca(e,t){let r=Jt,n=!1,o=!1,i=t,s=0,c=!1,a=e.input.charCodeAt(e.position),p=!1;if(a===124)p=!1;else if(a===62)p=!0;else return!1;e.kind="scalar",e.result="";let m=0;for(;a!==0;)if(a=e.input.charCodeAt(++e.position),a===43||a===45)if(Jt===r)r=a===43?Br:zs;else return h(e,"repeat of a chomping mode identifier");else if((m=ra(a))>=0){if(m===0)return h(e,"bad explicit indentation width of a block scalar; it cannot be less than one");if(!o)i=t+m-1,o=!0;else return h(e,"repeat of an indentation width identifier")}else break;if(ae(a)){do a=e.input.charCodeAt(++e.position);while(ae(a));if(a===35)do a=e.input.charCodeAt(++e.position);while(!W(a)&&a!==0)}for(;a!==0;){for(Xt(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!o||e.lineIndenti&&(i=e.lineIndent),W(a)){s++;continue}if(e.lineIndentt)&&i!==0)return h(e,"bad indentation of a sequence entry");if(e.lineIndentt)&&(ge(e,t,Ze,!0,a)&&(x?g=e.result:y=e.result),x||(fe(e,i,s,d,g,y,p,m),d=g=y=null),I(e,!0,-1),b=e.input.charCodeAt(e.position)),e.lineIndent>t&&b!==0)return h(e,"bad indentation of a mapping entry");if(e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndent tag; it should be "${m.kind}", not "${e.kind}"`);if(m.resolve(e.result))e.result=m.construct(e.result),e.anchor!==null&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=e.result);else return h(e,`cannot resolve a node with !<${e.tag}> explicit tag`)}else return h(e,`unknown tag !<${e.tag}>`);return e.listener&&e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||p}function da(e){let t=e.position,r,n,o,i=!1,s;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(s=e.input.charCodeAt(e.position))!==0&&(I(e,!0,-1),s=e.input.charCodeAt(e.position),!(e.lineIndent>0||s!==37));){for(i=!0,s=e.input.charCodeAt(++e.position),r=e.position;s!==0&&!D(s);)s=e.input.charCodeAt(++e.position);if(n=e.input.slice(r,e.position),o=[],n.length<1)return h(e,"directive name must not be less than one character in length");for(;s!==0;){for(;ae(s);)s=e.input.charCodeAt(++e.position);if(s===35){do s=e.input.charCodeAt(++e.position);while(s!==0&&!W(s));break}if(W(s))break;for(r=e.position;s!==0&&!D(s);)s=e.input.charCodeAt(++e.position);o.push(e.input.slice(r,e.position))}s!==0&&Jt(e),re(Hr,n)?Hr[n](e,n,...o):et(e,`unknown document directive "${n}"`)}if(I(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45)e.position+=3,I(e,!0,-1);else if(i)return h(e,"directives end mark is expected");if(ge(e,e.lineIndent-1,Ze,!1,!0),I(e,!0,-1),e.checkLineBreaks&&Xs.test(e.input.slice(t,e.position))&&et(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&tt(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,I(e,!0,-1));return}if(e.position({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select a model",e);if(!t){await u.flashNotification("No model selected.","error");return}let r=t.name;await xt(t),await we(t),await u.flashNotification(`Selected model: ${r}`),console.log("Selected model:",t)}async function an(){(!f||!f.imageModels)&&await z(!1);let e=f.imageModels.map(n=>({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select an image model",e);if(!t){await u.flashNotification("No image model selected.","error");return}let r=t.name;await yt(t),await wt(t),await u.flashNotification(`Selected image model: ${r}`),console.log("Selected image model:",t)}async function cn(){(!f||!f.embeddingModels)&&await z(!1);let e=f.embeddingModels.map(n=>({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select an embedding model",e);if(!t){await u.flashNotification("No embedding model selected.","error");return}let r=t.name;await bt(t),await Pt(t),await u.flashNotification(`Selected embedding model: ${r}`),console.log("Selected embedding model:",t)}async function ln(){await C();let e=await _e(),t=await u.prompt("Please enter a prompt to send to the LLM. Selected text or the entire note will also be sent as context."),r=await u.getCurrentPage(),n=new Date,o=n.toISOString().split("T")[0],i=n.toLocaleDateString("en-US",{weekday:"long"});await O.streamChatIntoEditor({messages:[{role:"system",content:"You are an AI note assistant. Follow all user instructions and use the note context and note content to help follow those instructions. Use Markdown for any formatting."},{role:"user",content:`Note Context: Today is ${i}, ${o}. The current note name is "${r}". +`,n?1+s:s),n=!0,o=!0,s=0;let d=e.position;for(;!W(a)&&a!==0;)a=e.input.charCodeAt(++e.position);te(e,d,e.position,!1)}return!0}function Wr(e,t){let r,n,o=!1,i,s=e.tag,c=e.anchor,a=[];for(e.anchor!==null&&typeof e.anchor<"u"&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);i!==0&&!(i!==45||(n=e.input.charCodeAt(e.position+1),!D(n)));){if(o=!0,e.position++,I(e,!0,-1)&&e.lineIndent<=t){a.push(null),i=e.input.charCodeAt(e.position);continue}if(r=e.line,fe(e,t,Vr,!1,!0),a.push(e.result),I(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===r||e.lineIndent>t)&&i!==0)return h(e,"bad indentation of a sequence entry");if(e.lineIndentt)&&(fe(e,t,Ze,!0,a)&&(x?g=e.result:y=e.result),x||(de(e,i,s,d,g,y,p,m),d=g=y=null),I(e,!0,-1),b=e.input.charCodeAt(e.position)),e.lineIndent>t&&b!==0)return h(e,"bad indentation of a mapping entry");if(e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndent tag; it should be "${m.kind}", not "${e.kind}"`);if(m.resolve(e.result))e.result=m.construct(e.result),e.anchor!==null&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=e.result);else return h(e,`cannot resolve a node with !<${e.tag}> explicit tag`)}else return h(e,`unknown tag !<${e.tag}>`);return e.listener&&e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||p}function da(e){let t=e.position,r,n,o,i=!1,s;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(s=e.input.charCodeAt(e.position))!==0&&(I(e,!0,-1),s=e.input.charCodeAt(e.position),!(e.lineIndent>0||s!==37));){for(i=!0,s=e.input.charCodeAt(++e.position),r=e.position;s!==0&&!D(s);)s=e.input.charCodeAt(++e.position);if(n=e.input.slice(r,e.position),o=[],n.length<1)return h(e,"directive name must not be less than one character in length");for(;s!==0;){for(;ae(s);)s=e.input.charCodeAt(++e.position);if(s===35){do s=e.input.charCodeAt(++e.position);while(s!==0&&!W(s));break}if(W(s))break;for(r=e.position;s!==0&&!D(s);)s=e.input.charCodeAt(++e.position);o.push(e.input.slice(r,e.position))}s!==0&&Xt(e),re(Hr,n)?Hr[n](e,n,...o):et(e,`unknown document directive "${n}"`)}if(I(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45)e.position+=3,I(e,!0,-1);else if(i)return h(e,"directives end mark is expected");if(fe(e,e.lineIndent-1,Ze,!1,!0),I(e,!0,-1),e.checkLineBreaks&&Xs.test(e.input.slice(t,e.position))&&et(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&tt(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,I(e,!0,-1));return}if(e.position({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select a model",e);if(!t){await u.flashNotification("No model selected.","error");return}let r=t.name;await xt(t),await be(t),await u.flashNotification(`Selected model: ${r}`),console.log("Selected model:",t)}async function an(){(!f||!f.imageModels)&&await z(!1);let e=f.imageModels.map(n=>({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select an image model",e);if(!t){await u.flashNotification("No image model selected.","error");return}let r=t.name;await yt(t),await wt(t),await u.flashNotification(`Selected image model: ${r}`),console.log("Selected image model:",t)}async function cn(){(!f||!f.embeddingModels)&&await z(!1);let e=f.embeddingModels.map(n=>({...n,name:n.name,description:n.description||`${n.modelName} on ${n.provider}`})),t=await u.filterBox("Select an embedding model",e);if(!t){await u.flashNotification("No embedding model selected.","error");return}let r=t.name;await bt(t),await Pt(t),await u.flashNotification(`Selected embedding model: ${r}`),console.log("Selected embedding model:",t)}async function ln(){await C();let e=await _e(),t=await u.prompt("Please enter a prompt to send to the LLM. Selected text or the entire note will also be sent as context."),r=await u.getCurrentPage(),n=new Date,o=n.toISOString().split("T")[0],i=n.toLocaleDateString("en-US",{weekday:"long"});await O.streamChatIntoEditor({messages:[{role:"system",content:"You are an AI note assistant. Follow all user instructions and use the note context and note content to help follow those instructions. Use Markdown for any formatting."},{role:"user",content:`Note Context: Today is ${i}, ${o}. The current note name is "${r}". User Prompt: ${t} Note Content: ${e.text}`}],stream:!0},e.to)}async function un(){await C();let e=await _e();if(console.log("selectedTextInfo",e),e.text.length>0){let t=await u.getCurrentPage(),r=await O.chatWithAI({messages:[{role:"user",content:`Please summarize this note using markdown for any formatting. Your summary will be appended to the end of this note, do not include any of the note contents yourself. Keep the summary brief. The note name is ${t}. ${e.text}`}],stream:!1});return console.log("OpenAI response:",r),{summary:r,selectedTextInfo:e}}return{summary:"",selectedTextInfo:null}}async function pn(){let{summary:e,selectedTextInfo:t}=await un();e&&t&&await u.insertAtPos(` -`+e,t.to)}async function mn(){let{summary:e}=await un();e?await u.showPanel("rhs",2,e):await u.flashNotification("No summary available.")}async function Zt(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=(await Or("tag select name where parent = 'page' order by name")).map(d=>d.name);console.log("All tags:",r);let n=`You are an AI tagging assistant. Please provide a short list of tags, separated by spaces. Follow these guidelines: +`+e,t.to)}async function mn(){let{summary:e}=await un();e?await u.showPanel("rhs",2,e):await u.flashNotification("No summary available.")}async function er(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=(await Ae("tag select name where parent = 'page' order by name")).map(d=>d.name);console.log("All tags:",r);let n=`You are an AI tagging assistant. Please provide a short list of tags, separated by spaces. Follow these guidelines: - Only return tags and no other content. - Tags must be one word only and in lowercase. - Use existing tags as a starting point. @@ -112,7 +112,7 @@ ${e.text}`}],stream:!1});return console.log("OpenAI response:",r),{summary:r,sel ${f.promptInstructions.tagRules}`,o=`Page Title: ${t} Page Content: -${e}`,s=(await O.singleMessageChat(o,n)).trim().replace(/,/g,"").split(/\s+/),c=await N.parseMarkdown(e),a=await V(c),p=[...new Set([...a.tags||[],...s])];a.tags=p,console.log("Current frontmatter:",a);let m=await ut(c,a);console.log("updatedNoteContent",m),await u.dispatch(m),await u.flashNotification("Note tagged successfully.")}async function er(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=[{name:"Generating suggestions...",description:""}];u.filterBox("Loading...",r,"Retrieving suggestions from LLM provider.").then(p=>{console.log("Selected option (initial):",p)});let o="";f.promptInstructions.pageRenameSystem?o=f.promptInstructions.pageRenameSystem:o=`You are an AI note-naming assistant. Your task is to suggest three to five possible names for the provided note content. Please adhere to the following guidelines: +${e}`,s=(await O.singleMessageChat(o,n)).trim().replace(/,/g,"").split(/\s+/),c=await N.parseMarkdown(e),a=await V(c),p=[...new Set([...a.tags||[],...s])];a.tags=p,console.log("Current frontmatter:",a);let m=await ut(c,a);console.log("updatedNoteContent",m),await u.dispatch(m),await u.flashNotification("Note tagged successfully.")}async function tr(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=[{name:"Generating suggestions...",description:""}];u.filterBox("Loading...",r,"Retrieving suggestions from LLM provider.").then(p=>{console.log("Selected option (initial):",p)});let o="";f.promptInstructions.pageRenameSystem?o=f.promptInstructions.pageRenameSystem:o=`You are an AI note-naming assistant. Your task is to suggest three to five possible names for the provided note content. Please adhere to the following guidelines: - Provide each name on a new line. - Use only spaces, forward slashes (as folder separators), and hyphens as special characters. - Ensure the names are concise, descriptive, and relevant to the content. @@ -126,7 +126,7 @@ ${e}`,`${o} Always follow the below rules, if any, given by the user: ${f.promptInstructions.pageRenameRules}`,!0)).trim().split(` -`).filter(p=>p.trim()!=="").map(p=>p.replace(/^[*-]\s*/,"").trim());s.push(t),s=[...new Set(s)],s.length===0&&await u.flashNotification("No suggestions available.");let c=await u.filterBox("New page name",s.map(p=>({name:p})),"Select a new page name from one of the suggestions below.");if(!c){await u.flashNotification("No page name selected.","error");return}console.log("selectedSuggestion",c);let a=await S.invokeFunction("index.renamePageCommand",{oldPage:t,page:c.name});console.log("renamedPage",a),a||await u.flashNotification("Error renaming page.","error")}async function tr(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=["title","tags"],o=await O.singleMessageChat(`Current Page Title: ${t} +`).filter(p=>p.trim()!=="").map(p=>p.replace(/^[*-]\s*/,"").trim());s.push(t),s=[...new Set(s)],s.length===0&&await u.flashNotification("No suggestions available.");let c=await u.filterBox("New page name",s.map(p=>({name:p})),"Select a new page name from one of the suggestions below.");if(!c){await u.flashNotification("No page name selected.","error");return}console.log("selectedSuggestion",c);let a=await S.invokeFunction("index.renamePageCommand",{oldPage:t,page:c.name});console.log("renamedPage",a),a||await u.flashNotification("Error renaming page.","error")}async function rr(){await C();let e=await u.getText(),t=await u.getCurrentPage(),r=["title","tags"],o=await O.singleMessageChat(`Current Page Title: ${t} Page Content: ${e}`,`You are an AI note enhancing assistant. Your task is to understand the content of a note, detect and extract important information, and convert it to frontmatter attributes. Please adhere to the following guidelines: @@ -142,11 +142,11 @@ ${e}`,`You are an AI note enhancing assistant. Your task is to understand the co Always follow the below rules, if any, given by the user: -${f.promptInstructions.enhanceFrontMatterPrompt}`,!0);console.log("frontmatter returned by enhanceNoteFrontMatter",o);try{let i=rn(o);if(typeof i!="object"||Array.isArray(i)||!i)throw new Error("Invalid YAML: Not an object");r.forEach(m=>{delete i[m]});let s=await N.parseMarkdown(e),a={...await V(s),...i},p=await ut(s,a);console.log("updatedNoteContent",p),await u.dispatch(p)}catch(i){console.error("Invalid YAML returned by enhanceNoteFrontMatter",i),await u.flashNotification("Error: Invalid Frontmatter YAML returned.","error");return}await u.flashNotification("Frontmatter enhanced successfully.","info")}async function dn(){await Zt(),await tr(),await er()}async function fn(){let e=await _e(),t=e.to;await O.streamChatIntoEditor({messages:[{role:"system",content:"You are an AI note assistant in a markdown-based note tool."},{role:"user",content:e.text}],stream:!0},t)}async function gn(){await C();let e=await Ve();if(e.length===0){await u.flashNotification("Error: The page does not match the required format for a chat.");return}e.unshift(xe);let t=await ue(e);console.log("enrichedMessages",t);let r=await se();await u.insertAtPos(` +${f.promptInstructions.enhanceFrontMatterPrompt}`,!0);console.log("frontmatter returned by enhanceNoteFrontMatter",o);try{let i=rn(o);if(typeof i!="object"||Array.isArray(i)||!i)throw new Error("Invalid YAML: Not an object");r.forEach(m=>{delete i[m]});let s=await N.parseMarkdown(e),a={...await V(s),...i},p=await ut(s,a);console.log("updatedNoteContent",p),await u.dispatch(p)}catch(i){console.error("Invalid YAML returned by enhanceNoteFrontMatter",i),await u.flashNotification("Error: Invalid Frontmatter YAML returned.","error");return}await u.flashNotification("Frontmatter enhanced successfully.","info")}async function dn(){await er(),await rr(),await tr()}async function fn(){let e=await _e(),t=e.to;await O.streamChatIntoEditor({messages:[{role:"system",content:"You are an AI note assistant in a markdown-based note tool."},{role:"user",content:e.text}],stream:!0},t)}async function gn(){await C();let e=await Ve();if(e.length===0){await u.flashNotification("Error: The page does not match the required format for a chat.");return}e.unshift(ye);let t=await ue(e);console.log("enrichedMessages",t);let r=await se();await u.insertAtPos(` **assistant**: `,r),r+=17,await u.insertAtPos(` -**user**: `,r),await u.moveCursor(r+12);try{await O.streamChatIntoEditor({messages:t,stream:!0},r)}catch(n){console.error("Error streaming chat on page:",n),await u.flashNotification("Error streaming chat on page.","error")}}async function hn(){if(await C(),!f.imageModels||f.imageModels.length===0){await u.flashNotification("No image models available.","error");return}try{let e=await u.prompt("Enter a prompt for DALL\xB7E:");if(!e||!e.trim()){await u.flashNotification("No prompt entered. Operation cancelled.","error");return}let t={prompt:e,numImages:1,size:"1024x1024",quality:"hd"},r=await Ye.generateImage(t);if(r&&r.data&&r.data.length>0){let n=r.data[0].b64_json,o=r.data[0].revised_prompt,i=new Uint8Array(Lr(n)),s=`dall-e-${Date.now()}.png`,c=Ir(await u.getCurrentPage())+"/";c==="/"&&(c=""),await $.writeAttachment(c+s,i);let a=`![${s}](${s}) +**user**: `,r),await u.moveCursor(r+12);try{await O.streamChatIntoEditor({messages:t,stream:!0},r)}catch(n){console.error("Error streaming chat on page:",n),await u.flashNotification("Error streaming chat on page.","error")}}async function hn(){if(await C(),!f.imageModels||f.imageModels.length===0){await u.flashNotification("No image models available.","error");return}try{let e=await u.prompt("Enter a prompt for DALL\xB7E:");if(!e||!e.trim()){await u.flashNotification("No prompt entered. Operation cancelled.","error");return}let t={prompt:e,numImages:1,size:"1024x1024",quality:"hd"},r=await Ye.generateImage(t);if(r&&r.data&&r.data.length>0){let n=r.data[0].b64_json,o=r.data[0].revised_prompt,i=new Uint8Array(Lr(n)),s=`dall-e-${Date.now()}.png`,c=Or(await u.getCurrentPage())+"/";c==="/"&&(c=""),await $.writeAttachment(c+s,i);let a=`![${s}](${s}) *${o}*`;await u.insertAtCursor(a),await u.flashNotification("Image generated and inserted with caption successfully.")}else await u.flashNotification("Failed to generate image.","error")}catch(e){console.error("Error generating image with DALL\xB7E:",e),await u.flashNotification("Error generating image.","error")}}async function yn(e,t){try{return await C(),await O.singleMessageChat(e,t||"You are an AI note assistant helping to render content for a note. Please follow user instructions and keep your response short and concise.")}catch(r){throw console.error("Error querying OpenAI:",r),r}}async function xn(){await C();let e=await u.prompt("Enter some text to embed:");if(!e){await u.flashNotification("No text entered.","error");return}let t=await j.generateEmbeddings({text:e});await u.insertAtCursor(` -Embedding: ${t}`)}var bn={aiPromptSlashCommplete:Fr,queryAI:yn,reloadSettingsPageEvent:nn,reloadConfigEvent:on,summarizeNote:mn,insertSummary:pn,callOpenAI:ln,tagNoteWithAI:Zt,promptAndGenerateImage:hn,streamOpenAIWithSelectionAsPrompt:fn,streamChatOnPage:gn,insertAiPromptFromTemplate:Rr,suggestPageName:er,enhanceNoteFrontMatter:tr,enhanceNoteWithAI:dn,selectTextModel:sn,selectImageModel:an,selectEmbeddingModel:cn,testEmbeddingGeneration:xn,getAllEmbeddings:vt,searchEmbeddings:Et,queueEmbeddingGeneration:br,processEmbeddingsQueue:wr,processSummaryQueue:Pr,generateEmbeddings:Sr,generateEmbeddingsOnServer:Ae,searchEmbeddingsForChat:Qe,searchCombinedEmbeddings:We,searchSummaryEmbeddings:vr,readPageSearchEmbeddings:Er,writePageSearchEmbeddings:Tr,getPageMetaSearchEmbeddings:Tt,searchCommand:Mr,updateSearchPage:Cr},wn={name:"silverbullet-ai",requiredPermissions:["fetch"],functions:{aiPromptSlashCommplete:{path:"src/prompts.ts:aiPromptSlashComplete",events:["slash:complete"]},queryAI:{path:"sbai.ts:queryAI"},reloadSettingsPageEvent:{path:"sbai.ts:reloadSettingsPage",events:["page:saved"]},reloadConfigEvent:{path:"sbai.ts:reloadConfig",events:["config:loaded"]},summarizeNote:{path:"sbai.ts:openSummaryPanel",command:{name:"AI: Summarize Note and open summary"}},insertSummary:{path:"sbai.ts:insertSummary",command:{name:"AI: Insert Summary"}},callOpenAI:{path:"sbai.ts:callOpenAIwithNote",command:{name:"AI: Call OpenAI with Note as context"}},tagNoteWithAI:{path:"sbai.ts:tagNoteWithAI",command:{name:"AI: Generate tags for note"}},promptAndGenerateImage:{path:"sbai.ts:promptAndGenerateImage",command:{name:"AI: Generate and insert image using DallE"}},streamOpenAIWithSelectionAsPrompt:{path:"sbai.ts:streamOpenAIWithSelectionAsPrompt",command:{name:"AI: Stream response with selection or note as prompt"}},streamChatOnPage:{path:"sbai.ts:streamChatOnPage",command:{name:"AI: Chat on current page",key:"Ctrl-Shift-Enter",mac:"Cmd-Shift-Enter"}},insertAiPromptFromTemplate:{path:"src/prompts.ts:insertAiPromptFromTemplate",command:{name:"AI: Execute AI Prompt from Custom Template"}},suggestPageName:{path:"sbai.ts:suggestPageName",command:{name:"AI: Suggest Page Name"}},enhanceNoteFrontMatter:{path:"sbai.ts:enhanceNoteFrontMatter",command:{name:"AI: Generate Note FrontMatter"}},enhanceNoteWithAI:{path:"sbai.ts:enhanceNoteWithAI",command:{name:"AI: Enhance Note"}},selectTextModel:{path:"sbai.ts:selectModelFromConfig",command:{name:"AI: Select Text Model from Config"}},selectImageModel:{path:"sbai.ts:selectImageModelFromConfig",command:{name:"AI: Select Image Model from Config"}},selectEmbeddingModel:{path:"sbai.ts:selectEmbeddingModelFromConfig",command:{name:"AI: Select Embedding Model from Config"}},testEmbeddingGeneration:{path:"sbai.ts:testEmbeddingGeneration",command:{name:"AI: Test Embedding Generation"}},getAllEmbeddings:{path:"src/embeddings.ts:getAllEmbeddings",env:"server"},searchEmbeddings:{path:"src/embeddings.ts:searchEmbeddings",env:"server"},queueEmbeddingGeneration:{path:"src/embeddings.ts:queueEmbeddingGeneration",env:"server",events:["page:index"]},processEmbeddingsQueue:{path:"src/embeddings.ts:processEmbeddingsQueue",mqSubscriptions:[{queue:"aiEmbeddingsQueue",batchSize:1,autoAck:!0,pollInterval:6e5}]},processSummaryQueue:{path:"src/embeddings.ts:processSummaryQueue",mqSubscriptions:[{queue:"aiSummaryQueue",batchSize:1,autoAck:!0,pollInterval:6e5}]},generateEmbeddings:{path:"src/embeddings.ts:generateEmbeddings"},generateEmbeddingsOnServer:{path:"src/embeddings.ts:generateEmbeddingsOnServer"},searchEmbeddingsForChat:{path:"src/embeddings.ts:searchEmbeddingsForChat"},searchCombinedEmbeddings:{path:"src/embeddings.ts:searchCombinedEmbeddings"},searchSummaryEmbeddings:{path:"src/embeddings.ts:searchSummaryEmbeddings"},readPageSearchEmbeddings:{path:"src/embeddings.ts:readFileEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"readFile"}},writePageSearchEmbeddings:{path:"src/embeddings.ts:writeFileEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"writeFile"}},getPageMetaSearchEmbeddings:{path:"src/embeddings.ts:getFileMetaEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"getFileMeta"}},searchCommand:{path:"src/embeddings.ts:searchCommand",command:{name:"AI: Search"}},updateSearchPage:{path:"src/embeddings.ts:updateSearchPage",events:["editor:pageLoaded","editor:pageReloaded"]}},assets:{}},zm={manifest:wn,functionMapping:bn};rr(bn,wn);export{zm as plug}; +Embedding: ${t}`)}var bn={aiPromptSlashCommplete:Fr,queryAI:yn,reloadSettingsPageEvent:nn,reloadConfigEvent:on,summarizeNote:mn,insertSummary:pn,callOpenAI:ln,tagNoteWithAI:er,promptAndGenerateImage:hn,streamOpenAIWithSelectionAsPrompt:fn,streamChatOnPage:gn,insertAiPromptFromTemplate:Rr,suggestPageName:tr,enhanceNoteFrontMatter:rr,enhanceNoteWithAI:dn,selectTextModel:sn,selectImageModel:an,selectEmbeddingModel:cn,testEmbeddingGeneration:xn,getAllEmbeddings:vt,searchEmbeddings:Et,queueEmbeddingGeneration:wr,processEmbeddingsQueue:Pr,processSummaryQueue:Ar,generateEmbeddings:vr,generateEmbeddingsOnServer:Pe,searchEmbeddingsForChat:Qe,searchCombinedEmbeddings:We,searchSummaryEmbeddings:Er,readPageSearchEmbeddings:Tr,writePageSearchEmbeddings:Cr,getPageMetaSearchEmbeddings:Tt,searchCommand:Ir,updateSearchPage:Mr},wn={name:"silverbullet-ai",requiredPermissions:["fetch"],functions:{aiPromptSlashCommplete:{path:"src/prompts.ts:aiPromptSlashComplete",events:["slash:complete"]},queryAI:{path:"sbai.ts:queryAI"},reloadSettingsPageEvent:{path:"sbai.ts:reloadSettingsPage",events:["page:saved"]},reloadConfigEvent:{path:"sbai.ts:reloadConfig",events:["config:loaded"]},summarizeNote:{path:"sbai.ts:openSummaryPanel",command:{name:"AI: Summarize Note and open summary"}},insertSummary:{path:"sbai.ts:insertSummary",command:{name:"AI: Insert Summary"}},callOpenAI:{path:"sbai.ts:callOpenAIwithNote",command:{name:"AI: Call OpenAI with Note as context"}},tagNoteWithAI:{path:"sbai.ts:tagNoteWithAI",command:{name:"AI: Generate tags for note"}},promptAndGenerateImage:{path:"sbai.ts:promptAndGenerateImage",command:{name:"AI: Generate and insert image using DallE"}},streamOpenAIWithSelectionAsPrompt:{path:"sbai.ts:streamOpenAIWithSelectionAsPrompt",command:{name:"AI: Stream response with selection or note as prompt"}},streamChatOnPage:{path:"sbai.ts:streamChatOnPage",command:{name:"AI: Chat on current page",key:"Ctrl-Shift-Enter",mac:"Cmd-Shift-Enter"}},insertAiPromptFromTemplate:{path:"src/prompts.ts:insertAiPromptFromTemplate",command:{name:"AI: Execute AI Prompt from Custom Template"}},suggestPageName:{path:"sbai.ts:suggestPageName",command:{name:"AI: Suggest Page Name"}},enhanceNoteFrontMatter:{path:"sbai.ts:enhanceNoteFrontMatter",command:{name:"AI: Generate Note FrontMatter"}},enhanceNoteWithAI:{path:"sbai.ts:enhanceNoteWithAI",command:{name:"AI: Enhance Note"}},selectTextModel:{path:"sbai.ts:selectModelFromConfig",command:{name:"AI: Select Text Model from Config"}},selectImageModel:{path:"sbai.ts:selectImageModelFromConfig",command:{name:"AI: Select Image Model from Config"}},selectEmbeddingModel:{path:"sbai.ts:selectEmbeddingModelFromConfig",command:{name:"AI: Select Embedding Model from Config"}},testEmbeddingGeneration:{path:"sbai.ts:testEmbeddingGeneration",command:{name:"AI: Test Embedding Generation"}},getAllEmbeddings:{path:"src/embeddings.ts:getAllEmbeddings",env:"server"},searchEmbeddings:{path:"src/embeddings.ts:searchEmbeddings",env:"server"},queueEmbeddingGeneration:{path:"src/embeddings.ts:queueEmbeddingGeneration",env:"server",events:["page:index"]},processEmbeddingsQueue:{path:"src/embeddings.ts:processEmbeddingsQueue",mqSubscriptions:[{queue:"aiEmbeddingsQueue",batchSize:1,autoAck:!0,pollInterval:6e5}]},processSummaryQueue:{path:"src/embeddings.ts:processSummaryQueue",mqSubscriptions:[{queue:"aiSummaryQueue",batchSize:1,autoAck:!0,pollInterval:6e5}]},generateEmbeddings:{path:"src/embeddings.ts:generateEmbeddings"},generateEmbeddingsOnServer:{path:"src/embeddings.ts:generateEmbeddingsOnServer"},searchEmbeddingsForChat:{path:"src/embeddings.ts:searchEmbeddingsForChat"},searchCombinedEmbeddings:{path:"src/embeddings.ts:searchCombinedEmbeddings"},searchSummaryEmbeddings:{path:"src/embeddings.ts:searchSummaryEmbeddings"},readPageSearchEmbeddings:{path:"src/embeddings.ts:readFileEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"readFile"}},writePageSearchEmbeddings:{path:"src/embeddings.ts:writeFileEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"writeFile"}},getPageMetaSearchEmbeddings:{path:"src/embeddings.ts:getFileMetaEmbeddings",pageNamespace:{pattern:"\u{1F916} .+",operation:"getFileMeta"}},searchCommand:{path:"src/embeddings.ts:searchCommand",command:{name:"AI: Search"}},updateSearchPage:{path:"src/embeddings.ts:updateSearchPage",events:["editor:pageLoaded","editor:pageReloaded"]}},assets:{}},zm={manifest:wn,functionMapping:bn};nr(bn,wn);export{zm as plug};