generated from silverbulletmd/silverbullet-plug-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsilverbullet-ai.plug.js
285 lines (200 loc) · 104 KB
/
silverbullet-ai.plug.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
var Nn=Object.defineProperty;var _=(e,t)=>{for(var r in t)Nn(e,r,{get:t[r],enumerable:!0})};var he=e=>{throw new Error("Not initialized yet")},at=typeof window>"u"&&typeof globalThis.WebSocketPair>"u";typeof Deno>"u"&&(self.Deno={args:[],build:{arch:"x86_64"},env:{get(){}}});var st=new Map,it=0;at&&(globalThis.syscall=async(e,...t)=>await new Promise((r,o)=>{it++,st.set(it,{resolve:r,reject:o}),he({type:"sys",id:it,name:e,args:t})}));function cr(e,t,r){at&&(he=r,self.addEventListener("message",o=>{(async()=>{let n=o.data;switch(n.type){case"inv":{let i=e[n.name];if(!i)throw new Error(`Function not loaded: ${n.name}`);try{let s=await Promise.resolve(i(...n.args||[]));he({type:"invr",id:n.id,result:s})}catch(s){console.error("An exception was thrown as a result of invoking function",n.name,"error:",s.message),he({type:"invr",id:n.id,error:s.message})}}break;case"sysr":{let i=n.id,s=st.get(i);if(!s)throw Error("Invalid request id");st.delete(i),n.error?s.reject(new Error(n.error)):s.resolve(n.result)}break}})().catch(console.error)}),he({type:"manifest",manifest:t}))}function kn(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}function lr(e){typeof e=="string"&&(e=new TextEncoder().encode(e));let t="",r=e.byteLength;for(let o=0;o<r;o++)t+=String.fromCharCode(e[o]);return btoa(t)}async function Fn(e,t){if(typeof e!="string"){let r=new Uint8Array(await e.arrayBuffer()),o=r.length>0?lr(r):void 0;t={method:e.method,headers:Object.fromEntries(e.headers.entries()),base64Body:o},e=e.url}return syscall("sandboxFetch.fetch",e,t)}globalThis.nativeFetch=globalThis.fetch;function Rn(){globalThis.fetch=async function(e,t){let r=t&&t.body?lr(new Uint8Array(await new Response(t.body).arrayBuffer())):void 0,o=await Fn(e,t&&{method:t.method,headers:t.headers,base64Body:r});return new Response(o.base64Body?kn(o.base64Body):null,{status:o.status,headers:o.headers})}}at&&Rn();function ct(e){if(e.children)for(let t of e.children){if(t.parent)return;t.parent=e,ct(t)}}function $n(e,t){return lt(e,r=>r.type===t)}function lt(e,t){if(t(e))return[e];let r=[];if(e.children)for(let o of e.children)r=[...r,...lt(o,t)];return r}async function ur(e,t){if(await t(e))return[e];let r=[];if(e.children)for(let o of e.children)r=[...r,...await ur(o,t)];return r}async function ut(e,t){if(e.children){let r=e.children.slice();for(let o of r){let n=await t(o);if(n!==void 0){let i=e.children.indexOf(o);n?e.children.splice(i,1,n):e.children.splice(i,1)}else await ut(o,t)}}}function pt(e,t){return lt(e,r=>r.type===t)[0]}async function Ie(e,t){await ur(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 mt(e,t=!0){if($n(e,"\u26A0").length>0)throw new Error(`Parse error in: ${R(e)}`);if(e.text!==void 0)return e.text;let o=[e.type];for(let n of e.children)n.type&&!n.type.endsWith("Mark")&&n.type!=="Comment"&&o.push(mt(n,t)),n.text&&(t&&n.text.trim()||!t)&&o.push(n.text);return o}function Ln(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 le(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(le);if(e instanceof Date)return Ln(e);let t={};for(let r of Object.keys(e)){let o=r.split("."),n=t;for(let i=0;i<o.length-1;i++){let s=o[i];n[s]||(n[s]={}),n=n[s]}n[o[o.length-1]]=le(e[r])}return t}var u={};_(u,{confirm:()=>mo,copyToClipboard:()=>vo,deleteLine:()=>To,dispatch:()=>uo,downloadFile:()=>Zn,filterBox:()=>ro,flashNotification:()=>to,fold:()=>ho,foldAll:()=>bo,getCurrentPage:()=>_n,getCursor:()=>jn,getSelection:()=>qn,getText:()=>Dn,getUiOption:()=>fo,goHistory:()=>Xn,hidePanel:()=>oo,insertAtCursor:()=>lo,insertAtPos:()=>io,moveCursor:()=>ao,moveCursorToLine:()=>co,navigate:()=>Kn,newWindow:()=>Jn,openCommandPalette:()=>Yn,openPageNavigator:()=>Gn,openSearchPanel:()=>So,openUrl:()=>zn,prompt:()=>po,redo:()=>Ao,reloadConfigAndCommands:()=>Vn,reloadPage:()=>Wn,reloadUI:()=>Qn,replaceRange:()=>so,save:()=>Bn,setSelection:()=>Hn,setText:()=>Un,setUiOption:()=>go,showPanel:()=>no,toggleFold:()=>xo,undo:()=>Po,unfold:()=>yo,unfoldAll:()=>wo,uploadFile:()=>eo,vimEx:()=>Eo});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function l(e,...t){return globalThis.syscall(e,...t)}function _n(){return l("editor.getCurrentPage")}function Dn(){return l("editor.getText")}function Un(e,t=!1){return l("editor.setText",e,t)}function jn(){return l("editor.getCursor")}function qn(){return l("editor.getSelection")}function Hn(e,t){return l("editor.setSelection",e,t)}function Bn(){return l("editor.save")}function Kn(e,t=!1,r=!1){return l("editor.navigate",e,t,r)}function Gn(e="page"){return l("editor.openPageNavigator",e)}function Yn(){return l("editor.openCommandPalette")}function Wn(){return l("editor.reloadPage")}function Qn(){return l("editor.reloadUI")}function Vn(){return l("editor.reloadConfigAndCommands")}function zn(e,t=!1){return l("editor.openUrl",e,t)}function Jn(){return l("editor.newWindow")}function Xn(e){return l("editor.goHistory",e)}function Zn(e,t){return l("editor.downloadFile",e,t)}function eo(e,t){return l("editor.uploadFile",e,t)}function to(e,t="info"){return l("editor.flashNotification",e,t)}function ro(e,t,r="",o=""){return l("editor.filterBox",e,t,r,o)}function no(e,t,r,o=""){return l("editor.showPanel",e,t,r,o)}function oo(e){return l("editor.hidePanel",e)}function io(e,t){return l("editor.insertAtPos",e,t)}function so(e,t,r){return l("editor.replaceRange",e,t,r)}function ao(e,t=!1){return l("editor.moveCursor",e,t)}function co(e,t=1,r=!1){return l("editor.moveCursorToLine",e,t,r)}function lo(e){return l("editor.insertAtCursor",e)}function uo(e){return l("editor.dispatch",e)}function po(e,t=""){return l("editor.prompt",e,t)}function mo(e){return l("editor.confirm",e)}function fo(e){return l("editor.getUiOption",e)}function go(e,t){return l("editor.setUiOption",e,t)}function ho(){return l("editor.fold")}function yo(){return l("editor.unfold")}function xo(){return l("editor.toggleFold")}function bo(){return l("editor.foldAll")}function wo(){return l("editor.unfoldAll")}function Po(){return l("editor.undo")}function Ao(){return l("editor.redo")}function So(){return l("editor.openSearchPanel")}function vo(e){return l("editor.copyToClipboard",e)}function To(){return l("editor.deleteLine")}function Eo(e){return l("editor.vimEx",e)}var k={};_(k,{parseMarkdown:()=>Co,renderParseTree:()=>Mo});function Co(e){return l("markdown.parseMarkdown",e)}function Mo(e){return l("markdown.renderParseTree",e)}var D={};_(D,{deleteAttachment:()=>Uo,deleteFile:()=>Ko,deletePage:()=>Fo,fileExists:()=>Go,getAttachmentMeta:()=>Lo,getFileMeta:()=>Ho,getPageMeta:()=>Oo,listAttachments:()=>$o,listFiles:()=>jo,listPages:()=>Io,listPlugs:()=>Ro,readAttachment:()=>_o,readFile:()=>qo,readPage:()=>No,writeAttachment:()=>Do,writeFile:()=>Bo,writePage:()=>ko});function Io(){return l("space.listPages")}function Oo(e){return l("space.getPageMeta",e)}function No(e){return l("space.readPage",e)}function ko(e,t){return l("space.writePage",e,t)}function Fo(e){return l("space.deletePage",e)}function Ro(){return l("space.listPlugs")}function $o(){return l("space.listAttachments")}function Lo(e){return l("space.getAttachmentMeta",e)}function _o(e){return l("space.readAttachment",e)}function Do(e,t){return l("space.writeAttachment",e,t)}function Uo(e){return l("space.deleteAttachment",e)}function jo(){return l("space.listFiles")}function qo(e){return l("space.readFile",e)}function Ho(e){return l("space.getFileMeta",e)}function Bo(e,t){return l("space.writeFile",e,t)}function Ko(e){return l("space.deleteFile",e)}function Go(e){return l("space.fileExists",e)}var S={};_(S,{applyAttributeExtractors:()=>Jo,getEnv:()=>ti,getMode:()=>ri,getSpaceConfig:()=>Xo,getVersion:()=>ni,invokeCommand:()=>Wo,invokeFunction:()=>Yo,invokeSpaceFunction:()=>zo,listCommands:()=>Qo,listSyscalls:()=>Vo,reloadConfig:()=>ei,reloadPlugs:()=>Zo});function Yo(e,...t){return l("system.invokeFunction",e,...t)}function Wo(e,t){return l("system.invokeCommand",e,t)}function Qo(){return l("system.listCommands")}function Vo(){return l("system.listSyscalls")}function zo(e,...t){return l("system.invokeSpaceFunction",e,...t)}function Jo(e,t,r){return l("system.applyAttributeExtractors",e,t,r)}async function Xo(e,t){return await l("system.getSpaceConfig",e)??t}function Zo(){return l("system.reloadPlugs")}function ei(){return l("system.reloadConfig")}function ti(){return l("system.getEnv")}function ri(){return l("system.getMode")}function ni(){return l("system.getVersion")}var Q={};_(Q,{del:()=>si,get:()=>ii,set:()=>oi});function oi(e,t){return l("clientStore.set",e,t)}function ii(e){return l("clientStore.get",e)}function si(e){return l("clientStore.delete",e)}var Oe={};_(Oe,{listLanguages:()=>ui,parseLanguage:()=>li});function li(e,t){return l("language.parseLanguage",e,t)}function ui(){return l("language.listLanguages")}var ne={};_(ne,{parseTemplate:()=>mi,renderTemplate:()=>pi});function pi(e,t,r={}){return l("template.renderTemplate",e,t,r)}function mi(e){return l("template.parseTemplate",e)}var ye={};_(ye,{dispatchEvent:()=>gi,listEvents:()=>hi});function gi(e,t,r){return new Promise((o,n)=>{let i=-1;r&&(i=setTimeout(()=>{console.log("Timeout!"),n("timeout")},r)),l("event.dispatch",e,t).then(s=>{i!==-1&&clearTimeout(i),o(s)}).catch(n)})}function hi(){return l("event.list")}var H={};_(H,{parse:()=>xi,stringify:()=>bi});function xi(e){return l("yaml.parse",e)}function bi(e){return l("yaml.stringify",e)}var oe={};_(oe,{ack:()=>Ai,batchAck:()=>Si,batchSend:()=>Pi,getQueueStats:()=>vi,send:()=>wi});function wi(e,t){return l("mq.send",e,t)}function Pi(e,t){return l("mq.batchSend",e,t)}function Ai(e,t){return l("mq.ack",e,t)}function Si(e,t){return l("mq.batchAck",e,t)}function vi(e){return l("mq.getQueueStats",e)}var Mi=/(!?\[\[)([^\]\|]+)(?:\|([^\]]+))?(\]\])/g;var Bc=new RegExp("^"+Mi.source);function pr(e){return e[0]!=="#"?(console.error("extractHashtag called on already clean string",e),e):e[1]==="<"?e.slice(-1)!==">"?e.slice(2):e.slice(2,-1):e.slice(1)}async function V(e,t={}){let r={tags:[]},o=[];ct(e),await ut(e,async n=>{if(n.type==="Paragraph"&&n.parent?.type==="Document"){let i=!0,s=new Set;for(let c of n.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=pr(c.children[0].text);s.add(a),(t.removeTags===!0||t.removeTags?.includes(a))&&(c.children[0].text="")}else if(c.type){i=!1;break}i&&o.push(...s)}if(n.type==="FrontMatter"){let i=n.children[1].children[0],s=R(i);try{let c=await H.parse(s),a={...c};if(r={...r,...c},r.tags||(r.tags=[]),typeof r.tags=="string"&&o.push(...r.tags.split(/,\s*|\s+/)),Array.isArray(r.tags)&&o.push(...r.tags),t.removeKeys&&t.removeKeys.length>0){let p=!1;for(let d of t.removeKeys)d in a&&(delete a[d],p=!0);p&&(i.text=await H.stringify(a))}if(Object.keys(a).length===0||t.removeFrontmatterSection)return null}catch{}}});try{r.tags=[...new Set([...o.map(n=>String(n).replace(/^#/,""))])]}catch(n){console.error("Error while processing tags",n)}return r=le(r),r}async function dt(e,t){let r=null;if(await Ie(e,async o=>{if(o.type==="FrontMatter"){let n=o.children[1].children[0],i=R(n);try{let s="";if(typeof t=="string")s=i+t+`
`;else{let a={...await H.parse(i),...t};s=await H.stringify(a)}r={changes:{from:n.from,to:n.to,insert:s}}}catch(s){console.error("Error parsing YAML",s)}return!0}return!1}),!r){let o="";typeof t=="string"?o=t+`
`:o=await H.stringify(t),r={changes:{from:0,to:0,insert:`---
`+o+`---
`}}}return r}function mr(e){let t={querySource:""},[r,o,...n]=e;if(r!=="Query")throw new Error(`Expected query type, got ${r}`);t.querySource=o[1];for(let i of n){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:xe(c[1][1])}):t.select.push({name:xe(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 xe(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]),xe(e[3][1])];case"Identifier":return["attr",xe(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[o,n,i,s]=r;t.push([n[1].slice(1,-1),M(s)])}return["object",t]}case"BinExpression":{let t=M(e[1]),r=e[2][0]==="in"?"in":e[2].trim(),o=M(e[3]);return[r,t,o]}case"LogicalExpression":{let t=M(e[1]),r=e[2],o=M(e[3]);return[r[1],t,o]}case"ParenthesizedExpression":return M(e[2]);case"Call":{let t=xe(e[1][1]),r=[];for(let o of e.slice(2))o[0]==="Expression"&&r.push(o);return["call",t,r.map(M)]}case"UnaryExpression":{if(e[1][0]==="not"||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,o,n,i,s]=e;return["?",M(r),M(n),M(s)]}case"QueryExpression":return["query",mr(e[2])];case"PageRef":return["pageref",e[1].slice(2,-2)];default:throw new Error(`Not supported: ${e[0]}`)}}async function dr(e){let t=mt(await Oe.parseLanguage("query",e));return mr(t[1])}async function fr(e,t){let r={};await Ie(t,async i=>{if(t!==i&&i.type==="ListItem")return!0;if(i.type==="Attribute"){let s=pt(i,"AttributeName"),c=pt(i,"AttributeValue");if(s&&c){let a=s.children[0].text,p=c.children[0].text;try{r[a]=le(await H.parse(p))}catch(d){console.error("Error parsing attribute value as YAML",p,d)}}return!0}return!1});let o=R(t),n=await S.applyAttributeExtractors(e,o,t);return r={...r,...n},r}function ft(e,t){if(t(e))return[e];let r=[];if(e.children)for(let o of e.children)r=[...r,...ft(o,t)];return r}function gt(e,t){return ft(e,r=>r.type===t)[0]}function gr(e,t){ft(e,t)}var be={};_(be,{confirm:()=>os,copyToClipboard:()=>gs,deleteLine:()=>hs,dispatch:()=>rs,downloadFile:()=>Gi,filterBox:()=>Qi,flashNotification:()=>Wi,fold:()=>as,foldAll:()=>us,getCurrentPage:()=>Ii,getCursor:()=>ki,getSelection:()=>Fi,getText:()=>Oi,getUiOption:()=>is,goHistory:()=>Ki,hidePanel:()=>zi,insertAtCursor:()=>ts,insertAtPos:()=>Ji,moveCursor:()=>Zi,moveCursorToLine:()=>es,navigate:()=>Li,newWindow:()=>Bi,openCommandPalette:()=>Di,openPageNavigator:()=>_i,openSearchPanel:()=>fs,openUrl:()=>Hi,prompt:()=>ns,redo:()=>ds,reloadConfigAndCommands:()=>qi,reloadPage:()=>Ui,reloadUI:()=>ji,replaceRange:()=>Xi,save:()=>$i,setSelection:()=>Ri,setText:()=>Ni,setUiOption:()=>ss,showPanel:()=>Vi,toggleFold:()=>ls,undo:()=>ms,unfold:()=>cs,unfoldAll:()=>ps,uploadFile:()=>Yi,vimEx:()=>ys});typeof self>"u"&&(self={syscall:()=>{throw new Error("Not implemented here")}});function m(e,...t){return globalThis.syscall(e,...t)}function Ii(){return m("editor.getCurrentPage")}function Oi(){return m("editor.getText")}function Ni(e,t=!1){return m("editor.setText",e,t)}function ki(){return m("editor.getCursor")}function Fi(){return m("editor.getSelection")}function Ri(e,t){return m("editor.setSelection",e,t)}function $i(){return m("editor.save")}function Li(e,t=!1,r=!1){return m("editor.navigate",e,t,r)}function _i(e="page"){return m("editor.openPageNavigator",e)}function Di(){return m("editor.openCommandPalette")}function Ui(){return m("editor.reloadPage")}function ji(){return m("editor.reloadUI")}function qi(){return m("editor.reloadConfigAndCommands")}function Hi(e,t=!1){return m("editor.openUrl",e,t)}function Bi(){return m("editor.newWindow")}function Ki(e){return m("editor.goHistory",e)}function Gi(e,t){return m("editor.downloadFile",e,t)}function Yi(e,t){return m("editor.uploadFile",e,t)}function Wi(e,t="info"){return m("editor.flashNotification",e,t)}function Qi(e,t,r="",o=""){return m("editor.filterBox",e,t,r,o)}function Vi(e,t,r,o=""){return m("editor.showPanel",e,t,r,o)}function zi(e){return m("editor.hidePanel",e)}function Ji(e,t){return m("editor.insertAtPos",e,t)}function Xi(e,t,r){return m("editor.replaceRange",e,t,r)}function Zi(e,t=!1){return m("editor.moveCursor",e,t)}function es(e,t=1,r=!1){return m("editor.moveCursorToLine",e,t,r)}function ts(e){return m("editor.insertAtCursor",e)}function rs(e){return m("editor.dispatch",e)}function ns(e,t=""){return m("editor.prompt",e,t)}function os(e){return m("editor.confirm",e)}function is(e){return m("editor.getUiOption",e)}function ss(e,t){return m("editor.setUiOption",e,t)}function as(){return m("editor.fold")}function cs(){return m("editor.unfold")}function ls(){return m("editor.toggleFold")}function us(){return m("editor.foldAll")}function ps(){return m("editor.unfoldAll")}function ms(){return m("editor.undo")}function ds(){return m("editor.redo")}function fs(){return m("editor.openSearchPanel")}function gs(e){return m("editor.copyToClipboard",e)}function hs(){return m("editor.deleteLine")}function ys(e){return m("editor.vimEx",e)}var Ne={};_(Ne,{parseMarkdown:()=>xs,renderParseTree:()=>bs});function xs(e){return m("markdown.parseMarkdown",e)}function bs(e){return m("markdown.renderParseTree",e)}var ke={};_(ke,{deleteAttachment:()=>Os,deleteFile:()=>$s,deletePage:()=>vs,fileExists:()=>Ls,getAttachmentMeta:()=>Cs,getFileMeta:()=>Fs,getPageMeta:()=>Ps,listAttachments:()=>Es,listFiles:()=>Ns,listPages:()=>ws,listPlugs:()=>Ts,readAttachment:()=>Ms,readFile:()=>ks,readPage:()=>As,writeAttachment:()=>Is,writeFile:()=>Rs,writePage:()=>Ss});function ws(){return m("space.listPages")}function Ps(e){return m("space.getPageMeta",e)}function As(e){return m("space.readPage",e)}function Ss(e,t){return m("space.writePage",e,t)}function vs(e){return m("space.deletePage",e)}function Ts(){return m("space.listPlugs")}function Es(){return m("space.listAttachments")}function Cs(e){return m("space.getAttachmentMeta",e)}function Ms(e){return m("space.readAttachment",e)}function Is(e,t){return m("space.writeAttachment",e,t)}function Os(e){return m("space.deleteAttachment",e)}function Ns(){return m("space.listFiles")}function ks(e){return m("space.readFile",e)}function Fs(e){return m("space.getFileMeta",e)}function Rs(e,t){return m("space.writeFile",e,t)}function $s(e){return m("space.deleteFile",e)}function Ls(e){return m("space.fileExists",e)}var Fe={};_(Fe,{parse:()=>Ws,stringify:()=>Qs});function Ws(e){return m("yaml.parse",e)}function Qs(e){return m("yaml.stringify",e)}async function Zs(e,t){let r=await ke.readPage(e),o=await Ne.parseMarkdown(r),n;return gr(o,i=>{if(i.type!=="FencedCode")return!1;let s=gt(i,"CodeInfo");if(t&&!s||t&&!t.includes(s.children[0].text))return!1;let c=gt(i,"CodeText");return c?(n=c.children[0].text,!0):!1}),n}async function hr(e,t=["yaml"]){let r=await Zs(e,t);if(r!==void 0)try{return Fe.parse(r)}catch(o){throw console.error("YAML Page parser error",o),new Error(`YAML Error: ${o.message}`)}}async function Re(e){try{let r=(await hr("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 ue=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,o,n,i=!0){this.apiKey=t,this.baseUrl=r,this.name=o,this.modelName=n,this.requireAuth=i}};var $e=class extends ue{constructor(t,r,o){super(t,o,"DALL-E",r)}async generateImage(t){try{C||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 o=await r.json();if(!o||o.length===0)throw new Error("Invalid response from DALL-E.");return o}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,o){this.listeners[r]===void 0&&(this.listeners[r]=[]),this.listeners[r].indexOf(o)===-1&&this.listeners[r].push(o)},this.removeEventListener=function(r,o){if(this.listeners[r]!==void 0){var n=[];this.listeners[r].forEach(function(i){i!==o&&n.push(i)}),n.length===0?delete this.listeners[r]:this.listeners[r]=n}},this.dispatchEvent=function(r){if(!r)return!0;this.debug&&console.debug(r),r.source=this;var o="on"+r.type;return this.hasOwnProperty(o)&&(this[o].call(this,r),r.defaultPrevented)?!1:this.listeners[r.type]?this.listeners[r.type].every(function(n){return n(r),!r.defaultPrevented}):!0},this._setReadyState=function(r){var o=new CustomEvent("readystatechange");o.readyState=r,this.readyState=r,this.dispatchEvent(o)},this._onStreamFailure=function(r){var o=new CustomEvent("error");o.data=r.currentTarget.response,this.dispatchEvent(o),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 o=this.xhr.responseText.substring(this.progress);this.progress+=o.length;var n=(this.chunk+o).split(/(\r\n\r\n|\r\r|\n\n)/g),i=n.pop();n.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 o={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 o&&(c==="data"&&o[c]!==null?o.data+=`
`+a:o[c]=a)}.bind(this));var n=new CustomEvent(o.event||"message");return n.data=o.data||"",n.id=o.id,n},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 yr={};function Le(e,t){yr[e]=t}function _e(e){return yr[e]}async function De(...e){let t=e.join(""),r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")}var G=class{apiKey;baseUrl;name;modelName;requireAuth;constructor(t,r,o,n,i=!0){this.apiKey=t,this.baseUrl=r,this.name=o,this.modelName=n,this.requireAuth=i}async generateEmbeddings(t){let r=await De(this.modelName,t.text),o=_e(r);if(o)return o;let n=await this._generateEmbeddings(t);return Le(r,n),n}};async function ht(){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 Ue(){let e=await ht(),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 yt(e,t){let r=e.split(`
`),o=0;for(let n=0;n<r.length;n++){if(o<=t&&t<o+r[n].length+1)return n;o+=r[n].length+1}return-1}function xt(e,t){let r=e.split(`
`);return t<0||t>=r.length?"":r[t]}function br(e,t){let r=yt(e,t);return xt(e,r)}function wr(e,t){let r=yt(e,t);return xt(e,r-1)}function Pr(e,t){let r=yt(e,t);return xt(e,r+1)}function Ar(e,t){let r=e.split(`
`),o=0,n=0,i=e.length;for(let s=0;s<r.length;s++){let c=r[s].length+1;if(o<=t&&t<o+c){console.log("Looking backwards for the start of the paragraph");for(let a=s;a>=0;a--)if(a===0||r[a-1].trim()===""){n=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<r.length;a++)if(a===r.length-1||r[a+1].trim()===""){i=r.slice(0,a+1).join(`
`).length;break}break}o+=c}return console.log("Found paragraph",e.slice(n,i)),{from:n,to:i,text:e.slice(n,i)}}var Y=class{name;apiKey;baseUrl;modelName;constructor(t,r,o,n){this.name=t,this.apiKey=r,this.baseUrl=o,this.modelName=n}async streamChatIntoEditor(t,r){let{onDataReceived:o,onResponseComplete:n,postProcessors:i}=t,s="\u{1F914} Thinking \u2026 ",c=r??await se();await u.insertAtPos(s,c);let a=!0,p=c,d=h=>{try{if(!h){console.log("No data received from LLM");return}a?(["`","-","*"].includes(h.charAt(0))&&(h=`
`+h),u.replaceRange(c,c+s.length,h),a=!1):u.insertAtPos(h,c),c+=h.length,o&&o(h)}catch(x){console.error("Error handling chat stream data:",x),u.flashNotification("An error occurred while processing chat data.","error")}},f=async h=>{console.log("Response complete:",h);let x=p+h.length;console.log("Start of response:",p),console.log("End of response:",x),console.log("Full response:",h),console.log("Post-processors:",i);let b=h;if(i){let A=await u.getText(),w={response:h,lineBefore:wr(A,p),lineCurrent:br(A,p),lineAfter:Pr(A,x)};for(let N of i)console.log("Applying post-processor:",N),b=await S.invokeSpaceFunction(N,w);console.log("Data changed by post-processors, updating editor"),u.replaceRange(p,x,b)}n&&n(h)};await this.chatWithAI({...t,onDataReceived:d,onResponseComplete:f})}async singleMessageChat(t,r,o=!1){let n=[{role:"user",content:t}];return r&&n.unshift({role:"system",content:r}),o&&(n=await pe(n)),await this.chatWithAI({messages:n,stream:!1})}};var je=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:o}){return r?await this.streamChat({messages:t,stream:r,onDataReceived:o}):await this.nonStreamingChat(t)}mapRolesForGemini(t){let r=[],o="";return t.forEach(n=>{let i="user";n.role==="system"||n.role==="user"?i="user":n.role==="assistant"&&(i="model"),i==="model"&&(r.length===0||o==="model")||(i==="user"&&o==="user"?r[r.length-1].parts[0].text+=" "+n.content:r.push({role:i,parts:[{text:n.content}]})),o=i}),r}streamChat(t){let{messages:r,onDataReceived:o}=t;try{let n=`${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(n,c),p="";a.addEventListener("message",d=>{try{if(d.data=="[DONE]")return a.close(),p;if(!d.data)console.error("Received empty message from Gemini"),console.log("source: ",a);else{let f=JSON.parse(d.data),h=f.candidates[0].content.parts[0].text||f.text||"";p+=h,o&&o(h)}}catch(f){console.error("Error processing message event:",f,d.data)}}),a.addEventListener("end",()=>(a.close(),p)),a.addEventListener("error",d=>{console.error("SSE error:",d),a.close()}),a.stream()}catch(n){throw console.error("Error streaming from Gemini chat endpoint:",n),n}}async nonStreamingChat(t){let r=this.mapRolesForGemini(t),o=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(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return(await o.json()).candidates[0].content.parts[0].text}},qe=class extends G{constructor(t,r,o="https://generativelanguage.googleapis.com",n=!0){super(t,o,"Gemini",r,n)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,content:{parts:[{text:t.text}]}}),o={"Content-Type":"application/json"};this.requireAuth&&(o.Authorization=`Bearer ${this.apiKey}`);let n=await nativeFetch(`${this.baseUrl}/v1beta/models/${this.modelName}:embedContent?key=${this.apiKey}`,{method:"POST",headers:o,body:r});if(!n.ok)throw console.error("HTTP response: ",n),console.error("HTTP response body: ",await n.json()),new Error(`HTTP error, status: ${n.status}`);let i=await n.json();if(!i||!i.embedding||!i.embedding.values)throw new Error("Invalid response from Gemini.");return i.embedding.values}};var me=class extends Y{name="OpenAI";requireAuth;constructor(t,r,o,n){super("OpenAI",t,o,r),this.requireAuth=n}async chatWithAI({messages:t,stream:r,onDataReceived:o,onResponseComplete:n}){return r?await this.streamChat({messages:t,onDataReceived:o,onResponseComplete:n}):await this.nonStreamingChat(t)}async streamChat(t){let{messages:r,onDataReceived:o,onResponseComplete:n}=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(d){try{if(d.data=="[DONE]")return a.close(),n&&n(p),p;{let h=JSON.parse(d.data).choices[0]?.delta?.content||"";p+=h,o&&o(h)}}catch(f){console.error("Error processing message event:",f,d.data)}}),a.addEventListener("end",function(){return a.close(),n&&n(p),p}),a.addEventListener("error",d=>{console.error("SSE error sseEvent.data:",d.data," ssEventObj:",d),a.close()}),a.stream()}catch(i){throw console.error("Error streaming from OpenAI chat endpoint:",i),await be.flashNotification("Error streaming from OpenAI chat endpoint.","error"),i}return""}async listModels(){try{let t={"Content-Type":"application/json"};this.requireAuth&&(t.Authorization=`Bearer ${this.apiKey}`);let r=await nativeFetch(`${this.baseUrl}/models`,{method:"GET",headers:t});if(!r.ok)throw console.error("HTTP response: ",r),console.error("HTTP response body: ",await r.json()),new Error(`HTTP error, status: ${r.status}`);let o=await r.json();if(!o||!o.data)throw new Error("Invalid response from OpenAI models endpoint.");return o.data.map(n=>n.id)}catch(t){throw console.error("Error fetching OpenAI models:",t),t}}async nonStreamingChat(t){try{let r=JSON.stringify({model:this.modelName,messages:t}),o={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},n=await nativeFetch(this.baseUrl+"/chat/completions",{method:"POST",headers:o,body:r});if(!n.ok)throw console.error("http response: ",n),console.error("http response body: ",await n.json()),new Error(`HTTP error, status: ${n.status}`);let i=await n.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 be.flashNotification("Error calling OpenAI chat endpoint.","error"),r}}},He=class extends G{constructor(t,r,o,n=!0){super(t,o,"OpenAI",r,n)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,input:t.text,encoding_format:"float"}),o={"Content-Type":"application/json"};this.requireAuth&&(o.Authorization=`Bearer ${this.apiKey}`);let n=await nativeFetch(`${this.baseUrl}/embeddings`,{method:"POST",headers:o,body:r});if(!n.ok)throw console.error("HTTP response: ",n),console.error("HTTP response body: ",await n.json()),new Error(`HTTP error, status: ${n.status}`);let i=await n.json();if(!i||!i.data||i.data.length===0)throw new Error("Invalid response from OpenAI.");return i.data[0].embedding}};var Be=class extends Y{name="Ollama";requireAuth;openaiProvider;constructor(t,r,o,n){super("Ollama",t,o,r),this.requireAuth=n,this.openaiProvider=new me(t,r,o,n)}async chatWithAI({messages:t,stream:r,onDataReceived:o,onResponseComplete:n}){return await this.openaiProvider.chatWithAI({messages:t,stream:r,onDataReceived:o,onResponseComplete:n})}async listModels(){try{let t={"Content-Type":"application/json"};this.requireAuth&&(t.Authorization=`Bearer ${this.apiKey}`);let r=await nativeFetch(`${this.baseUrl.replace(/\/v1\/?/,"")}/api/tags`,{method:"GET",headers:t});if(!r.ok)throw console.error("HTTP response: ",r),console.error("HTTP response body: ",await r.json()),new Error(`HTTP error, status: ${r.status}`);let o=await r.json();if(!o||!o.models)throw new Error("Invalid response from Ollama models endpoint.");return o.models.map(n=>n.name)}catch(t){throw console.error("Error fetching Ollama models:",t),t}}},Ke=class extends G{constructor(t,r,o,n=!1){super(t,o,"Ollama",r,n)}async _generateEmbeddings(t){let r=JSON.stringify({model:this.modelName,prompt:t.text}),o={"Content-Type":"application/json"};this.requireAuth&&(o.Authorization=`Bearer ${this.apiKey}`);let n=await nativeFetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:o,body:r});if(!n.ok)throw console.error("HTTP response: ",n),console.error("HTTP response body: ",await n.json()),new Error(`HTTP error, status: ${n.status}`);let i=await n.json();if(!i||!i.embedding||i.embedding.length===0)throw new Error("Invalid response from Ollama.");return i.embedding}};var Ge=class extends Y{constructor(t,r,o="http://localhost"){super(t,o,"mock",r)}async chatWithAI(t){let r="This is a mock response from the AI.";if(t.onDataReceived)for(let o of r)await new Promise(n=>setTimeout(n,50)),t.onDataReceived(o);return r}listModels(){return Promise.resolve(["mock-gpt-3.5","mock-gpt-4","mock-claude-2",this.modelName])}},Ye=class extends ue{constructor(t,r,o="http://localhost"){super(t,o,"mock",r)}generateImage(t){return new Promise(r=>{setTimeout(()=>{r("https://example.com/mock-image.jpg")},5)})}},We=class extends G{constructor(t,r,o="http://localhost"){super(t,o,"mock",r)}_generateEmbeddings(t){return new Promise(r=>{setTimeout(()=>{let o=Array(1536).fill(0).map(()=>Math.random());r(o)},5)})}};var C,g,we,O,Qe,$,bt,ea,Pe;async function T(){let e=await Ve();(!C||!O||!g||!bt||JSON.stringify(e)!==JSON.stringify(bt))&&await z(!0)}async function Ve(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedTextModel")}catch{return}}async function wt(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedImageModel")}catch{return}}async function Pt(){if(await S.getEnv()!="server")try{return await Q.get("ai.selectedEmbeddingModel")}catch{return}}async function At(e){await S.getEnv()!="server"&&await Q.set("ai.selectedImageModel",e)}async function St(e){await S.getEnv()!="server"&&await Q.set("ai.selectedTextModel",e)}async function vt(e){await S.getEnv()!="server"&&await Q.set("ai.selectedEmbeddingModel",e)}async function ta(){let e=await Ve()||g.textModels[0];if(!e)throw new Error("No text model selected or available as default.");await ae(e)}async function ra(){let e=await wt()||g.imageModels[0];if(!e)throw new Error("No image model selected or available as default.");await Tt(e)}async function na(){let e=await Pt()||g.embeddingModels[0];if(!e)throw new Error("No embedding model selected or available as default.");await Ae(e)}function oa(e){let t=e.provider.toLowerCase();switch(U("client","Provider name",t),t){case"dalle":Qe=new $e(C,e.modelName,e.baseUrl||g.dallEBaseUrl);break;case"mock":Qe=new Ye(C,e.modelName);break;default:throw new Error(`Unsupported image provider: ${e.provider}. Please configure a supported provider.`)}}function ia(e){switch(e.provider.toLowerCase()){case"openai":O=new me(C,e.modelName,e.baseUrl||g.openAIBaseUrl,e.requireAuth||g.requireAuth);break;case"gemini":O=new je(C,e.modelName);break;case"ollama":O=new Be(C,e.modelName,e.baseUrl||"http://localhost:11434/v1",e.requireAuth);break;case"mock":O=new Ge(C,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported AI provider: ${e.provider}. Please configure a supported provider.`)}return O}function sa(e){switch(e.provider.toLowerCase()){case"openai":$=new He(C,e.modelName,e.baseUrl||g.openAIBaseUrl);break;case"gemini":$=new qe(C,e.modelName);break;case"ollama":$=new Ke(C,e.modelName,e.baseUrl||"http://localhost:11434",e.requireAuth);break;case"mock":$=new We(C,e.modelName,e.baseUrl);break;default:throw new Error(`Unsupported embedding provider: ${e.provider}. Please configure a supported provider.`)}}async function ae(e){if(U("client","configureSelectedModel called with:",e),!e)throw new Error("No model provided to configure");if(e.requireAuth=e.requireAuth??g.requireAuth,e.requireAuth)try{let t=await Re(e.secretName||"OPENAI_API_KEY");t!==C&&(C=t,U("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&&!C)throw new Error("AI API key is missing. Please set it in the secrets page.");return bt=e,ia(e)}async function Tt(e){if(U("client","configureSelectedImageModel called with:",e),!e)throw new Error("No image model provided to configure");if(e.requireAuth){let t=await Re(e.secretName||"OPENAI_API_KEY");t!==C&&(C=t,U("client","API key updated for image model"))}if(e.requireAuth&&!C)throw new Error("AI API key is missing for image model. Please set it in the secrets page.");ea=e,oa(e)}async function Ae(e){if(U("client","configureSelectedEmbeddingModel called with:",e),!e)throw new Error("No embedding model provided to configure");if(e.requireAuth){let t=await Re(e.secretName||"OPENAI_API_KEY");t!==C&&(C=t,U("client","API key updated for embedding model"))}if(e.requireAuth&&!C)throw new Error("AI API key is missing for embedding model. Please set it in the secrets page.");Pe=e,sa(e)}async function aa(){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:""},o=await S.getSpaceConfig("ai",{}),n={...e,...o};return n.chat={...t,...o.chat||{}},n.promptInstructions={...r,...o.promptInstructions||{}},n}async function z(e=!0){let t=await aa();!g||JSON.stringify(g)!==JSON.stringify(t)?(U("client","aiSettings updating from",g),g=t,U("client","aiSettings updated to",g)):U("client","aiSettings unchanged",g),g.textModels.length===1&&await St(g.textModels[0]),g.imageModels.length===1&&await At(g.imageModels[0]),g.embeddingModels.length===1&&await vt(g.embeddingModels[0]),e&&(g.textModels.length>0&&await ta(),g.imageModels.length>0&&await ra(),g.embeddingModels.length>0&&await na()),we={role:"system",content:"This is an interactive chat session with a user in a markdown-based note-taking tool called SilverBullet."},g.chat.userInformation&&(we.content+=`
The user has provided the following information about themselves: ${g.chat.userInformation}`),g.chat.userInstructions&&(we.content+=`
The user has provided the following instructions for the chat, follow them as closely as possible: ${g.chat.userInstructions}`)}var Et="\u{1F916} ";function Se(e){return!(["SETTINGS","SECRETS",...g.indexEmbeddingsExcludePages].includes(e)||e.startsWith("_")||e.startsWith("Library/")||/\.conflicted\.\d+$/.test(e))}async function Sr(){return await T(),g.indexEmbeddings&&$!==void 0&&Pe!==void 0&&g.embeddingModels.length>0&&await S.getEnv()==="server"}async function vr(){return await T(),g.indexEmbeddings&&g.indexSummary&&$!==void 0&&Pe!==void 0&&g.embeddingModels.length>0&&await S.getEnv()==="server"}async function ca(e){if(!await Sr()||!Se(e))return;let t=await D.readPage(e),r=await k.parseMarkdown(t);if(!r.children)return;let o=r.children.filter(a=>a.type==="Paragraph"),n=[],i=Date.now();for(let a of o){let p=R(a).trim();if(!p||p.length<10||g.indexEmbeddingsExcludeStrings.some(x=>p.includes(x)))continue;let d=await $.generateEmbeddings({text:p}),f=a.from??0,h={ref:`${e}@${f}`,page:e,pos:f,embedding:d,text:p,tag:"embedding"};n.push(h)}await kt(e,n);let c=(Date.now()-i)/1e3;U("any",`AI: Indexed ${n.length} embedding objects for page ${e} in ${c} seconds`)}async function la(e){if(!await vr()||!Se(e))return;let t=await D.readPage(e),r=await k.parseMarkdown(t);if(!r.children)return;let o=Date.now(),n=R(r),i=g.textModels.find(b=>b.name===g.indexSummaryModelName);if(!i)throw new Error(`Could not find summary model ${g.indexSummaryModelName}`);let s=await ae(i),c;g.promptInstructions.indexSummaryPrompt!==""?c=g.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 De(i.name,n,c),p=_e(a);p||(p=await s.singleMessageChat("Contents of "+e+`:
`+n+`
`+c),Le(a,p));let d=await $.generateEmbeddings({text:p}),f={ref:`${e}@0`,page:e,embedding:d,text:p,tag:"aiSummary"};await kt(e,[f]);let x=(Date.now()-o)/1e3;U("any",`AI: Indexed summary for page ${e} in ${x} seconds`)}async function Tr({name:e,tree:t}){await T(),Se(e)&&t.children&&(await Sr()&&await oe.send("aiEmbeddingsQueue",e),await vr()&&await oe.send("aiSummaryQueue",e))}async function Er(e){await T();for(let r of e){let o=r.body;console.log(`AI: Generating and indexing embeddings for file ${o}`),await ca(o)}let t=await oe.getQueueStats("aiEmbeddingsQueue");console.log(`AI: Embeddings queue stats: ${JSON.stringify(t)}`)}async function Cr(e){await T();for(let r of e){let o=r.body;console.log(`AI: Generating and indexing summary for ${o}`),await la(o)}let t=await oe.getQueueStats("aiSummaryQueue");console.log(`AI: Summary queue stats: ${JSON.stringify(t)}`)}async function Mt(){return await Ft()?await l("system.invokeFunctionOnServer","index.queryObjects","embedding",{}):await Nt("embedding",{})}async function Mr(){return await Ft()?await l("system.invokeFunctionOnServer","index.queryObjects","aiSummary",{}):await Nt("aiSummary",{})}async function Ir(e){if(await T(),!$||!Pe)throw new Error("No embedding provider found");return await $.generateEmbeddings({text:e})}async function ve(e){return await l("system.invokeFunctionOnServer","silverbullet-ai.generateEmbeddings",e)}function Ct(e,t){let r=e.reduce((i,s,c)=>i+s*t[c],0),o=Math.sqrt(e.reduce((i,s)=>i+s*s,0)),n=Math.sqrt(t.reduce((i,s)=>i+s*s,0));return r/(o*n)}async function It(e,t=10,r=!1){await T(),await S.getEnv()==="server"&&(r=!1);let o=Date.now(),n=typeof e=="string"?await ve(e):e,i=Date.now();console.log(`searchEmbeddings: Query embedding generation took ${i-o} ms`);let s=Date.now(),c=await Mt(),a=Date.now();console.log(`Retrieved ${c.length} embeddings in ${a-s} ms`);let p="",d=0;r&&(p=`Retrieved ${c.length} embeddings in ${a-s} ms
`,d=(await u.getText()).length,await u.replaceRange(d,d,p));let f=[],h=Date.now();for(let x=0;x<c.length;x++){let b=c[x];if(Se(b.page)){if(f.push({page:b.page,ref:b.ref,text:b.text,similarity:Ct(n,b.embedding)}),r&&(x%100===0||Date.now()-h>=100)){let A=d+p.length;p=`
Processed ${x+1} of ${c.length} embeddings...
`,await u.replaceRange(d,A,p),h=Date.now()}if(r&&x>=c.length-1){let A=d+p.length;await u.replaceRange(d,A,"")}}}if(console.log(`Finished searching embeddings in ${Date.now()-s} ms`),g.indexSummary){let x=Date.now(),b=await Mr(),A=Date.now();console.log(`Retrieved ${b.length} summaries in ${A-x} ms`);let w="",N=0;r&&(w=`Retrieved ${b.length} summaries in ${A-x} ms
`,N=(await u.getText()).length,await u.replaceRange(N,N,w));let J=[],v=Date.now();for(let F=0;F<b.length;F++){let X=b[F];if(Se(X.page)){if(J.push({page:X.page,ref:X.ref,text:`Page Summary: ${X.text}`,similarity:Ct(n,X.embedding)}),r&&(F%100===0||Date.now()-v>=100)){let E=N+w.length;w=`
Processed ${F+1} of ${b.length} summaries...
`,await u.replaceRange(N,E,w),v=Date.now()}if(r&&F>=b.length-1){let E=N+w.length;await u.replaceRange(N,E,"")}}}console.log(`Finished searching summaries in ${Date.now()-x} ms`),f.push(...J)}return f.sort((x,b)=>b.similarity-x.similarity).slice(0,t)}async function Or(e,t=10){await T();let r=await ve(e);return(await Mr()).map(i=>({page:i.page,ref:i.ref,text:i.text,similarity:Ct(r,i.embedding)})).sort((i,s)=>s.similarity-i.similarity).slice(0,t)}async function ze(e,t=10,r=.15,o=!1){let n=await It(e,-1,o),i={};for(let c of n)c.similarity<r||(i[c.page]?(i[c.page].score+=c.similarity,i[c.page].children.push(c)):i[c.page]={page:c.page,score:c.similarity,children:[c]});for(let c in i)i[c].children=i[c].children.sort((a,p)=>p.similarity-a.similarity).slice(0,t);return Object.values(i).sort((c,a)=>a.score-c.score).slice(0,t)}async function Je(e,t=10){try{let r=await ze(e,t),o="";if(r.length>0)for(let n of r){o+=`>>${n.page}<<
`;for(let i of n.children)o+=`> ${i.text}
`}else return"No relevant pages found.";return o}catch(r){return console.error("Error in searchEmbeddingsForChat:",r),"An error occurred during the search."}}function Nr(e){return{data:new TextEncoder().encode(""),meta:{name:e,contentType:"text/markdown",size:0,created:0,lastModified:0,perm:"ro"}}}function Ot(e){return{name:e,contentType:"text/markdown",size:-1,created:0,lastModified:0,perm:"ro"}}function kr(e){return Ot(e)}async function Fr(){let e=await u.getCurrentPage();if(e.startsWith(Et)){await T();let t=e.substring(Et.length),r=`# Search results for "${t}"`,o=r+`
`;if(!g.indexEmbeddings){o+=`> **warning** Embeddings generation is disabled.
`,o+=`> You can enable it in the AI settings.
`,await u.setText(o);return}let n=`${r}
Searching for "${t}"...`;n+=`
Generating query vector embeddings..`,await u.setText(n);let i=[];try{i=await ve(t)}catch(a){console.error("Error generating query vector embeddings",a),n+=`
> **error** \u26A0\uFE0F Failed to generate query vector embeddings.
`,n+=`> ${a}
`,await u.setText(n);return}n+=`
Searching for similar embeddings...`,await u.setText(n);let s=[];try{s=await ze(i,void 0,void 0,!0)}catch(a){console.error("Error searching embeddings",a),n+=`
> **error** \u26A0\uFE0F Failed to search through embeddings.
`,n+=`> ${a}
`,await u.setText(n);return}let c=n.length;o=r+`
`,s.length===0&&(o+=`No results found.
`);for(let a of s){o+=`## [[${a.page}]]
`;for(let p of a.children){let f=p.ref.split("@")[1].padStart(4," ");o+=`> [[${p.ref}|${f}]] | ${p.text}
`}}await u.replaceRange(0,c,o)}}async function Rr(){let e=await u.prompt("Search for: ");e&&await u.navigate({page:`${Et}${e}`})}function $r(e){return e.split("/").slice(0,-1).join("/")}async function U(e,...t){(await S.getEnv()===e||e==="any")&&console.log(...t)}async function Te(e,t){let r=await dr(e);return ua(r,t)}async function ua(e,t){e.limit||(e.limit=["number",1e3]);let r=`query:${e.querySource}`,o={query:e};t&&(o.variables=t);let n=await ye.dispatchEvent(r,o,30*1e3);if(n.length===0)throw new Error(`Unsupported query source '${e.querySource}'`);return n.flat()}async function Nt(e,t){return await S.invokeFunction("index.queryObjects",e,t)}async function kt(e,t){return await S.invokeFunction("index.indexObjects",e,t)}async function Xe(e){e||(e=await u.getText());let t=await k.parseMarkdown(e);await V(t,{removeFrontmatterSection:!0}),e=R(t);let r=e.split(`
`),o=[],n="user",i="";return r.forEach(s=>{if(s.trim()==="")return;let c=s.match(/^\*\*(\w+)\*\*:/);if(c){let a=c[1].toLowerCase();n&&n!==a&&i.trim()!==""&&(o.push({role:n,content:i.trim()}),i=""),n=a,i+=s.replace(/^\*\*(\w+)\*\*:/,"").trim()+`
`}else n&&(i+=s.trim()+`
`)}),i&&n&&o.push({role:n,content:i.trim()}),o}async function Lr(){try{let e=await l("system.getVersion"),[t,r,o]=e.split(".").map(Number),[n,i,s]="0.7.2".split(".").map(Number);return t>n||t===n&&r>i||t===n&&r===i&&o>=s}catch{return!1}}async function Ft(){try{return(await S.listSyscalls()).some(t=>t.name==="system.invokeFunctionOnServer")}catch{return!1}}async function pe(e,t){let r=[],o,n;try{o=await u.getCurrentPage(),n=await D.getPageMeta(o)}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 k.parseMarkdown(i.content),c=await fr([],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"&&(n?(console.log("Rendering template",i.content,n),a=await ne.renderTemplate(i.content,n,{page:n,...t})):console.log("No page metadata found, skipping template rendering")),g.chat.searchEmbeddings&&g.indexEmbeddings){let h=await Je(a);h!=="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+=h)}if(g.chat.parseWikiLinks&&(a=await pa(a)),g.chat.bakeMessages){let h=await k.parseMarkdown(a),x=await S.invokeFunction("markdown.expandCodeWidgets",h,"");a=R(x).trim()}let d=(await ye.dispatchEvent("ai:enrichMessage",{enrichedContent:a,message:i})).flat().concat(g.chat.customEnrichFunctions),f=[...new Set(d)];console.log("Received custom enrich message functions",f);for(let h of f)a=await S.invokeSpaceFunction(h,a);r.push({...i,content:a})}return r}async function pa(e){let t=[],r=e,o=/\[\[([^\]]+)\]\]/g,n,i=!1;for(;(n=o.exec(e))!==null;){let s=n[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 D.readPage(s);t.push(s),r+=`
Content of the [[${s}]] page:
~~~
${c}
~~~
`}catch(c){console.error(`Error fetching page '${s}':`,c)}}}return r=r.replace(o,">>$1<<"),r}async function _r(e,t={},r={}){try{let o=await k.parseMarkdown(e),n=await V(o,{removeFrontmatterSection:!0,removeTags:["template"]});e=R(o).trimStart();let i;return n.frontmatter&&(typeof n.frontmatter=="string"?i=n.frontmatter:i=await H.stringify(n.frontmatter),i=await ne.renderTemplate(i,t,r)),{frontmatter:n,renderedFrontmatter:i,text:await ne.renderTemplate(e,t,r)}}catch(o){throw console.error("Error rendering template",o),o}}async function Dr(e){return Lr()?{options:(await Te("template where aiprompt and aiprompt.slashCommand")).map(r=>{let o=r.aiprompt;return{label:o.slashCommand,detail:o.description||r.description,order:o.order||0,templatePage:r.ref,pageName:e.pageName,invoke:"silverbullet-ai.insertAiPromptFromTemplate"}})}:void 0}async function Ur(e){let t;if(!e||!e.templatePage){let E=await Te("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 D.readPage(e.templatePage),q=await k.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 T();let o,n,i;try{o=await D.readPage(t.ref),n=await u.getCurrentPage(),i=await D.getPageMeta(n)}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,d,f,h,x,b,A,w,N,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),d=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")&&(f=await S.invokeFunction("editor.determineItemBounds",s,a,void 0,!0),h=s.slice(f.from,f.to),x=await S.invokeFunction("editor.determineItemBounds",s,a,0,!0),b=s.slice(x.from,x.to))}catch(E){console.error("Error fetching current item",E)}try{(t.insertAt==="replace-paragraph"||t.insertAt==="replace-smart")&&(A=Ar(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")&&(w=await ht())}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,d,"");break;case"replace-selection":w?.text?(v=w.from,await u.replaceRange(w.from,w.to,"")):v=await u.getCursor();break;case"replace-paragraph":A?.text?(v=A.from,await u.replaceRange(A.from,A.to,"")):await u.flashNotification("Error: current paragraph is undefined","error");break;case"replace-smart":if(w?.text)N="selected-text",J=w.text,v=w.from,await u.replaceRange(w.from,w.to,"");else if(h&&f)N="current-item",J=h,v=f.from,await u.replaceRange(f.from,f.to,`
`);else if(A?.text)N="current-paragraph",J=A.text,v=A.from,await u.replaceRange(A.from,A.to,"");else{await u.flashNotification("Error: replace-smart: no text selected, current paragraph, or current item","error");return}console.log("smartReplaceType: ",N),console.log("smartReplaceText: ",J);break;case"start-of-line":v=p;break;case"end-of-line":v=d;break;case"new-line-above":v=p,await u.insertAtPos(`
`,v),v+=1;break;case"new-line-below":v=d,await u.insertAtPos(`
`,v),v+=1;break;case"start-of-item":v=f.from;break;case"end-of-item":v=f.to;break;case"cursor":default:v=await u.getCursor()}v===void 0&&(v=await se()),console.log("templatetext: ",o);let F=[],X={page:i,currentItemText:h,currentLineNumber:c,lineStartPos:p,lineEndPos:d,currentPageText:s,parentItemText:b,selectedText:w?.text,currentParagraph:A?.text,smartReplaceType:N,smartReplaceText:J};if(t.chat)F=await Xe(o),t.systemPrompt&&F.unshift({role:"system",content:t.systemPrompt}),t.chat&&t.enrichMessages&&(F=await pe(F,X));else{let E=await _r(o,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 op=new TextEncoder;function jr(e){let t=atob(e),r=t.length,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=t.charCodeAt(n);return o}var ee=class extends Error{constructor(r="(unknown reason)",o=""){super(`${r} ${o}`);this.mark=o;this.name=this.constructor.name}toString(r){return`${this.name}: ${this.message} ${this.mark}`}};function qr(e){return typeof e=="boolean"||e instanceof Boolean}function Hr(e){return e!==null&&typeof e=="object"}function K(e,t){let r="";for(let o=0;o<t;o++)r+=e;return r}function Ee(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Ze=class{constructor(t,r,o,n,i){this.name=t;this.buffer=r;this.position=o;this.line=n;this.column=i}getSnippet(t=4,r=75){if(!this.buffer)return null;let o="",n=this.position;for(;n>0&&`\0\r
\x85\u2028\u2029`.indexOf(this.buffer.charAt(n-1))===-1;)if(n-=1,this.position-n>r/2-1){o=" ... ",n+=5;break}let i="",s=this.position;for(;s<this.buffer.length&&`\0\r
\x85\u2028\u2029`.indexOf(this.buffer.charAt(s))===-1;)if(s+=1,s-this.position>r/2-1){i=" ... ",s-=5;break}let c=this.buffer.slice(n,s);return`${K(" ",t)}${o}${c}${i}
${K(" ",t+this.position-n+o.length)}^`}toString(t){let r,o="";return this.name&&(o+=`in "${this.name}" `),o+=`at line ${this.line+1}, column ${this.column+1}`,t||(r=this.getSnippet(),r&&(o+=`:
${r}`)),o}};function Rt(e,t,r){let o=[];for(let n of e.include)r=Rt(n,t,r);for(let n of e[t]){for(let[i,s]of r.entries())s.tag===n.tag&&s.kind===n.kind&&o.push(i);r.push(n)}return r.filter((n,i)=>!o.includes(i))}function ma(...e){let t={fallback:{},mapping:{},scalar:{},sequence:{}};for(let r of e)for(let o of r)o.kind!==null&&(t[o.kind][o.tag]=t.fallback[o.tag]=o);return t}var B=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=Rt(this,"implicit",[]),this.compiledExplicit=Rt(this,"explicit",[]),this.compiledTypeMap=ma(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 P=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||(o=>o),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 $t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
\r`;function da(e){if(e===null)return!1;let t,r=0,o=e.length,n=$t;for(let i=0;i<o;i++)if(t=n.indexOf(e.charAt(i)),!(t>64)){if(t<0)return!1;r+=6}return r%8===0}function fa(e){let t=e.replace(/[\r\n=]/g,""),r=t.length,o=$t,n=[],i=0;for(let c=0;c<r;c++)c%4===0&&c&&(n.push(i>>16&255),n.push(i>>8&255),n.push(i&255)),i=i<<6|o.indexOf(t.charAt(c));let s=r%4*6;return s===0?(n.push(i>>16&255),n.push(i>>8&255),n.push(i&255)):s===18?(n.push(i>>10&255),n.push(i>>2&255)):s===12&&n.push(i>>4&255),new Uint8Array(n)}function ga(e){let t=e.length,r=$t,o="",n=0;for(let s=0;s<t;s++)s%3===0&&s&&(o+=r[n>>18&63],o+=r[n>>12&63],o+=r[n>>6&63],o+=r[n&63]),n=(n<<8)+e[s];let i=t%3;return i===0?(o+=r[n>>18&63],o+=r[n>>12&63],o+=r[n>>6&63],o+=r[n&63]):i===2?(o+=r[n>>10&63],o+=r[n>>4&63],o+=r[n<<2&63],o+=r[64]):i===1&&(o+=r[n>>2&63],o+=r[n<<4&63],o+=r[64],o+=r[64]),o}function ha(e){return e instanceof Uint8Array}var Lt=new P("tag:yaml.org,2002:binary",{construct:fa,kind:"scalar",predicate:ha,represent:ga,resolve:da});function ya(e){let t=e.length;return t===4&&(e==="true"||e==="True"||e==="TRUE")||t===5&&(e==="false"||e==="False"||e==="FALSE")}function xa(e){return e==="true"||e==="True"||e==="TRUE"}var _t=new P("tag:yaml.org,2002:bool",{construct:xa,defaultStyle:"lowercase",kind:"scalar",predicate:qr,represent:{lowercase(e){return e?"true":"false"},uppercase(e){return e?"TRUE":"FALSE"},camelcase(e){return e?"True":"False"}},resolve:ya});var ba=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 wa(e){return!(!ba.test(e)||e[e.length-1]==="_")}function Pa(e){let t=e.replace(/_/g,"").toLowerCase(),r=t[0]==="-"?-1:1,o=[];if(t[0]&&"+-".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=>{o.unshift(parseFloat(s))});let n=0,i=1;return o.forEach(s=>{n+=s*i,i*=60}),r*n}return r*parseFloat(t)}var Aa=/^[-+]?[0-9]+e/;function Sa(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(Ee(e))return"-0.0";let r=e.toString(10);return Aa.test(r)?r.replace("e",".e"):r}function va(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||Ee(e))}var Dt=new P("tag:yaml.org,2002:float",{construct:Pa,defaultStyle:"lowercase",kind:"scalar",predicate:va,represent:Sa,resolve:wa});function Kr(e){let t=new Function(`return ${e}`)();if(!(t instanceof Function))throw new TypeError(`Expected function but got ${typeof t}: ${e}`);return t}var Ta=new P("tag:yaml.org,2002:js/function",{kind:"scalar",resolve(e){if(e===null)return!1;try{return Kr(`${e}`),!0}catch{return!1}},construct(e){return Kr(e)},predicate(e){return e instanceof Function},represent(e){return e.toString()}});function Ea(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function Ca(e){return 48<=e&&e<=55}function Ma(e){return 48<=e&&e<=57}function Ia(e){let t=e.length,r=0,o=!1;if(!t)return!1;let n=e[r];if((n==="-"||n==="+")&&(n=e[++r]),n==="0"){if(r+1===t)return!0;if(n=e[++r],n==="b"){for(r++;r<t;r++)if(n=e[r],n!=="_"){if(n!=="0"&&n!=="1")return!1;o=!0}return o&&n!=="_"}if(n==="x"){for(r++;r<t;r++)if(n=e[r],n!=="_"){if(!Ea(e.charCodeAt(r)))return!1;o=!0}return o&&n!=="_"}for(;r<t;r++)if(n=e[r],n!=="_"){if(!Ca(e.charCodeAt(r)))return!1;o=!0}return o&&n!=="_"}if(n==="_")return!1;for(;r<t;r++)if(n=e[r],n!=="_"){if(n===":")break;if(!Ma(e.charCodeAt(r)))return!1;o=!0}return!o||n==="_"?!1:n!==":"?!0:/^(:[0-5]?[0-9])+$/.test(e.slice(r))}function Oa(e){let t=e,r=[];t.indexOf("_")!==-1&&(t=t.replace(/_/g,""));let o=1,n=t[0];if((n==="-"||n==="+")&&(n==="-"&&(o=-1),t=t.slice(1),n=t[0]),t==="0")return 0;if(n==="0")return t[1]==="b"?o*parseInt(t.slice(2),2):t[1]==="x"?o*parseInt(t,16):o*parseInt(t,8);if(t.indexOf(":")!==-1){t.split(":").forEach(c=>{r.unshift(parseInt(c,10))});let i=0,s=1;return r.forEach(c=>{i+=c*s,s*=60}),o*i}return o*parseInt(t,10)}function Na(e){return Object.prototype.toString.call(e)==="[object Number]"&&e%1===0&&!Ee(e)}var Ut=new P("tag:yaml.org,2002:int",{construct:Oa,defaultStyle:"decimal",kind:"scalar",predicate:Na,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:Ia,styleAliases:{binary:[2,"bin"],decimal:[10,"dec"],hexadecimal:[16,"hex"],octal:[8,"oct"]}});var jt=new P("tag:yaml.org,2002:map",{construct(e){return e!==null?e:{}},kind:"mapping"});function ka(e){return e==="<<"||e===null}var qt=new P("tag:yaml.org,2002:merge",{kind:"scalar",resolve:ka});function Fa(e){let t=e.length;return t===1&&e==="~"||t===4&&(e==="null"||e==="Null"||e==="NULL")}function Ra(){return null}function $a(e){return e===null}var Ht=new P("tag:yaml.org,2002:null",{construct:Ra,defaultStyle:"lowercase",kind:"scalar",predicate:$a,represent:{canonical(){return"~"},lowercase(){return"null"},uppercase(){return"NULL"},camelcase(){return"Null"}},resolve:Fa});var{hasOwn:La}=Object,_a=Object.prototype.toString;function Da(e){let t=[],r="",o=!1;for(let n of e){if(o=!1,_a.call(n)!=="[object Object]")return!1;for(r in n)if(La(n,r))if(!o)o=!0;else return!1;if(!o)return!1;if(t.indexOf(r)===-1)t.push(r);else return!1}return!0}function Ua(e){return e!==null?e:[]}var Bt=new P("tag:yaml.org,2002:omap",{construct:Ua,kind:"sequence",resolve:Da});var ja=Object.prototype.toString;function qa(e){let t=Array.from({length:e.length});for(let[r,o]of e.entries()){if(ja.call(o)!=="[object Object]")return!1;let n=Object.keys(o);if(n.length!==1)return!1;t[r]=[n[0],o[n[0]]]}return!0}function Ha(e){if(e===null)return[];let t=Array.from({length:e.length});for(let r=0;r<e.length;r+=1){let o=e[r],n=Object.keys(o);t[r]=[n[0],o[n[0]]]}return t}var Kt=new P("tag:yaml.org,2002:pairs",{construct:Ha,kind:"sequence",resolve:qa});var Gt=/^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/,Yt=new P("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(!Gt.test(e))return!1;let r=[...t.match(Gt)?.groups?.modifiers??""];if(new Set(r).size<r.length)return!1}return!0},construct(e){let{regexp:t=`${e}`,modifiers:r=""}=`${e}`.match(Gt)?.groups??{};return new RegExp(t,r)},predicate(e){return e instanceof RegExp},represent(e){return e.toString()}});var Wt=new P("tag:yaml.org,2002:seq",{construct(e){return e!==null?e:[]},kind:"sequence"});var{hasOwn:Ba}=Object;function Ka(e){if(e===null)return!0;for(let t in e)if(Ba(e,t)&&e[t]!==null)return!1;return!0}function Ga(e){return e!==null?e:{}}var Qt=new P("tag:yaml.org,2002:set",{construct:Ga,kind:"mapping",resolve:Ka});var Vt=new P("tag:yaml.org,2002:str",{construct(e){return e!==null?e:""},kind:"scalar"});var Gr=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Yr=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function Ya(e){return e===null?!1:Gr.exec(e)!==null||Yr.exec(e)!==null}function Wa(e){let t=Gr.exec(e);if(t===null&&(t=Yr.exec(e)),t===null)throw new Error("Date resolve error");let r=+t[1],o=+t[2]-1,n=+t[3];if(!t[4])return new Date(Date.UTC(r,o,n));let i=+t[4],s=+t[5],c=+t[6],a=0;if(t[7]){let f=t[7].slice(0,3);for(;f.length<3;)f+="0";a=+f}let p=null;if(t[9]&&t[10]){let f=+t[10],h=+(t[11]||0);p=(f*60+h)*6e4,t[9]==="-"&&(p=-p)}let d=new Date(Date.UTC(r,o,n,i,s,c,a));return p&&d.setTime(d.getTime()-p),d}function Qa(e){return e.toISOString()}var zt=new P("tag:yaml.org,2002:timestamp",{construct:Wa,instanceOf:Date,kind:"scalar",represent:Qa,resolve:Ya});var Jt=new P("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve(){return!0},construct(){},predicate(e){return typeof e>"u"},represent(){return""}});var Xt=new B({explicit:[Vt,Wt,jt]});var Zt=new B({implicit:[Ht,_t,Ut,Dt],include:[Xt]});var er=new B({include:[Zt]});var Ce=new B({explicit:[Lt,Bt,Kt,Qt],implicit:[zt,qt],include:[er]});var Va=new B({explicit:[Yt,Jt],include:[Ce]});var Me=class{constructor(t=Ce){this.schema=t}};var et=class extends Me{constructor(r,{filename:o,schema:n,onWarning:i,legacy:s=!1,json:c=!1,listener:a=null}){super(n);this.input=r;this.filename=o,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,tt=1,Zr=2,en=3,rt=4,tr=1,za=2,Wr=3,Ja=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,Xa=/[\x85\u2028\u2029]/,Za=/[,\[\]\{\}]/,tn=/^(?:!|!!|![a-z\-]+!)$/i,rn=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Qr(e){return Object.prototype.toString.call(e)}function W(e){return e===10||e===13}function ce(e){return e===9||e===32}function j(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 ec(e){if(48<=e&&e<=57)return e-48;let t=e|32;return 97<=t&&t<=102?t-97+10:-1}function tc(e){return e===120?2:e===117?4:e===85?8:0}function rc(e){return 48<=e&&e<=57?e-48:-1}function Vr(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 nc(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}var nn=Array.from({length:256}),on=Array.from({length:256});for(let e=0;e<256;e++)nn[e]=Vr(e)?1:0,on[e]=Vr(e);function sn(e,t){return new ee(t,new Ze(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function y(e,t){throw sn(e,t)}function nt(e,t){e.onWarning&&e.onWarning.call(null,sn(e,t))}var zr={YAML(e,t,...r){if(e.version!==null)return y(e,"duplication of %YAML directive");if(r.length!==1)return y(e,"YAML directive accepts exactly one argument");let o=/^([0-9]+)\.([0-9]+)$/.exec(r[0]);if(o===null)return y(e,"ill-formed argument of the YAML directive");let n=parseInt(o[1],10),i=parseInt(o[2],10);if(n!==1)return y(e,"unacceptable YAML version of the document");if(e.version=r[0],e.checkLineBreaks=i<2,i!==1&&i!==2)return nt(e,"unsupported YAML version of the document")},TAG(e,t,...r){if(r.length!==2)return y(e,"TAG directive accepts exactly two arguments");let o=r[0],n=r[1];if(!tn.test(o))return y(e,"ill-formed tag handle (first argument) of the TAG directive");if(e.tagMap&&re(e.tagMap,o))return y(e,`there is a previously declared suffix for "${o}" tag handle`);if(!rn.test(n))return y(e,"ill-formed tag prefix (second argument) of the TAG directive");typeof e.tagMap>"u"&&(e.tagMap=Object.create(null)),e.tagMap[o]=n}};function te(e,t,r,o){let n;if(t<r){if(n=e.input.slice(t,r),o)for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(!(s===9||32<=s&&s<=1114111))return y(e,"expected valid JSON character")}else if(Ja.test(n))return y(e,"the stream contains non-printable characters");e.result+=n}}function Jr(e,t,r,o){if(!Hr(r))return y(e,"cannot merge mappings; the provided source object is unacceptable");for(let n in Object.keys(r))re(t,n)||(Object.defineProperty(t,n,{value:r[n],writable:!0,enumerable:!0,configurable:!0}),o[n]=!0)}function fe(e,t,r,o,n,i,s,c){if(Array.isArray(n)){n=Array.prototype.slice.call(n);for(let a=0;a<n.length;a++){if(Array.isArray(n[a]))return y(e,"nested arrays are not supported inside keys");typeof n=="object"&&Qr(n[a])==="[object Object]"&&(n[a]="[object Object]")}}if(typeof n=="object"&&Qr(n)==="[object Object]"&&(n="[object Object]"),n=String(n),t===null&&(t={}),o==="tag:yaml.org,2002:merge")if(Array.isArray(i))for(let a=0;a<i.length;a++)Jr(e,t,i[a],r);else Jr(e,t,i,r);else{if(!e.json&&!re(r,n)&&re(t,n))return e.line=s||e.line,e.position=c||e.position,y(e,"duplicated mapping key");Object.defineProperty(t,n,{value:i,writable:!0,enumerable:!0,configurable:!0}),delete r[n]}return t}function rr(e){let t=e.input.charCodeAt(e.position);if(t===10)e.position++;else if(t===13)e.position++,e.input.charCodeAt(e.position)===10&&e.position++;else return y(e,"a line break is expected");e.line+=1,e.lineStart=e.position}function I(e,t,r){let o=0,n=e.input.charCodeAt(e.position);for(;n!==0;){for(;ce(n);)n=e.input.charCodeAt(++e.position);if(t&&n===35)do n=e.input.charCodeAt(++e.position);while(n!==10&&n!==13&&n!==0);if(W(n))for(rr(e),n=e.input.charCodeAt(e.position),o++,e.lineIndent=0;n===32;)e.lineIndent++,n=e.input.charCodeAt(++e.position);else break}return r!==-1&&o!==0&&e.lineIndent<r&&nt(e,"deficient indentation"),o}function ot(e){let t=e.position,r=e.input.charCodeAt(t);return!!((r===45||r===46)&&r===e.input.charCodeAt(t+1)&&r===e.input.charCodeAt(t+2)&&(t+=3,r=e.input.charCodeAt(t),r===0||j(r)))}function nr(e,t){t===1?e.result+=" ":t>1&&(e.result+=K(`
`,t-1))}function oc(e,t,r){let o=e.kind,n=e.result,i=e.input.charCodeAt(e.position);if(j(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),j(s)||r&&de(s)))return!1;e.kind="scalar",e.result="";let c=e.position,a=e.position,p=!1,d=0;for(;i!==0;){if(i===58){if(s=e.input.charCodeAt(e.position+1),j(s)||r&&de(s))break}else if(i===35){let f=e.input.charCodeAt(e.position-1);if(j(f))break}else{if(e.position===e.lineStart&&ot(e)||r&&de(i))break;if(W(i)){d=e.line;let f=e.lineStart,h=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=d,e.lineStart=f,e.lineIndent=h;break}}}p&&(te(e,a,c,!1),nr(e,e.line-d),a=c=e.position,p=!1),ce(i)||(c=e.position+1),i=e.input.charCodeAt(++e.position)}return te(e,a,c,!1),e.result?!0:(e.kind=o,e.result=n,!1)}function ic(e,t){let r,o,n;if(r=e.input.charCodeAt(e.position),r!==39)return!1;for(e.kind="scalar",e.result="",e.position++,o=n=e.position;(r=e.input.charCodeAt(e.position))!==0;)if(r===39)if(te(e,o,e.position,!0),r=e.input.charCodeAt(++e.position),r===39)o=e.position,e.position++,n=e.position;else return!0;else if(W(r))te(e,o,n,!0),nr(e,I(e,!1,t)),o=n=e.position;else{if(e.position===e.lineStart&&ot(e))return y(e,"unexpected end of the document within a single quoted scalar");e.position++,n=e.position}return y(e,"unexpected end of the stream within a single quoted scalar")}function sc(e,t){let r=e.input.charCodeAt(e.position);if(r!==34)return!1;e.kind="scalar",e.result="",e.position++;let o=e.position,n=e.position,i;for(;(r=e.input.charCodeAt(e.position))!==0;){if(r===34)return te(e,n,e.position,!0),e.position++,!0;if(r===92){if(te(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),W(r))I(e,!1,t);else if(r<256&&nn[r])e.result+=on[r],e.position++;else if((i=tc(r))>0){let s=i,c=0;for(;s>0;s--)if(r=e.input.charCodeAt(++e.position),(i=ec(r))>=0)c=(c<<4)+i;else return y(e,"expected hexadecimal character");e.result+=nc(c),e.position++}else return y(e,"unknown escape sequence");n=o=e.position}else if(W(r))te(e,n,o,!0),nr(e,I(e,!1,t)),n=o=e.position;else{if(e.position===e.lineStart&&ot(e))return y(e,"unexpected end of the document within a double quoted scalar");e.position++,o=e.position}}return y(e,"unexpected end of the stream within a double quoted scalar")}function ac(e,t){let r=e.input.charCodeAt(e.position),o,n=!0,i={};if(r===91)o=93,n=!1,i=[];else if(r===123)o=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=null,d=null,f=null,h=!1,x=!1,b=0,A=0,w=Object.create(null);for(;r!==0;){if(I(e,!0,t),r=e.input.charCodeAt(e.position),r===o)return e.position++,e.tag=s,e.anchor=c,e.kind=n?"mapping":"sequence",e.result=i,!0;if(!a)return y(e,"missed comma between flow collection entries");f=d=p=null,x=h=!1,r===63&&(b=e.input.charCodeAt(e.position+1),j(b)&&(x=h=!0,e.position++,I(e,!0,t))),A=e.line,ge(e,t,tt,!1,!0),f=e.tag||null,d=e.result,I(e,!0,t),r=e.input.charCodeAt(e.position),(h||e.line===A)&&r===58&&(x=!0,r=e.input.charCodeAt(++e.position),I(e,!0,t),ge(e,t,tt,!1,!0),p=e.result),n?fe(e,i,w,f,d,p):x?i.push(fe(e,null,w,f,d,p)):i.push(d),I(e,!0,t),r=e.input.charCodeAt(e.position),r===44?(a=!0,r=e.input.charCodeAt(++e.position)):a=!1}return y(e,"unexpected end of the stream within a flow collection")}function cc(e,t){let r=tr,o=!1,n=!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 d=0;for(;a!==0;)if(a=e.input.charCodeAt(++e.position),a===43||a===45)if(tr===r)r=a===43?Wr:za;else return y(e,"repeat of a chomping mode identifier");else if((d=rc(a))>=0){if(d===0)return y(e,"bad explicit indentation width of a block scalar; it cannot be less than one");if(!n)i=t+d-1,n=!0;else return y(e,"repeat of an indentation width identifier")}else break;if(ce(a)){do a=e.input.charCodeAt(++e.position);while(ce(a));if(a===35)do a=e.input.charCodeAt(++e.position);while(!W(a)&&a!==0)}for(;a!==0;){for(rr(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!n||e.lineIndent<i)&&a===32;)e.lineIndent++,a=e.input.charCodeAt(++e.position);if(!n&&e.lineIndent>i&&(i=e.lineIndent),W(a)){s++;continue}if(e.lineIndent<i){r===Wr?e.result+=K(`
`,o?1+s:s):r===tr&&o&&(e.result+=`
`);break}p?ce(a)?(c=!0,e.result+=K(`
`,o?1+s:s)):c?(c=!1,e.result+=K(`
`,s+1)):s===0?o&&(e.result+=" "):e.result+=K(`
`,s):e.result+=K(`
`,o?1+s:s),o=!0,n=!0,s=0;let f=e.position;for(;!W(a)&&a!==0;)a=e.input.charCodeAt(++e.position);te(e,f,e.position,!1)}return!0}function Xr(e,t){let r,o,n=!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||(o=e.input.charCodeAt(e.position+1),!j(o)));){if(n=!0,e.position++,I(e,!0,-1)&&e.lineIndent<=t){a.push(null),i=e.input.charCodeAt(e.position);continue}if(r=e.line,ge(e,t,en,!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 y(e,"bad indentation of a sequence entry");if(e.lineIndent<t)break}return n?(e.tag=s,e.anchor=c,e.kind="sequence",e.result=a,!0):!1}function lc(e,t,r){let o=e.tag,n=e.anchor,i={},s=Object.create(null),c,a=!1,p,d,f=null,h=null,x=null,b=!1,A=!1,w;for(e.anchor!==null&&typeof e.anchor<"u"&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=i),w=e.input.charCodeAt(e.position);w!==0;){if(c=e.input.charCodeAt(e.position+1),p=e.line,d=e.position,(w===63||w===58)&&j(c)){if(w===63)b&&(fe(e,i,s,f,h,null),f=h=x=null),A=!0,b=!0,a=!0;else if(b)b=!1,a=!0;else return y(e,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");e.position+=1,w=c}else if(ge(e,r,Zr,!1,!0))if(e.line===p){for(w=e.input.charCodeAt(e.position);ce(w);)w=e.input.charCodeAt(++e.position);if(w===58){if(w=e.input.charCodeAt(++e.position),!j(w))return y(e,"a whitespace character is expected after the key-value separator within a block mapping");b&&(fe(e,i,s,f,h,null),f=h=x=null),A=!0,b=!1,a=!1,f=e.tag,h=e.result}else return A?y(e,"can not read an implicit mapping pair; a colon is missed"):(e.tag=o,e.anchor=n,!0)}else return A?y(e,"can not read a block mapping entry; a multiline key may not be an implicit key"):(e.tag=o,e.anchor=n,!0);else break;if((e.line===p||e.lineIndent>t)&&(ge(e,t,rt,!0,a)&&(b?h=e.result:x=e.result),b||(fe(e,i,s,f,h,x,p,d),f=h=x=null),I(e,!0,-1),w=e.input.charCodeAt(e.position)),e.lineIndent>t&&w!==0)return y(e,"bad indentation of a mapping entry");if(e.lineIndent<t)break}return b&&fe(e,i,s,f,h,null),A&&(e.tag=o,e.anchor=n,e.kind="mapping",e.result=i),A}function uc(e){let t,r=!1,o=!1,n="",i,s;if(s=e.input.charCodeAt(e.position),s!==33)return!1;if(e.tag!==null)return y(e,"duplication of a tag property");if(s=e.input.charCodeAt(++e.position),s===60?(r=!0,s=e.input.charCodeAt(++e.position)):s===33?(o=!0,n="!!",s=e.input.charCodeAt(++e.position)):n="!",t=e.position,r){do s=e.input.charCodeAt(++e.position);while(s!==0&&s!==62);if(e.position<e.length)i=e.input.slice(t,e.position),s=e.input.charCodeAt(++e.position);else return y(e,"unexpected end of the stream within a verbatim tag")}else{for(;s!==0&&!j(s);){if(s===33){if(o)return y(e,"tag suffix cannot contain exclamation marks");if(n=e.input.slice(t-1,e.position+1),!tn.test(n))return y(e,"named tag handle cannot contain such characters");o=!0,t=e.position+1}s=e.input.charCodeAt(++e.position)}if(i=e.input.slice(t,e.position),Za.test(i))return y(e,"tag suffix cannot contain flow indicator characters")}if(i&&!rn.test(i))return y(e,`tag name cannot contain such characters: ${i}`);if(r)e.tag=i;else if(typeof e.tagMap<"u"&&re(e.tagMap,n))e.tag=e.tagMap[n]+i;else if(n==="!")e.tag=`!${i}`;else if(n==="!!")e.tag=`tag:yaml.org,2002:${i}`;else return y(e,`undeclared tag handle "${n}"`);return!0}function pc(e){let t=e.input.charCodeAt(e.position);if(t!==38)return!1;if(e.anchor!==null)return y(e,"duplication of an anchor property");t=e.input.charCodeAt(++e.position);let r=e.position;for(;t!==0&&!j(t)&&!de(t);)t=e.input.charCodeAt(++e.position);return e.position===r?y(e,"name of an anchor node must contain at least one character"):(e.anchor=e.input.slice(r,e.position),!0)}function mc(e){let t=e.input.charCodeAt(e.position);if(t!==42)return!1;t=e.input.charCodeAt(++e.position);let r=e.position;for(;t!==0&&!j(t)&&!de(t);)t=e.input.charCodeAt(++e.position);if(e.position===r)return y(e,"name of an alias node must contain at least one character");let o=e.input.slice(r,e.position);return typeof e.anchorMap<"u"&&!re(e.anchorMap,o)?y(e,`unidentified alias "${o}"`):(typeof e.anchorMap<"u"&&(e.result=e.anchorMap[o]),I(e,!0,-1),!0)}function ge(e,t,r,o,n){let i,s,c=1,a=!1,p=!1,d,f,h;e.listener&&e.listener!==null&&e.listener("open",e),e.tag=null,e.anchor=null,e.kind=null,e.result=null;let x=i=s=rt===r||en===r;if(o&&I(e,!0,-1)&&(a=!0,e.lineIndent>t?c=1:e.lineIndent===t?c=0:e.lineIndent<t&&(c=-1)),c===1)for(;uc(e)||pc(e);)I(e,!0,-1)?(a=!0,s=x,e.lineIndent>t?c=1:e.lineIndent===t?c=0:e.lineIndent<t&&(c=-1)):s=!1;if(s&&(s=a||n),c===1||rt===r)if(f=tt===r||Zr===r?t:t+1,h=e.position-e.lineStart,c===1)if(s&&(Xr(e,h)||lc(e,h,f))||ac(e,f))p=!0;else{if(i&&cc(e,f)||ic(e,f)||sc(e,f))p=!0;else if(mc(e)){if(p=!0,e.tag!==null||e.anchor!==null)return y(e,"alias node should not have Any properties")}else oc(e,f,tt===r)&&(p=!0,e.tag===null&&(e.tag="?"));e.anchor!==null&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=e.result)}else c===0&&(p=s&&Xr(e,h));if(e.tag!==null&&e.tag!=="!")if(e.tag==="?"){for(let b=0;b<e.implicitTypes.length;b++)if(d=e.implicitTypes[b],d.resolve(e.result)){e.result=d.construct(e.result),e.tag=d.tag,e.anchor!==null&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=e.result);break}}else if(re(e.typeMap[e.kind||"fallback"],e.tag)){if(d=e.typeMap[e.kind||"fallback"][e.tag],e.result!==null&&d.kind!==e.kind)return y(e,`unacceptable node kind for !<${e.tag}> tag; it should be "${d.kind}", not "${e.kind}"`);if(d.resolve(e.result))e.result=d.construct(e.result),e.anchor!==null&&typeof e.anchorMap<"u"&&(e.anchorMap[e.anchor]=e.result);else return y(e,`cannot resolve a node with !<${e.tag}> explicit tag`)}else return y(e,`unknown tag !<${e.tag}>`);return e.listener&&e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||p}function dc(e){let t=e.position,r,o,n,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&&!j(s);)s=e.input.charCodeAt(++e.position);if(o=e.input.slice(r,e.position),n=[],o.length<1)return y(e,"directive name must not be less than one character in length");for(;s!==0;){for(;ce(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&&!j(s);)s=e.input.charCodeAt(++e.position);n.push(e.input.slice(r,e.position))}s!==0&&rr(e),re(zr,o)?zr[o](e,o,...n):nt(e,`unknown document directive "${o}"`)}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 y(e,"directives end mark is expected");if(ge(e,e.lineIndent-1,rt,!1,!0),I(e,!0,-1),e.checkLineBreaks&&Xa.test(e.input.slice(t,e.position))&&nt(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&ot(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,I(e,!0,-1));return}if(e.position<e.length-1)return y(e,"end of the stream or a document separator is expected")}function fc(e,t){e=String(e),t=t||{},e.length!==0&&(e.charCodeAt(e.length-1)!==10&&e.charCodeAt(e.length-1)!==13&&(e+=`
`),e.charCodeAt(0)===65279&&(e=e.slice(1)));let r=new et(e,t);for(r.input+="\0";r.input.charCodeAt(r.position)===32;)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)dc(r);return r.documents}function an(e,t){let r=fc(e,t);if(r.length===0)return null;if(r.length===1)return r[0];throw new ee("expected a single document in the stream, but found more")}function cn(e,t){return an(e,t)}var{hasOwn:Vm}=Object;var{hasOwn:ed}=Object;var L={};L[0]="\\0";L[7]="\\a";L[8]="\\b";L[9]="\\t";L[10]="\\n";L[11]="\\v";L[12]="\\f";L[13]="\\r";L[27]="\\e";L[34]='\\"';L[92]="\\\\";L[133]="\\N";L[160]="\\_";L[8232]="\\L";L[8233]="\\P";async function ln(e){(e==="SETTINGS"||e==="SECRETS")&&await z(!0)}async function un(){await z(!0)}async function pn(){(!g||!g.textModels)&&await z(!1);let e=g.textModels.map(o=>({...o,name:o.name,description:o.description||`${o.modelName} on ${o.provider}`})),t=await u.filterBox("Select a model",e);if(!t){await u.flashNotification("No model selected.","error");return}let r=t.name;await St(t),await ae(t),await u.flashNotification(`Selected model: ${r}`),console.log("Selected model:",t)}async function mn(){(!g||!g.imageModels)&&await z(!1);let e=g.imageModels.map(o=>({...o,name:o.name,description:o.description||`${o.modelName} on ${o.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 At(t),await Tt(t),await u.flashNotification(`Selected image model: ${r}`),console.log("Selected image model:",t)}async function dn(){(!g||!g.embeddingModels)&&await z(!1);let e=g.embeddingModels.map(o=>({...o,name:o.name,description:o.description||`${o.modelName} on ${o.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 vt(t),await Ae(t),await u.flashNotification(`Selected embedding model: ${r}`),console.log("Selected embedding model:",t)}async function fn(){await T();let e=await Ue(),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(),o=new Date,n=o.toISOString().split("T")[0],i=o.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}, ${n}. The current note name is "${r}".
User Prompt: ${t}
Note Content:
${e.text}`}],stream:!0},e.to)}async function gn(){await T();let e=await Ue();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 hn(){let{summary:e,selectedTextInfo:t}=await gn();e&&t&&await u.insertAtPos(`
`+e,t.to)}async function yn(){let{summary:e}=await gn();e?await u.showPanel("rhs",2,e):await u.flashNotification("No summary available.")}async function or(){await T();let e=await u.getText(),t=await u.getCurrentPage(),r=(await Te("tag select name where parent = 'page' order by name")).map(f=>f.name);console.log("All tags:",r);let o=`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.
- Suggest tags sparingly, treating them as thematic descriptors rather than keywords.
The following tags are currently being used by other notes:
${r.join(", ")}
Always follow the below rules, if any, given by the user:
${g.promptInstructions.tagRules}`,n=`Page Title: ${t}
Page Content:
${e}`,s=(await O.singleMessageChat(n,o)).trim().replace(/,/g,"").split(/\s+/),c=await k.parseMarkdown(e),a=await V(c),p=[...new Set([...a.tags||[],...s])];a.tags=p,console.log("Current frontmatter:",a);let d=await dt(c,a);console.log("updatedNoteContent",d),await u.dispatch(d),await u.flashNotification("Note tagged successfully.")}async function ir(){await T();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 n="";g.promptInstructions.pageRenameSystem?n=g.promptInstructions.pageRenameSystem:n=`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.
- Avoid suggesting the same name as the current note.
- Include as much detail as possible within 3 to 10 words.
- Start names with ASCII characters only.
- Do not use markdown or any other formatting in your response.`;let s=(await O.singleMessageChat(`Current Page Title: ${t}
Page Content:
${e}`,`${n}
Always follow the below rules, if any, given by the user:
${g.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 sr(){await T();let e=await u.getText(),t=await u.getCurrentPage(),r=["title","tags"],n=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:
- Only return valid YAML frontmatter.
- Do not use any markdown or any other formatting in your response.
- Do not include --- in your response.
- Do not include any content from the note in your response.
- Extract useful facts from the note and add them to the frontmatter, such as a person's name, age, a location, etc.
- Do not return any tags.
- Do not return a new note title.
- Do not use special characters in key names. Only ASCII.
- Only return important information that would be useful when searching or filtering notes.
Always follow the below rules, if any, given by the user:
${g.promptInstructions.enhanceFrontMatterPrompt}`,!0);console.log("frontmatter returned by enhanceNoteFrontMatter",n);try{let i=cn(n);if(typeof i!="object"||Array.isArray(i)||!i)throw new Error("Invalid YAML: Not an object");r.forEach(d=>{delete i[d]});let s=await k.parseMarkdown(e),a={...await V(s),...i},p=await dt(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 xn(){await or(),await sr(),await ir()}async function bn(){let e=await Ue(),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 wn(){await T();let e=await Xe();if(e.length===0){await u.flashNotification("Error: The page does not match the required format for a chat.");return}e.unshift(we);let t=await pe(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(o){console.error("Error streaming chat on page:",o),await u.flashNotification("Error streaming chat on page.","error")}}async function Pn(){if(await T(),!g.imageModels||g.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 Qe.generateImage(t);if(r&&r.data&&r.data.length>0){let o=r.data[0].b64_json,n=r.data[0].revised_prompt,i=new Uint8Array(jr(o)),s=`dall-e-${Date.now()}.png`,c=$r(await u.getCurrentPage())+"/";c==="/"&&(c=""),await D.writeAttachment(c+s,i);let a=`![${s}](${s})
*${n}*`;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 An(e,t){try{return await T(),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 Sn(){await T();let e=await u.prompt("Enter some text to embed:");if(!e){await u.flashNotification("No text entered.","error");return}let t=await $.generateEmbeddings({text:e});await u.insertAtCursor(`
Embedding: ${t}`)}var vn="\u{1F6F0}\uFE0F AI Connectivity Test";function Tn(e){return{data:new TextEncoder().encode(""),meta:{name:e,contentType:"text/markdown",size:0,created:0,lastModified:0,perm:"ro"}}}function ar(e){return{name:e,contentType:"text/markdown",size:-1,created:0,lastModified:0,perm:"ro"}}function En(e){return ar(e)}async function Cn(){if(await u.getCurrentPage()===vn){await T();let t=`# \u{1F6F0}\uFE0F AI Connectivity Test
## Status Overview
`,r=await Ve(),o=await wt(),n=await Pt();if(!r&&!o&&!n)t+=`> \u26A0\uFE0F **No models currently selected**
## Available Models
`,g.textModels.length>0?(t+=`### \u{1F4AC} Text Models
`,g.textModels.forEach(i=>t+=`* ${i.name}
`),t+=`
`):t+=`### \u{1F4AC} Text Models
_No text models configured._
`,g.imageModels.length>0?(t+=`### \u{1F3A8} Image Models
`,g.imageModels.forEach(i=>t+=`* ${i.name}
`),t+=`
`):t+=`### \u{1F3A8} Image Models
_No image models configured._
`,g.embeddingModels.length>0?(t+=`### \u{1F524} Embedding Models
`,g.embeddingModels.forEach(i=>t+=`* ${i.name}
`),t+=`
`):t+=`### \u{1F524} Embedding Models
_No embedding models configured._
`,t+=`## Quick Setup
Use these commands to select your models:
* \`AI: Select Text Model from Config\`
* \`AI: Select Image Model from Config\`
* \`AI: Select Embedding Model from Config\`
`;else{let i=(s,c,a)=>{t+=`## ${a} ${c} Configuration
### Model Details
| Setting | Value |
|---------|-------|
| Name | ${s.name} |
| Description | ${s.description||"_No description provided_"} |
| Provider | ${s.provider} |
| Model Name | \`${s.modelName}\` |
| Authentication | ${s.requireAuth?"Required":"Not Required"} |
| Secret Name | ${s.secretName?`\`${s.secretName}\``:"_Not provided_"} |${s.baseUrl?`
| API Endpoint | \`${s.baseUrl}\` |`:""}
`};if(r){i(r,"Text Model","\u{1F4AC}"),t+=`
> \u{1F504} Starting connectivity tests...
`,await u.setText(t),t+=`### \u{1F50C} Provider Setup
`;try{let s=await ae(r);t+=`> \u2705 Provider successfully configured
`,t+=`### \u{1F4CB} Model Availability
`;try{let c=await s.listModels();c.includes(r.modelName)?t+=`> \u2705 Selected model is available
`:(t+=`> \u26A0\uFE0F Selected model not found in available models
`,t+=`#### Available Models
`,c.forEach(a=>t+=`* \`${a}\`
`),t+=`
`)}catch(c){t+=`> \u274C Failed to fetch available models: ${c}
`}t+=`### \u{1F50C} API Connectivity
`;try{t+=`#### \u{1F4E1} Non-Streaming Test
`;let c=await s.singleMessageChat("This is a connectivity test. Respond with exactly 'CONNECTED' (no quotes, no other text).");c&&c.trim()==="CONNECTED"?t+=`> \u2705 Successfully connected to API and received expected response
`:(t+=`> \u26A0\uFE0F Connected to API but received unexpected response
`,t+="```diff\n",t+=`- Expected: CONNECTED
`,t+=`+ Received: ${c}
`,t+="```\n\n",t+=`_Note: The API is accessible but may not be following instructions precisely._
`),t+=`#### \u{1F4E1} Streaming Test
`;try{let a=[],p=await new Promise((d,f)=>{let h="";s.chatWithAI({messages:[{role:"user",content:"This is a streaming connectivity test. Respond with exactly 'CONNECTED' (no quotes, no other text)."}],stream:!0,onDataReceived:x=>{console.log("Streaming chunk received:",x),a.push(x),h+=x},onResponseComplete:x=>{d(x)}}).catch(f)});p.trim()==="CONNECTED"?t+=`> \u2705 Successfully connected to streaming API and received expected response
`:(t+=`> \u26A0\uFE0F Connected to streaming API but received unexpected response
`,t+="```diff\n",t+=`- Expected: CONNECTED
`,t+=`+ Received: ${p}
`,t+="```\n\n",t+=`_Note: The streaming API is accessible but may not be following instructions precisely._
`),t+="Received chunks: \n```\n",a.forEach((d,f)=>{t+=`Chunk ${f+1}: "${d}"
`}),t+="```\n\n\n"}catch(a){t+=`> \u274C Failed to connect to streaming API: ${a}
`,t+=`**Troubleshooting Tips:**
`,t+=`* Verify your provider supports streaming
`,t+=`* Ensure there isn't a proxy affecting streaming
`}}catch(c){t+=`> \u274C Failed to connect to API: ${c}
`,t+=`**Troubleshooting Tips:**
`,t+=`* Check your API key if needed
`,t+=`* Ensure the API endpoint is accessible
`,t+=`* Check if you have exceeded API rate limits
`,t+=`* Verify you are not using https on silverbullet and connecting to regular http for the api endpoint
`}}catch(s){t+=`> **error** \u26A0\uFE0F Failed to configure provider: ${s}
`}}if(o&&(i(o,"Image Model","\u{1F3A8}"),t+=`> \u2139\uFE0F Image generation testing is disabled to avoid unnecessary API usage
`),n){i(n,"Embedding Model","\u{1F524}"),t+=`### \u{1F50C} Embedding Provider Setup
`;try{await Ae(n),t+=`> \u2705 Embedding provider successfully configured
`,t+=`### \u{1F9EE} Embedding Generation
`;try{let c=await $.generateEmbeddings({text:"This is a connectivity test."});c&&c.length>0?(t+=`> \u2705 Successfully generated embeddings
`,t+=`\`\`\`
Generated ${c.length}-dimensional embedding vector
\`\`\`
`):t+=`> \u26A0\uFE0F Connected to API but received empty embeddings
`}catch(s){t+=`> \u274C Failed to generate embeddings: ${s}
`}}catch(s){t+=`> \u274C Failed to configure embedding provider: ${s}
`}}}await u.setText(t)}}async function Mn(){await T(),await u.navigate({page:vn})}var In={aiPromptSlashCommplete:Dr,queryAI:An,reloadSettingsPageEvent:ln,reloadConfigEvent:un,summarizeNote:yn,insertSummary:hn,callOpenAI:fn,tagNoteWithAI:or,promptAndGenerateImage:Pn,streamOpenAIWithSelectionAsPrompt:bn,streamChatOnPage:wn,insertAiPromptFromTemplate:Ur,suggestPageName:ir,enhanceNoteFrontMatter:sr,enhanceNoteWithAI:xn,selectTextModel:pn,selectImageModel:mn,selectEmbeddingModel:dn,testEmbeddingGeneration:Sn,getAllEmbeddings:Mt,searchEmbeddings:It,queueEmbeddingGeneration:Tr,processEmbeddingsQueue:Er,processSummaryQueue:Cr,generateEmbeddings:Ir,generateEmbeddingsOnServer:ve,searchEmbeddingsForChat:Je,searchCombinedEmbeddings:ze,searchSummaryEmbeddings:Or,readPageSearchEmbeddings:Nr,writePageSearchEmbeddings:kr,getPageMetaSearchEmbeddings:Ot,searchCommand:Rr,updateSearchPage:Fr,readPageConnectivityTest:Tn,writePageConnectivityTest:En,getPageMetaConnectivityTest:ar,connectivityTestCommand:Mn,updateConnectivityTestPage:Cn},On={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"]},readPageConnectivityTest:{path:"src/connectivity.ts:readFileConnectivityTest",pageNamespace:{pattern:"\u{1F6F0}\uFE0F AI Connectivity Test",operation:"readFile"}},writePageConnectivityTest:{path:"src/connectivity.ts:writeFileConnectivityTest",pageNamespace:{pattern:"\u{1F6F0}\uFE0F AI Connectivity Test",operation:"writeFile"}},getPageMetaConnectivityTest:{path:"src/connectivity.ts:getFileMetaConnectivityTest",pageNamespace:{pattern:"\u{1F6F0}\uFE0F AI Connectivity Test",operation:"getFileMeta"}},connectivityTestCommand:{path:"src/connectivity.ts:connectivityTestCommand",command:{name:"AI: Connectivity Test"}},updateConnectivityTestPage:{path:"src/connectivity.ts:updateConnectivityTestPage",events:["editor:pageLoaded","editor:pageReloaded"]}},assets:{}},cf={manifest:On,functionMapping:In};cr(In,On,self.postMessage);export{cf as plug};