-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
238 lines (193 loc) · 142 KB
/
main.js
File metadata and controls
238 lines (193 loc) · 142 KB
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
var je=Object.defineProperty;var Un=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var Gn=Object.prototype.hasOwnProperty;var N=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),jn=(n,t)=>{for(var e in t)je(n,e,{get:t[e],enumerable:!0})},Vn=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qn(t))!Gn.call(n,s)&&s!==e&&je(n,s,{get:()=>t[s],enumerable:!(i=Un(t,s))||i.enumerable});return n};var Kn=n=>Vn(je({},"__esModule",{value:!0}),n);var Ft=N((Ir,Ke)=>{function Ht(n,t){if(t&&t.documentElement)n=t,t=arguments[2];else if(!n||!n.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(t=t||{},this._doc=n,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._debug=!!t.debug,this._maxElemsToParse=t.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=t.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=t.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(t.classesToPreserve||[]),this._keepClasses=!!t.keepClasses,this._serializer=t.serializer||function(e){return e.innerHTML},this._disableJSONLD=!!t.disableJSONLD,this._allowedVideoRegex=t.allowedVideoRegex||this.REGEXPS.videos,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let e=function(i){if(i.nodeType==i.TEXT_NODE)return`${i.nodeName} ("${i.textContent}")`;let s=Array.from(i.attributes||[],function(r){return`${r.name}="${r.value}"`}).join(" ");return`<${i.localName} ${s}>`};this.log=function(){if(typeof console!="undefined"){let s=Array.from(arguments,r=>r&&r.nodeType==this.ELEMENT_NODE?e(r):r);s.unshift("Reader: (Readability)"),console.log.apply(console,s)}else if(typeof dump!="undefined"){var i=Array.prototype.map.call(arguments,function(s){return s&&s.nodeName?e(s):s}).join(" ");dump("Reader: (Readability) "+i+`
`)}}}else this.log=function(){}}Ht.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent:function(n){this._fixRelativeUris(n),this._simplifyNestedElements(n),this._keepClasses||this._cleanClasses(n)},_removeNodes:function(n,t){if(this._docJSDOMParser&&n._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var e=n.length-1;e>=0;e--){var i=n[e],s=i.parentNode;s&&(!t||t.call(this,i,e,n))&&s.removeChild(i)}},_replaceNodeTags:function(n,t){if(this._docJSDOMParser&&n._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(let e of n)this._setNodeTag(e,t)},_forEachNode:function(n,t){Array.prototype.forEach.call(n,t,this)},_findNode:function(n,t){return Array.prototype.find.call(n,t,this)},_someNode:function(n,t){return Array.prototype.some.call(n,t,this)},_everyNode:function(n,t){return Array.prototype.every.call(n,t,this)},_concatNodeLists:function(){var n=Array.prototype.slice,t=n.call(arguments),e=t.map(function(i){return n.call(i)});return Array.prototype.concat.apply([],e)},_getAllNodesWithTag:function(n,t){return n.querySelectorAll?n.querySelectorAll(t.join(",")):[].concat.apply([],t.map(function(e){var i=n.getElementsByTagName(e);return Array.isArray(i)?i:Array.from(i)}))},_cleanClasses:function(n){var t=this._classesToPreserve,e=(n.getAttribute("class")||"").split(/\s+/).filter(function(i){return t.indexOf(i)!=-1}).join(" ");for(e?n.setAttribute("class",e):n.removeAttribute("class"),n=n.firstElementChild;n;n=n.nextElementSibling)this._cleanClasses(n)},_fixRelativeUris:function(n){var t=this._doc.baseURI,e=this._doc.documentURI;function i(a){if(t==e&&a.charAt(0)=="#")return a;try{return new URL(a,t).href}catch(o){}return a}var s=this._getAllNodesWithTag(n,["a"]);this._forEachNode(s,function(a){var o=a.getAttribute("href");if(o)if(o.indexOf("javascript:")===0)if(a.childNodes.length===1&&a.childNodes[0].nodeType===this.TEXT_NODE){var l=this._doc.createTextNode(a.textContent);a.parentNode.replaceChild(l,a)}else{for(var c=this._doc.createElement("span");a.firstChild;)c.appendChild(a.firstChild);a.parentNode.replaceChild(c,a)}else a.setAttribute("href",i(o))});var r=this._getAllNodesWithTag(n,["img","picture","figure","video","audio","source"]);this._forEachNode(r,function(a){var o=a.getAttribute("src"),l=a.getAttribute("poster"),c=a.getAttribute("srcset");if(o&&a.setAttribute("src",i(o)),l&&a.setAttribute("poster",i(l)),c){var u=c.replace(this.REGEXPS.srcsetUrl,function(d,h,p,g){return i(h)+(p||"")+g});a.setAttribute("srcset",u)}})},_simplifyNestedElements:function(n){for(var t=n;t;){if(t.parentNode&&["DIV","SECTION"].includes(t.tagName)&&!(t.id&&t.id.startsWith("readability"))){if(this._isElementWithoutContent(t)){t=this._removeAndGetNext(t);continue}else if(this._hasSingleTagInsideElement(t,"DIV")||this._hasSingleTagInsideElement(t,"SECTION")){for(var e=t.children[0],i=0;i<t.attributes.length;i++)e.setAttribute(t.attributes[i].name,t.attributes[i].value);t.parentNode.replaceChild(e,t),t=e;continue}}t=this._getNextNode(t)}},_getArticleTitle:function(){var n=this._doc,t="",e="";try{t=e=n.title.trim(),typeof t!="string"&&(t=e=this._getInnerText(n.getElementsByTagName("title")[0]))}catch(u){}var i=!1;function s(u){return u.split(/\s+/).length}if(/ [\|\-\\\/>»] /.test(t))i=/ [\\\/>»] /.test(t),t=e.replace(/(.*)[\|\-\\\/>»] .*/gi,"$1"),s(t)<3&&(t=e.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi,"$1"));else if(t.indexOf(": ")!==-1){var r=this._concatNodeLists(n.getElementsByTagName("h1"),n.getElementsByTagName("h2")),a=t.trim(),o=this._someNode(r,function(u){return u.textContent.trim()===a});o||(t=e.substring(e.lastIndexOf(":")+1),s(t)<3?t=e.substring(e.indexOf(":")+1):s(e.substr(0,e.indexOf(":")))>5&&(t=e))}else if(t.length>150||t.length<15){var l=n.getElementsByTagName("h1");l.length===1&&(t=this._getInnerText(l[0]))}t=t.trim().replace(this.REGEXPS.normalize," ");var c=s(t);return c<=4&&(!i||c!=s(e.replace(/[\|\-\\\/>»]+/g,""))-1)&&(t=e),t},_prepDocument:function(){var n=this._doc;this._removeNodes(this._getAllNodesWithTag(n,["style"])),n.body&&this._replaceBrs(n.body),this._replaceNodeTags(this._getAllNodesWithTag(n,["font"]),"SPAN")},_nextNode:function(n){for(var t=n;t&&t.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(t.textContent);)t=t.nextSibling;return t},_replaceBrs:function(n){this._forEachNode(this._getAllNodesWithTag(n,["br"]),function(t){for(var e=t.nextSibling,i=!1;(e=this._nextNode(e))&&e.tagName=="BR";){i=!0;var s=e.nextSibling;e.parentNode.removeChild(e),e=s}if(i){var r=this._doc.createElement("p");for(t.parentNode.replaceChild(r,t),e=r.nextSibling;e;){if(e.tagName=="BR"){var a=this._nextNode(e.nextSibling);if(a&&a.tagName=="BR")break}if(!this._isPhrasingContent(e))break;var o=e.nextSibling;r.appendChild(e),e=o}for(;r.lastChild&&this._isWhitespace(r.lastChild);)r.removeChild(r.lastChild);r.parentNode.tagName==="P"&&this._setNodeTag(r.parentNode,"DIV")}})},_setNodeTag:function(n,t){if(this.log("_setNodeTag",n,t),this._docJSDOMParser)return n.localName=t.toLowerCase(),n.tagName=t.toUpperCase(),n;for(var e=n.ownerDocument.createElement(t);n.firstChild;)e.appendChild(n.firstChild);n.parentNode.replaceChild(e,n),n.readability&&(e.readability=n.readability);for(var i=0;i<n.attributes.length;i++)try{e.setAttribute(n.attributes[i].name,n.attributes[i].value)}catch(s){}return e},_prepArticle:function(n){this._cleanStyles(n),this._markDataTables(n),this._fixLazyImages(n),this._cleanConditionally(n,"form"),this._cleanConditionally(n,"fieldset"),this._clean(n,"object"),this._clean(n,"embed"),this._clean(n,"footer"),this._clean(n,"link"),this._clean(n,"aside");var t=this.DEFAULT_CHAR_THRESHOLD;this._forEachNode(n.children,function(e){this._cleanMatchedNodes(e,function(i,s){return this.REGEXPS.shareElements.test(s)&&i.textContent.length<t})}),this._clean(n,"iframe"),this._clean(n,"input"),this._clean(n,"textarea"),this._clean(n,"select"),this._clean(n,"button"),this._cleanHeaders(n),this._cleanConditionally(n,"table"),this._cleanConditionally(n,"ul"),this._cleanConditionally(n,"div"),this._replaceNodeTags(this._getAllNodesWithTag(n,["h1"]),"h2"),this._removeNodes(this._getAllNodesWithTag(n,["p"]),function(e){var i=e.getElementsByTagName("img").length,s=e.getElementsByTagName("embed").length,r=e.getElementsByTagName("object").length,a=e.getElementsByTagName("iframe").length,o=i+s+r+a;return o===0&&!this._getInnerText(e,!1)}),this._forEachNode(this._getAllNodesWithTag(n,["br"]),function(e){var i=this._nextNode(e.nextSibling);i&&i.tagName=="P"&&e.parentNode.removeChild(e)}),this._forEachNode(this._getAllNodesWithTag(n,["table"]),function(e){var i=this._hasSingleTagInsideElement(e,"TBODY")?e.firstElementChild:e;if(this._hasSingleTagInsideElement(i,"TR")){var s=i.firstElementChild;if(this._hasSingleTagInsideElement(s,"TD")){var r=s.firstElementChild;r=this._setNodeTag(r,this._everyNode(r.childNodes,this._isPhrasingContent)?"P":"DIV"),e.parentNode.replaceChild(r,e)}}})},_initializeNode:function(n){switch(n.readability={contentScore:0},n.tagName){case"DIV":n.readability.contentScore+=5;break;case"PRE":case"TD":case"BLOCKQUOTE":n.readability.contentScore+=3;break;case"ADDRESS":case"OL":case"UL":case"DL":case"DD":case"DT":case"LI":case"FORM":n.readability.contentScore-=3;break;case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":case"TH":n.readability.contentScore-=5;break}n.readability.contentScore+=this._getClassWeight(n)},_removeAndGetNext:function(n){var t=this._getNextNode(n,!0);return n.parentNode.removeChild(n),t},_getNextNode:function(n,t){if(!t&&n.firstElementChild)return n.firstElementChild;if(n.nextElementSibling)return n.nextElementSibling;do n=n.parentNode;while(n&&!n.nextElementSibling);return n&&n.nextElementSibling},_textSimilarity:function(n,t){var e=n.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean),i=t.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean);if(!e.length||!i.length)return 0;var s=i.filter(a=>!e.includes(a)),r=s.join(" ").length/i.join(" ").length;return 1-r},_checkByline:function(n,t){if(this._articleByline)return!1;if(n.getAttribute!==void 0)var e=n.getAttribute("rel"),i=n.getAttribute("itemprop");return(e==="author"||i&&i.indexOf("author")!==-1||this.REGEXPS.byline.test(t))&&this._isValidByline(n.textContent)?(this._articleByline=n.textContent.trim(),!0):!1},_getNodeAncestors:function(n,t){t=t||0;for(var e=0,i=[];n.parentNode&&(i.push(n.parentNode),!(t&&++e===t));)n=n.parentNode;return i},_grabArticle:function(n){this.log("**** grabArticle ****");var t=this._doc,e=n!==null;if(n=n||this._doc.body,!n)return this.log("No body found in document. Abort."),null;for(var i=n.innerHTML;;){this.log("Starting grabArticle loop");var s=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),r=[],a=this._doc.documentElement;let Tt=!0;for(;a;){a.tagName==="HTML"&&(this._articleLang=a.getAttribute("lang"));var o=a.className+" "+a.id;if(!this._isProbablyVisible(a)){this.log("Removing hidden node - "+o),a=this._removeAndGetNext(a);continue}if(a.getAttribute("aria-modal")=="true"&&a.getAttribute("role")=="dialog"){a=this._removeAndGetNext(a);continue}if(this._checkByline(a,o)){a=this._removeAndGetNext(a);continue}if(Tt&&this._headerDuplicatesTitle(a)){this.log("Removing header: ",a.textContent.trim(),this._articleTitle.trim()),Tt=!1,a=this._removeAndGetNext(a);continue}if(s){if(this.REGEXPS.unlikelyCandidates.test(o)&&!this.REGEXPS.okMaybeItsACandidate.test(o)&&!this._hasAncestorTag(a,"table")&&!this._hasAncestorTag(a,"code")&&a.tagName!=="BODY"&&a.tagName!=="A"){this.log("Removing unlikely candidate - "+o),a=this._removeAndGetNext(a);continue}if(this.UNLIKELY_ROLES.includes(a.getAttribute("role"))){this.log("Removing content with role "+a.getAttribute("role")+" - "+o),a=this._removeAndGetNext(a);continue}}if((a.tagName==="DIV"||a.tagName==="SECTION"||a.tagName==="HEADER"||a.tagName==="H1"||a.tagName==="H2"||a.tagName==="H3"||a.tagName==="H4"||a.tagName==="H5"||a.tagName==="H6")&&this._isElementWithoutContent(a)){a=this._removeAndGetNext(a);continue}if(this.DEFAULT_TAGS_TO_SCORE.indexOf(a.tagName)!==-1&&r.push(a),a.tagName==="DIV"){for(var l=null,c=a.firstChild;c;){var u=c.nextSibling;if(this._isPhrasingContent(c))l!==null?l.appendChild(c):this._isWhitespace(c)||(l=t.createElement("p"),a.replaceChild(l,c),l.appendChild(c));else if(l!==null){for(;l.lastChild&&this._isWhitespace(l.lastChild);)l.removeChild(l.lastChild);l=null}c=u}if(this._hasSingleTagInsideElement(a,"P")&&this._getLinkDensity(a)<.25){var d=a.children[0];a.parentNode.replaceChild(d,a),a=d,r.push(a)}else this._hasChildBlockElement(a)||(a=this._setNodeTag(a,"P"),r.push(a))}a=this._getNextNode(a)}var h=[];this._forEachNode(r,function(D){if(!(!D.parentNode||typeof D.parentNode.tagName=="undefined")){var B=this._getInnerText(D);if(!(B.length<25)){var At=this._getNodeAncestors(D,5);if(At.length!==0){var ge=0;ge+=1,ge+=B.split(this.REGEXPS.commas).length,ge+=Math.min(Math.floor(B.length/100),3),this._forEachNode(At,function(q,qe){if(!(!q.tagName||!q.parentNode||typeof q.parentNode.tagName=="undefined")){if(typeof q.readability=="undefined"&&(this._initializeNode(q),h.push(q)),qe===0)var Ge=1;else qe===1?Ge=2:Ge=qe*3;q.readability.contentScore+=ge/Ge}})}}}});for(var p=[],g=0,y=h.length;g<y;g+=1){var v=h[g],w=v.readability.contentScore*(1-this._getLinkDensity(v));v.readability.contentScore=w,this.log("Candidate:",v,"with score "+w);for(var E=0;E<this._nbTopCandidates;E++){var A=p[E];if(!A||w>A.readability.contentScore){p.splice(E,0,v),p.length>this._nbTopCandidates&&p.pop();break}}}var m=p[0]||null,_=!1,f;if(m===null||m.tagName==="BODY"){for(m=t.createElement("DIV"),_=!0;n.firstChild;)this.log("Moving child out:",n.firstChild),m.appendChild(n.firstChild);n.appendChild(m),this._initializeNode(m)}else if(m){for(var b=[],x=1;x<p.length;x++)p[x].readability.contentScore/m.readability.contentScore>=.75&&b.push(this._getNodeAncestors(p[x]));var T=3;if(b.length>=T)for(f=m.parentNode;f.tagName!=="BODY";){for(var M=0,H=0;H<b.length&&M<T;H++)M+=Number(b[H].includes(f));if(M>=T){m=f;break}f=f.parentNode}m.readability||this._initializeNode(m),f=m.parentNode;for(var $=m.readability.contentScore,W=$/3;f.tagName!=="BODY";){if(!f.readability){f=f.parentNode;continue}var I=f.readability.contentScore;if(I<W)break;if(I>$){m=f;break}$=f.readability.contentScore,f=f.parentNode}for(f=m.parentNode;f.tagName!="BODY"&&f.children.length==1;)m=f,f=m.parentNode;m.readability||this._initializeNode(m)}var k=t.createElement("DIV");e&&(k.id="readability-content");var U=Math.max(10,m.readability.contentScore*.2);f=m.parentNode;for(var F=f.children,R=0,V=F.length;R<V;R++){var L=F[R],ee=!1;if(this.log("Looking at sibling node:",L,L.readability?"with score "+L.readability.contentScore:""),this.log("Sibling has score",L.readability?L.readability.contentScore:"Unknown"),L===m)ee=!0;else{var Et=0;if(L.className===m.className&&m.className!==""&&(Et+=m.readability.contentScore*.2),L.readability&&L.readability.contentScore+Et>=U)ee=!0;else if(L.nodeName==="P"){var St=this._getLinkDensity(L),xt=this._getInnerText(L),We=xt.length;(We>80&&St<.25||We<80&&We>0&&St===0&&xt.search(/\.( |$)/)!==-1)&&(ee=!0)}}ee&&(this.log("Appending node:",L),this.ALTER_TO_DIV_EXCEPTIONS.indexOf(L.nodeName)===-1&&(this.log("Altering sibling:",L,"to div."),L=this._setNodeTag(L,"DIV")),k.appendChild(L),F=f.children,R-=1,V-=1)}if(this._debug&&this.log("Article content pre-prep: "+k.innerHTML),this._prepArticle(k),this._debug&&this.log("Article content post-prep: "+k.innerHTML),_)m.id="readability-page-1",m.className="page";else{var pe=t.createElement("DIV");for(pe.id="readability-page-1",pe.className="page";k.firstChild;)pe.appendChild(k.firstChild);k.appendChild(pe)}this._debug&&this.log("Article content after paging: "+k.innerHTML);var Ue=!0,te=this._getInnerText(k,!0).length;if(te<this._charThreshold)if(Ue=!1,n.innerHTML=i,this._flagIsActive(this.FLAG_STRIP_UNLIKELYS))this._removeFlag(this.FLAG_STRIP_UNLIKELYS),this._attempts.push({articleContent:k,textLength:te});else if(this._flagIsActive(this.FLAG_WEIGHT_CLASSES))this._removeFlag(this.FLAG_WEIGHT_CLASSES),this._attempts.push({articleContent:k,textLength:te});else if(this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY))this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY),this._attempts.push({articleContent:k,textLength:te});else{if(this._attempts.push({articleContent:k,textLength:te}),this._attempts.sort(function(D,B){return B.textLength-D.textLength}),!this._attempts[0].textLength)return null;k=this._attempts[0].articleContent,Ue=!0}if(Ue){var Wn=[f,m].concat(this._getNodeAncestors(f));return this._someNode(Wn,function(D){if(!D.tagName)return!1;var B=D.getAttribute("dir");return B?(this._articleDir=B,!0):!1}),k}}},_isValidByline:function(n){return typeof n=="string"||n instanceof String?(n=n.trim(),n.length>0&&n.length<100):!1},_unescapeHtmlEntities:function(n){if(!n)return n;var t=this.HTML_ESCAPE_MAP;return n.replace(/&(quot|amp|apos|lt|gt);/g,function(e,i){return t[i]}).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi,function(e,i,s){var r=parseInt(i||s,i?16:10);return String.fromCharCode(r)})},_getJSONLD:function(n){var t=this._getAllNodesWithTag(n,["script"]),e;return this._forEachNode(t,function(i){if(!e&&i.getAttribute("type")==="application/ld+json")try{var s=i.textContent.replace(/^\s*<!\[CDATA\[|\]\]>\s*$/g,""),r=JSON.parse(s);if(!r["@context"]||!r["@context"].match(/^https?\:\/\/schema\.org$/)||(!r["@type"]&&Array.isArray(r["@graph"])&&(r=r["@graph"].find(function(c){return(c["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes)})),!r||!r["@type"]||!r["@type"].match(this.REGEXPS.jsonLdArticleTypes)))return;if(e={},typeof r.name=="string"&&typeof r.headline=="string"&&r.name!==r.headline){var a=this._getArticleTitle(),o=this._textSimilarity(r.name,a)>.75,l=this._textSimilarity(r.headline,a)>.75;l&&!o?e.title=r.headline:e.title=r.name}else typeof r.name=="string"?e.title=r.name.trim():typeof r.headline=="string"&&(e.title=r.headline.trim());r.author&&(typeof r.author.name=="string"?e.byline=r.author.name.trim():Array.isArray(r.author)&&r.author[0]&&typeof r.author[0].name=="string"&&(e.byline=r.author.filter(function(c){return c&&typeof c.name=="string"}).map(function(c){return c.name.trim()}).join(", "))),typeof r.description=="string"&&(e.excerpt=r.description.trim()),r.publisher&&typeof r.publisher.name=="string"&&(e.siteName=r.publisher.name.trim()),typeof r.datePublished=="string"&&(e.datePublished=r.datePublished.trim());return}catch(c){this.log(c.message)}}),e||{}},_getArticleMetadata:function(n){var t={},e={},i=this._doc.getElementsByTagName("meta"),s=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,r=/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;return this._forEachNode(i,function(a){var o=a.getAttribute("name"),l=a.getAttribute("property"),c=a.getAttribute("content");if(c){var u=null,d=null;l&&(u=l.match(s),u&&(d=u[0].toLowerCase().replace(/\s/g,""),e[d]=c.trim())),!u&&o&&r.test(o)&&(d=o,c&&(d=d.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),e[d]=c.trim()))}}),t.title=n.title||e["dc:title"]||e["dcterm:title"]||e["og:title"]||e["weibo:article:title"]||e["weibo:webpage:title"]||e.title||e["twitter:title"],t.title||(t.title=this._getArticleTitle()),t.byline=n.byline||e["dc:creator"]||e["dcterm:creator"]||e.author,t.excerpt=n.excerpt||e["dc:description"]||e["dcterm:description"]||e["og:description"]||e["weibo:article:description"]||e["weibo:webpage:description"]||e.description||e["twitter:description"],t.siteName=n.siteName||e["og:site_name"],t.publishedTime=n.datePublished||e["article:published_time"]||null,t.title=this._unescapeHtmlEntities(t.title),t.byline=this._unescapeHtmlEntities(t.byline),t.excerpt=this._unescapeHtmlEntities(t.excerpt),t.siteName=this._unescapeHtmlEntities(t.siteName),t.publishedTime=this._unescapeHtmlEntities(t.publishedTime),t},_isSingleImage:function(n){return n.tagName==="IMG"?!0:n.children.length!==1||n.textContent.trim()!==""?!1:this._isSingleImage(n.children[0])},_unwrapNoscriptImages:function(n){var t=Array.from(n.getElementsByTagName("img"));this._forEachNode(t,function(i){for(var s=0;s<i.attributes.length;s++){var r=i.attributes[s];switch(r.name){case"src":case"srcset":case"data-src":case"data-srcset":return}if(/\.(jpg|jpeg|png|webp)/i.test(r.value))return}i.parentNode.removeChild(i)});var e=Array.from(n.getElementsByTagName("noscript"));this._forEachNode(e,function(i){var s=n.createElement("div");if(s.innerHTML=i.innerHTML,!!this._isSingleImage(s)){var r=i.previousElementSibling;if(r&&this._isSingleImage(r)){var a=r;a.tagName!=="IMG"&&(a=r.getElementsByTagName("img")[0]);for(var o=s.getElementsByTagName("img")[0],l=0;l<a.attributes.length;l++){var c=a.attributes[l];if(c.value!==""&&(c.name==="src"||c.name==="srcset"||/\.(jpg|jpeg|png|webp)/i.test(c.value))){if(o.getAttribute(c.name)===c.value)continue;var u=c.name;o.hasAttribute(u)&&(u="data-old-"+u),o.setAttribute(u,c.value)}}i.parentNode.replaceChild(s.firstElementChild,r)}}})},_removeScripts:function(n){this._removeNodes(this._getAllNodesWithTag(n,["script","noscript"]))},_hasSingleTagInsideElement:function(n,t){return n.children.length!=1||n.children[0].tagName!==t?!1:!this._someNode(n.childNodes,function(e){return e.nodeType===this.TEXT_NODE&&this.REGEXPS.hasContent.test(e.textContent)})},_isElementWithoutContent:function(n){return n.nodeType===this.ELEMENT_NODE&&n.textContent.trim().length==0&&(n.children.length==0||n.children.length==n.getElementsByTagName("br").length+n.getElementsByTagName("hr").length)},_hasChildBlockElement:function(n){return this._someNode(n.childNodes,function(t){return this.DIV_TO_P_ELEMS.has(t.tagName)||this._hasChildBlockElement(t)})},_isPhrasingContent:function(n){return n.nodeType===this.TEXT_NODE||this.PHRASING_ELEMS.indexOf(n.tagName)!==-1||(n.tagName==="A"||n.tagName==="DEL"||n.tagName==="INS")&&this._everyNode(n.childNodes,this._isPhrasingContent)},_isWhitespace:function(n){return n.nodeType===this.TEXT_NODE&&n.textContent.trim().length===0||n.nodeType===this.ELEMENT_NODE&&n.tagName==="BR"},_getInnerText:function(n,t){t=typeof t=="undefined"?!0:t;var e=n.textContent.trim();return t?e.replace(this.REGEXPS.normalize," "):e},_getCharCount:function(n,t){return t=t||",",this._getInnerText(n).split(t).length-1},_cleanStyles:function(n){if(!(!n||n.tagName.toLowerCase()==="svg")){for(var t=0;t<this.PRESENTATIONAL_ATTRIBUTES.length;t++)n.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[t]);this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.indexOf(n.tagName)!==-1&&(n.removeAttribute("width"),n.removeAttribute("height"));for(var e=n.firstElementChild;e!==null;)this._cleanStyles(e),e=e.nextElementSibling}},_getLinkDensity:function(n){var t=this._getInnerText(n).length;if(t===0)return 0;var e=0;return this._forEachNode(n.getElementsByTagName("a"),function(i){var s=i.getAttribute("href"),r=s&&this.REGEXPS.hashUrl.test(s)?.3:1;e+=this._getInnerText(i).length*r}),e/t},_getClassWeight:function(n){if(!this._flagIsActive(this.FLAG_WEIGHT_CLASSES))return 0;var t=0;return typeof n.className=="string"&&n.className!==""&&(this.REGEXPS.negative.test(n.className)&&(t-=25),this.REGEXPS.positive.test(n.className)&&(t+=25)),typeof n.id=="string"&&n.id!==""&&(this.REGEXPS.negative.test(n.id)&&(t-=25),this.REGEXPS.positive.test(n.id)&&(t+=25)),t},_clean:function(n,t){var e=["object","embed","iframe"].indexOf(t)!==-1;this._removeNodes(this._getAllNodesWithTag(n,[t]),function(i){if(e){for(var s=0;s<i.attributes.length;s++)if(this._allowedVideoRegex.test(i.attributes[s].value))return!1;if(i.tagName==="object"&&this._allowedVideoRegex.test(i.innerHTML))return!1}return!0})},_hasAncestorTag:function(n,t,e,i){e=e||3,t=t.toUpperCase();for(var s=0;n.parentNode;){if(e>0&&s>e)return!1;if(n.parentNode.tagName===t&&(!i||i(n.parentNode)))return!0;n=n.parentNode,s++}return!1},_getRowAndColumnCount:function(n){for(var t=0,e=0,i=n.getElementsByTagName("tr"),s=0;s<i.length;s++){var r=i[s].getAttribute("rowspan")||0;r&&(r=parseInt(r,10)),t+=r||1;for(var a=0,o=i[s].getElementsByTagName("td"),l=0;l<o.length;l++){var c=o[l].getAttribute("colspan")||0;c&&(c=parseInt(c,10)),a+=c||1}e=Math.max(e,a)}return{rows:t,columns:e}},_markDataTables:function(n){for(var t=n.getElementsByTagName("table"),e=0;e<t.length;e++){var i=t[e],s=i.getAttribute("role");if(s=="presentation"){i._readabilityDataTable=!1;continue}var r=i.getAttribute("datatable");if(r=="0"){i._readabilityDataTable=!1;continue}var a=i.getAttribute("summary");if(a){i._readabilityDataTable=!0;continue}var o=i.getElementsByTagName("caption")[0];if(o&&o.childNodes.length>0){i._readabilityDataTable=!0;continue}var l=["col","colgroup","tfoot","thead","th"],c=function(d){return!!i.getElementsByTagName(d)[0]};if(l.some(c)){this.log("Data table because found data-y descendant"),i._readabilityDataTable=!0;continue}if(i.getElementsByTagName("table")[0]){i._readabilityDataTable=!1;continue}var u=this._getRowAndColumnCount(i);if(u.rows>=10||u.columns>4){i._readabilityDataTable=!0;continue}i._readabilityDataTable=u.rows*u.columns>10}},_fixLazyImages:function(n){this._forEachNode(this._getAllNodesWithTag(n,["img","picture","figure"]),function(t){if(t.src&&this.REGEXPS.b64DataUrl.test(t.src)){var e=this.REGEXPS.b64DataUrl.exec(t.src);if(e[1]==="image/svg+xml")return;for(var i=!1,s=0;s<t.attributes.length;s++){var r=t.attributes[s];if(r.name!=="src"&&/\.(jpg|jpeg|png|webp)/i.test(r.value)){i=!0;break}}if(i){var a=t.src.search(/base64\s*/i)+7,o=t.src.length-a;o<133&&t.removeAttribute("src")}}if(!((t.src||t.srcset&&t.srcset!="null")&&t.className.toLowerCase().indexOf("lazy")===-1)){for(var l=0;l<t.attributes.length;l++)if(r=t.attributes[l],!(r.name==="src"||r.name==="srcset"||r.name==="alt")){var c=null;if(/\.(jpg|jpeg|png|webp)\s+\d/.test(r.value)?c="srcset":/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(r.value)&&(c="src"),c){if(t.tagName==="IMG"||t.tagName==="PICTURE")t.setAttribute(c,r.value);else if(t.tagName==="FIGURE"&&!this._getAllNodesWithTag(t,["img","picture"]).length){var u=this._doc.createElement("img");u.setAttribute(c,r.value),t.appendChild(u)}}}}})},_getTextDensity:function(n,t){var e=this._getInnerText(n,!0).length;if(e===0)return 0;var i=0,s=this._getAllNodesWithTag(n,t);return this._forEachNode(s,r=>i+=this._getInnerText(r,!0).length),i/e},_cleanConditionally:function(n,t){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(n,[t]),function(e){var i=function(f){return f._readabilityDataTable},s=t==="ul"||t==="ol";if(!s){var r=0,a=this._getAllNodesWithTag(e,["ul","ol"]);this._forEachNode(a,f=>r+=this._getInnerText(f).length),s=r/this._getInnerText(e).length>.9}if(t==="table"&&i(e)||this._hasAncestorTag(e,"table",-1,i)||this._hasAncestorTag(e,"code"))return!1;var o=this._getClassWeight(e);this.log("Cleaning Conditionally",e);var l=0;if(o+l<0)return!0;if(this._getCharCount(e,",")<10){for(var c=e.getElementsByTagName("p").length,u=e.getElementsByTagName("img").length,d=e.getElementsByTagName("li").length-100,h=e.getElementsByTagName("input").length,p=this._getTextDensity(e,["h1","h2","h3","h4","h5","h6"]),g=0,y=this._getAllNodesWithTag(e,["object","embed","iframe"]),v=0;v<y.length;v++){for(var w=0;w<y[v].attributes.length;w++)if(this._allowedVideoRegex.test(y[v].attributes[w].value))return!1;if(y[v].tagName==="object"&&this._allowedVideoRegex.test(y[v].innerHTML))return!1;g++}var E=this._getLinkDensity(e),A=this._getInnerText(e).length,m=u>1&&c/u<.5&&!this._hasAncestorTag(e,"figure")||!s&&d>c||h>Math.floor(c/3)||!s&&p<.9&&A<25&&(u===0||u>2)&&!this._hasAncestorTag(e,"figure")||!s&&o<25&&E>.2||o>=25&&E>.5||g===1&&A<75||g>1;if(s&&m){for(var _=0;_<e.children.length;_++)if(e.children[_].children.length>1)return m;let f=e.getElementsByTagName("li").length;if(u==f)return!1}return m}return!1})},_cleanMatchedNodes:function(n,t){for(var e=this._getNextNode(n,!0),i=this._getNextNode(n);i&&i!=e;)t.call(this,i,i.className+" "+i.id)?i=this._removeAndGetNext(i):i=this._getNextNode(i)},_cleanHeaders:function(n){let t=this._getAllNodesWithTag(n,["h1","h2"]);this._removeNodes(t,function(e){let i=this._getClassWeight(e)<0;return i&&this.log("Removing header with low class weight:",e),i})},_headerDuplicatesTitle:function(n){if(n.tagName!="H1"&&n.tagName!="H2")return!1;var t=this._getInnerText(n,!1);return this.log("Evaluating similarity of header:",t,this._articleTitle),this._textSimilarity(this._articleTitle,t)>.75},_flagIsActive:function(n){return(this._flags&n)>0},_removeFlag:function(n){this._flags=this._flags&~n},_isProbablyVisible:function(n){return(!n.style||n.style.display!="none")&&(!n.style||n.style.visibility!="hidden")&&!n.hasAttribute("hidden")&&(!n.hasAttribute("aria-hidden")||n.getAttribute("aria-hidden")!="true"||n.className&&n.className.indexOf&&n.className.indexOf("fallback-image")!==-1)},parse:function(){if(this._maxElemsToParse>0){var n=this._doc.getElementsByTagName("*").length;if(n>this._maxElemsToParse)throw new Error("Aborting parsing document; "+n+" elements found")}this._unwrapNoscriptImages(this._doc);var t=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var e=this._getArticleMetadata(t);this._articleTitle=e.title;var i=this._grabArticle();if(!i)return null;if(this.log("Grabbed: "+i.innerHTML),this._postProcessContent(i),!e.excerpt){var s=i.getElementsByTagName("p");s.length>0&&(e.excerpt=s[0].textContent.trim())}var r=i.textContent;return{title:this._articleTitle,byline:e.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(i),textContent:r,length:r.length,excerpt:e.excerpt,siteName:e.siteName||this._articleSiteName,publishedTime:e.publishedTime}}};typeof Ke=="object"&&(Ke.exports=Ht)});var $t=N((Dr,ze)=>{var Bt={unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i};function Xn(n){return(!n.style||n.style.display!="none")&&!n.hasAttribute("hidden")&&(!n.hasAttribute("aria-hidden")||n.getAttribute("aria-hidden")!="true"||n.className&&n.className.indexOf&&n.className.indexOf("fallback-image")!==-1)}function Yn(n,t={}){typeof t=="function"&&(t={visibilityChecker:t});var e={minScore:20,minContentLength:140,visibilityChecker:Xn};t=Object.assign(e,t);var i=n.querySelectorAll("p, pre, article"),s=n.querySelectorAll("div > br");if(s.length){var r=new Set(i);[].forEach.call(s,function(o){r.add(o.parentNode)}),i=Array.from(r)}var a=0;return[].some.call(i,function(o){if(!t.visibilityChecker(o))return!1;var l=o.className+" "+o.id;if(Bt.unlikelyCandidates.test(l)&&!Bt.okMaybeItsACandidate.test(l)||o.matches("li p"))return!1;var c=o.textContent.trim().length;return c<t.minContentLength?!1:(a+=Math.sqrt(c-t.minContentLength),a>t.minScore)})}typeof ze=="object"&&(ze.exports=Yn)});var Ut=N((Or,Wt)=>{var Jn=Ft(),Qn=$t();Wt.exports={Readability:Jn,isProbablyReaderable:Qn}});var O=N(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.default=Xt;function Xt(){}Xt.prototype={diff:function(t,e){var i,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=s.callback;typeof s=="function"&&(r=s,s={}),this.options=s;var a=this;function o(m){return r?(setTimeout(function(){r(void 0,m)},0),!0):m}t=this.castInput(t),e=this.castInput(e),t=this.removeEmpty(this.tokenize(t)),e=this.removeEmpty(this.tokenize(e));var l=e.length,c=t.length,u=1,d=l+c;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(i=s.timeout)!==null&&i!==void 0?i:1/0,p=Date.now()+h,g=[{oldPos:-1,lastComponent:void 0}],y=this.extractCommon(g[0],e,t,0);if(g[0].oldPos+1>=c&&y+1>=l)return o([{value:this.join(e),count:e.length}]);var v=-1/0,w=1/0;function E(){for(var m=Math.max(v,-u);m<=Math.min(w,u);m+=2){var _=void 0,f=g[m-1],b=g[m+1];f&&(g[m-1]=void 0);var x=!1;if(b){var T=b.oldPos-m;x=b&&0<=T&&T<l}var M=f&&f.oldPos+1<c;if(!x&&!M){g[m]=void 0;continue}if(!M||x&&f.oldPos+1<b.oldPos?_=a.addToPath(b,!0,void 0,0):_=a.addToPath(f,void 0,!0,1),y=a.extractCommon(_,e,t,m),_.oldPos+1>=c&&y+1>=l)return o(ri(a,_.lastComponent,e,t,a.useLongestToken));g[m]=_,_.oldPos+1>=c&&(w=Math.min(w,m-1)),y+1>=l&&(v=Math.max(v,m+1))}u++}if(r)(function m(){setTimeout(function(){if(u>d||Date.now()>p)return r();E()||m()},0)})();else for(;u<=d&&Date.now()<=p;){var A=E();if(A)return A}},addToPath:function(t,e,i,s){var r=t.lastComponent;return r&&r.added===e&&r.removed===i?{oldPos:t.oldPos+s,lastComponent:{count:r.count+1,added:e,removed:i,previousComponent:r.previousComponent}}:{oldPos:t.oldPos+s,lastComponent:{count:1,added:e,removed:i,previousComponent:r}}},extractCommon:function(t,e,i,s){for(var r=e.length,a=i.length,o=t.oldPos,l=o-s,c=0;l+1<r&&o+1<a&&this.equals(e[l+1],i[o+1]);)l++,o++,c++;return c&&(t.lastComponent={count:c,previousComponent:t.lastComponent}),t.oldPos=o,l},equals:function(t,e){return this.options.comparator?this.options.comparator(t,e):t===e||this.options.ignoreCase&&t.toLowerCase()===e.toLowerCase()},removeEmpty:function(t){for(var e=[],i=0;i<t.length;i++)t[i]&&e.push(t[i]);return e},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function ri(n,t,e,i,s){for(var r=[],a;t;)r.push(t),a=t.previousComponent,delete t.previousComponent,t=a;r.reverse();for(var o=0,l=r.length,c=0,u=0;o<l;o++){var d=r[o];if(d.removed){if(d.value=n.join(i.slice(u,u+d.count)),u+=d.count,o&&r[o-1].added){var p=r[o-1];r[o-1]=r[o],r[o]=p}}else{if(!d.added&&s){var h=e.slice(c,c+d.count);h=h.map(function(y,v){var w=i[u+v];return w.length>y.length?w:y}),d.value=n.join(h)}else d.value=n.join(e.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var g=r[l-1];return l>1&&typeof g.value=="string"&&(g.added||g.removed)&&n.equals("",g.value)&&(r[l-2].value+=g.value,r.pop()),r}});var Jt=N(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.diffChars=oi;ae.characterDiff=void 0;var si=ai(O());function ai(n){return n&&n.__esModule?n:{default:n}}var Yt=new si.default;ae.characterDiff=Yt;function oi(n,t,e){return Yt.diff(n,t,e)}});var tt=N(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.generateOptions=li;function li(n,t){if(typeof n=="function")t.callback=n;else if(n)for(var e in n)n.hasOwnProperty(e)&&(t[e]=n[e]);return t}});var en=N(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.diffWords=di;z.diffWordsWithSpace=pi;z.wordDiff=void 0;var ci=hi(O()),ui=tt();function hi(n){return n&&n.__esModule?n:{default:n}}var Qt=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Zt=/\S/,oe=new ci.default;z.wordDiff=oe;oe.equals=function(n,t){return this.options.ignoreCase&&(n=n.toLowerCase(),t=t.toLowerCase()),n===t||this.options.ignoreWhitespace&&!Zt.test(n)&&!Zt.test(t)};oe.tokenize=function(n){for(var t=n.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),e=0;e<t.length-1;e++)!t[e+1]&&t[e+2]&&Qt.test(t[e])&&Qt.test(t[e+2])&&(t[e]+=t[e+2],t.splice(e+1,2),e--);return t};function di(n,t,e){return e=(0,ui.generateOptions)(e,{ignoreWhitespace:!0}),oe.diff(n,t,e)}function pi(n,t,e){return oe.diff(n,t,e)}});var xe=N(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.diffLines=yi;X.diffTrimmedLines=vi;X.lineDiff=void 0;var gi=mi(O()),fi=tt();function mi(n){return n&&n.__esModule?n:{default:n}}var Se=new gi.default;X.lineDiff=Se;Se.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
`));var t=[],e=n.split(/(\n|\r\n)/);e[e.length-1]||e.pop();for(var i=0;i<e.length;i++){var s=e[i];i%2&&!this.options.newlineIsToken?t[t.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),t.push(s))}return t};function yi(n,t,e){return Se.diff(n,t,e)}function vi(n,t,e){var i=(0,fi.generateOptions)(e,{ignoreWhitespace:!0});return Se.diff(n,t,i)}});var tn=N(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.diffSentences=_i;le.sentenceDiff=void 0;var wi=bi(O());function bi(n){return n&&n.__esModule?n:{default:n}}var nt=new wi.default;le.sentenceDiff=nt;nt.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};function _i(n,t,e){return nt.diff(n,t,e)}});var nn=N(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.diffCss=xi;ce.cssDiff=void 0;var Ei=Si(O());function Si(n){return n&&n.__esModule?n:{default:n}}var it=new Ei.default;ce.cssDiff=it;it.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};function xi(n,t,e){return it.diff(n,t,e)}});var sn=N(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.diffJson=Ni;Y.canonicalize=Ae;Y.jsonDiff=void 0;var rn=Ai(O()),Ti=xe();function Ai(n){return n&&n.__esModule?n:{default:n}}function Te(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Te=function(e){return typeof e}:Te=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Te(n)}var Ci=Object.prototype.toString,G=new rn.default;Y.jsonDiff=G;G.useLongestToken=!0;G.tokenize=Ti.lineDiff.tokenize;G.castInput=function(n){var t=this.options,e=t.undefinedReplacement,i=t.stringifyReplacer,s=i===void 0?function(r,a){return typeof a=="undefined"?e:a}:i;return typeof n=="string"?n:JSON.stringify(Ae(n,null,null,s),s," ")};G.equals=function(n,t){return rn.default.prototype.equals.call(G,n.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Ni(n,t,e){return G.diff(n,t,e)}function Ae(n,t,e,i,s){t=t||[],e=e||[],i&&(n=i(s,n));var r;for(r=0;r<t.length;r+=1)if(t[r]===n)return e[r];var a;if(Ci.call(n)==="[object Array]"){for(t.push(n),a=new Array(n.length),e.push(a),r=0;r<n.length;r+=1)a[r]=Ae(n[r],t,e,i,s);return t.pop(),e.pop(),a}if(n&&n.toJSON&&(n=n.toJSON()),Te(n)==="object"&&n!==null){t.push(n),a={},e.push(a);var o=[],l;for(l in n)n.hasOwnProperty(l)&&o.push(l);for(o.sort(),r=0;r<o.length;r+=1)l=o[r],a[l]=Ae(n[l],t,e,i,l);t.pop(),e.pop()}else a=n;return a}});var an=N(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.diffArrays=Li;he.arrayDiff=void 0;var Pi=ki(O());function ki(n){return n&&n.__esModule?n:{default:n}}var ue=new Pi.default;he.arrayDiff=ue;ue.tokenize=function(n){return n.slice()};ue.join=ue.removeEmpty=function(n){return n};function Li(n,t,e){return ue.diff(n,t,e)}});var Ce=N(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.parsePatch=Mi;function Mi(n){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},e=n.split(/\r\n|[\n\v\f\r\x85]/),i=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],s=[],r=0;function a(){var c={};for(s.push(c);r<e.length;){var u=e[r];if(/^(\-\-\-|\+\+\+|@@)\s/.test(u))break;var d=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(u);d&&(c.index=u.substring(d[0].length).trim()),r++}for(o(c),o(c),c.hunks=[];r<e.length;){var h=e[r];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))c.hunks.push(l());else{if(h&&t.strict)throw new Error("Unknown line "+(r+1)+" "+JSON.stringify(h));r++}}}function o(c){var u=/^(---|\+\+\+)\s+/.exec(e[r]);if(u){var d=u[1]==="---"?"old":"new",h=e[r].substring(3).trim().split(" ",2),p=h[0].replace(/\\\\/g,"\\");p.startsWith('"')&&p.endsWith('"')&&(p=p.substr(1,p.length-2)),c[d+"FileName"]=p,c[d+"Header"]=(h[1]||"").trim(),r++}}function l(){var c=r,u=e[r++],d=u.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+d[1],oldLines:typeof d[2]=="undefined"?1:+d[2],newStart:+d[3],newLines:typeof d[4]=="undefined"?1:+d[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var p=0,g=0;r<e.length&&!(e[r].indexOf("--- ")===0&&r+2<e.length&&e[r+1].indexOf("+++ ")===0&&e[r+2].indexOf("@@")===0);r++){var y=e[r].length==0&&r!=e.length-1?" ":e[r][0];if(y==="+"||y==="-"||y===" "||y==="\\")h.lines.push(e[r]),h.linedelimiters.push(i[r]||`
`),y==="+"?p++:y==="-"?g++:y===" "&&(p++,g++);else break}if(!p&&h.newLines===1&&(h.newLines=0),!g&&h.oldLines===1&&(h.oldLines=0),t.strict){if(p!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(c+1));if(g!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(c+1))}return h}for(;r<e.length;)a();return s}});var on=N(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.default=Ri;function Ri(n,t,e){var i=!0,s=!1,r=!1,a=1;return function o(){if(i&&!r){if(s?a++:i=!1,n+a<=e)return a;r=!0}if(!s)return r||(i=!0),t<=n-a?-a++:(s=!0,o())}}});var un=N(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.applyPatch=cn;Ne.applyPatches=Oi;var ln=Ce(),Ii=Di(on());function Di(n){return n&&n.__esModule?n:{default:n}}function cn(n,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof t=="string"&&(t=(0,ln.parsePatch)(t)),Array.isArray(t)){if(t.length>1)throw new Error("applyPatch only works with a single input.");t=t[0]}var i=n.split(/\r\n|[\n\v\f\r\x85]/),s=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],r=t.hunks,a=e.compareLine||function(k,U,F,R){return U===R},o=0,l=e.fuzzFactor||0,c=0,u=0,d,h;function p(k,U){for(var F=0;F<k.lines.length;F++){var R=k.lines[F],V=R.length>0?R[0]:" ",L=R.length>0?R.substr(1):R;if(V===" "||V==="-"){if(!a(U+1,i[U],V,L)&&(o++,o>l))return!1;U++}}return!0}for(var g=0;g<r.length;g++){for(var y=r[g],v=i.length-y.oldLines,w=0,E=u+y.oldStart-1,A=(0,Ii.default)(E,c,v);w!==void 0;w=A())if(p(y,E+w)){y.offset=u+=w;break}if(w===void 0)return!1;c=y.offset+y.oldStart+y.oldLines}for(var m=0,_=0;_<r.length;_++){var f=r[_],b=f.oldStart+f.offset+m-1;m+=f.newLines-f.oldLines;for(var x=0;x<f.lines.length;x++){var T=f.lines[x],M=T.length>0?T[0]:" ",H=T.length>0?T.substr(1):T,$=f.linedelimiters&&f.linedelimiters[x]||`
`;if(M===" ")b++;else if(M==="-")i.splice(b,1),s.splice(b,1);else if(M==="+")i.splice(b,0,H),s.splice(b,0,$),b++;else if(M==="\\"){var W=f.lines[x-1]?f.lines[x-1][0]:null;W==="+"?d=!0:W==="-"&&(h=!0)}}}if(d)for(;!i[i.length-1];)i.pop(),s.pop();else h&&(i.push(""),s.push(`
`));for(var I=0;I<i.length-1;I++)i[I]=i[I]+s[I];return i.join("")}function Oi(n,t){typeof n=="string"&&(n=(0,ln.parsePatch)(n));var e=0;function i(){var s=n[e++];if(!s)return t.complete();t.loadFile(s,function(r,a){if(r)return t.complete(r);var o=cn(a,s,t);t.patched(s,o,function(l){if(l)return t.complete(l);i()})})}i()}});var ct=N(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.structuredPatch=hn;J.formatPatch=lt;J.createTwoFilesPatch=dn;J.createPatch=Ui;var Hi=xe();function at(n){return Wi(n)||$i(n)||Bi(n)||Fi()}function Fi(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Bi(n,t){if(n){if(typeof n=="string")return ot(n,t);var e=Object.prototype.toString.call(n).slice(8,-1);if(e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set")return Array.from(n);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return ot(n,t)}}function $i(n){if(typeof Symbol!="undefined"&&Symbol.iterator in Object(n))return Array.from(n)}function Wi(n){if(Array.isArray(n))return ot(n)}function ot(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=new Array(t);e<t;e++)i[e]=n[e];return i}function hn(n,t,e,i,s,r,a){a||(a={}),typeof a.context=="undefined"&&(a.context=4);var o=(0,Hi.diffLines)(e,i,a);if(!o)return;o.push({value:"",lines:[]});function l(w){return w.map(function(E){return" "+E})}for(var c=[],u=0,d=0,h=[],p=1,g=1,y=function(E){var A=o[E],m=A.lines||A.value.replace(/\n$/,"").split(`
`);if(A.lines=m,A.added||A.removed){var _;if(!u){var f=o[E-1];u=p,d=g,f&&(h=a.context>0?l(f.lines.slice(-a.context)):[],u-=h.length,d-=h.length)}(_=h).push.apply(_,at(m.map(function(I){return(A.added?"+":"-")+I}))),A.added?g+=m.length:p+=m.length}else{if(u)if(m.length<=a.context*2&&E<o.length-2){var b;(b=h).push.apply(b,at(l(m)))}else{var x,T=Math.min(m.length,a.context);(x=h).push.apply(x,at(l(m.slice(0,T))));var M={oldStart:u,oldLines:p-u+T,newStart:d,newLines:g-d+T,lines:h};if(E>=o.length-2&&m.length<=a.context){var H=/\n$/.test(e),$=/\n$/.test(i),W=m.length==0&&h.length>M.oldLines;!H&&W&&e.length>0&&h.splice(M.oldLines,0,"\\ No newline at end of file"),(!H&&!W||!$)&&h.push("\\ No newline at end of file")}c.push(M),u=0,d=0,h=[]}p+=m.length,g+=m.length}},v=0;v<o.length;v++)y(v);return{oldFileName:n,newFileName:t,oldHeader:s,newHeader:r,hunks:c}}function lt(n){if(Array.isArray(n))return n.map(lt).join(`
`);var t=[];n.oldFileName==n.newFileName&&t.push("Index: "+n.oldFileName),t.push("==================================================================="),t.push("--- "+n.oldFileName+(typeof n.oldHeader=="undefined"?"":" "+n.oldHeader)),t.push("+++ "+n.newFileName+(typeof n.newHeader=="undefined"?"":" "+n.newHeader));for(var e=0;e<n.hunks.length;e++){var i=n.hunks[e];i.oldLines===0&&(i.oldStart-=1),i.newLines===0&&(i.newStart-=1),t.push("@@ -"+i.oldStart+","+i.oldLines+" +"+i.newStart+","+i.newLines+" @@"),t.push.apply(t,i.lines)}return t.join(`
`)+`
`}function dn(n,t,e,i,s,r,a){return lt(hn(n,t,e,i,s,r,a))}function Ui(n,t,e,i,s,r){return dn(n,n,t,e,i,s,r)}});var gn=N(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.arrayEqual=qi;Pe.arrayStartsWith=pn;function qi(n,t){return n.length!==t.length?!1:pn(n,t)}function pn(n,t){if(t.length>n.length)return!1;for(var e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}});var Tn=N(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.calcLineCount=xn;Le.merge=Yi;var Gi=ct(),ji=Ce(),ut=gn();function Q(n){return Xi(n)||zi(n)||Ki(n)||Vi()}function Vi(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ki(n,t){if(n){if(typeof n=="string")return ht(n,t);var e=Object.prototype.toString.call(n).slice(8,-1);if(e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set")return Array.from(n);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return ht(n,t)}}function zi(n){if(typeof Symbol!="undefined"&&Symbol.iterator in Object(n))return Array.from(n)}function Xi(n){if(Array.isArray(n))return ht(n)}function ht(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=new Array(t);e<t;e++)i[e]=n[e];return i}function xn(n){var t=dt(n.lines),e=t.oldLines,i=t.newLines;e!==void 0?n.oldLines=e:delete n.oldLines,i!==void 0?n.newLines=i:delete n.newLines}function Yi(n,t,e){n=fn(n,e),t=fn(t,e);var i={};(n.index||t.index)&&(i.index=n.index||t.index),(n.newFileName||t.newFileName)&&(mn(n)?mn(t)?(i.oldFileName=ke(i,n.oldFileName,t.oldFileName),i.newFileName=ke(i,n.newFileName,t.newFileName),i.oldHeader=ke(i,n.oldHeader,t.oldHeader),i.newHeader=ke(i,n.newHeader,t.newHeader)):(i.oldFileName=n.oldFileName,i.newFileName=n.newFileName,i.oldHeader=n.oldHeader,i.newHeader=n.newHeader):(i.oldFileName=t.oldFileName||n.oldFileName,i.newFileName=t.newFileName||n.newFileName,i.oldHeader=t.oldHeader||n.oldHeader,i.newHeader=t.newHeader||n.newHeader)),i.hunks=[];for(var s=0,r=0,a=0,o=0;s<n.hunks.length||r<t.hunks.length;){var l=n.hunks[s]||{oldStart:1/0},c=t.hunks[r]||{oldStart:1/0};if(yn(l,c))i.hunks.push(vn(l,a)),s++,o+=l.newLines-l.oldLines;else if(yn(c,l))i.hunks.push(vn(c,o)),r++,a+=c.newLines-c.oldLines;else{var u={oldStart:Math.min(l.oldStart,c.oldStart),oldLines:0,newStart:Math.min(l.newStart+a,c.oldStart+o),newLines:0,lines:[]};Ji(u,l.oldStart,l.lines,c.oldStart,c.lines),r++,s++,i.hunks.push(u)}}return i}function fn(n,t){if(typeof n=="string"){if(/^@@/m.test(n)||/^Index:/m.test(n))return(0,ji.parsePatch)(n)[0];if(!t)throw new Error("Must provide a base reference or pass in a patch");return(0,Gi.structuredPatch)(void 0,void 0,t,n)}return n}function mn(n){return n.newFileName&&n.newFileName!==n.oldFileName}function ke(n,t,e){return t===e?t:(n.conflict=!0,{mine:t,theirs:e})}function yn(n,t){return n.oldStart<t.oldStart&&n.oldStart+n.oldLines<t.oldStart}function vn(n,t){return{oldStart:n.oldStart,oldLines:n.oldLines,newStart:n.newStart+t,newLines:n.newLines,lines:n.lines}}function Ji(n,t,e,i,s){var r={offset:t,lines:e,index:0},a={offset:i,lines:s,index:0};for(bn(n,r,a),bn(n,a,r);r.index<r.lines.length&&a.index<a.lines.length;){var o=r.lines[r.index],l=a.lines[a.index];if((o[0]==="-"||o[0]==="+")&&(l[0]==="-"||l[0]==="+"))Qi(n,r,a);else if(o[0]==="+"&&l[0]===" "){var c;(c=n.lines).push.apply(c,Q(j(r)))}else if(l[0]==="+"&&o[0]===" "){var u;(u=n.lines).push.apply(u,Q(j(a)))}else o[0]==="-"&&l[0]===" "?wn(n,r,a):l[0]==="-"&&o[0]===" "?wn(n,a,r,!0):o===l?(n.lines.push(o),r.index++,a.index++):pt(n,j(r),j(a))}_n(n,r),_n(n,a),xn(n)}function Qi(n,t,e){var i=j(t),s=j(e);if(En(i)&&En(s)){if((0,ut.arrayStartsWith)(i,s)&&Sn(e,i,i.length-s.length)){var r;(r=n.lines).push.apply(r,Q(i));return}else if((0,ut.arrayStartsWith)(s,i)&&Sn(t,s,s.length-i.length)){var a;(a=n.lines).push.apply(a,Q(s));return}}else if((0,ut.arrayEqual)(i,s)){var o;(o=n.lines).push.apply(o,Q(i));return}pt(n,i,s)}function wn(n,t,e,i){var s=j(t),r=Zi(e,s);if(r.merged){var a;(a=n.lines).push.apply(a,Q(r.merged))}else pt(n,i?r:s,i?s:r)}function pt(n,t,e){n.conflict=!0,n.lines.push({conflict:!0,mine:t,theirs:e})}function bn(n,t,e){for(;t.offset<e.offset&&t.index<t.lines.length;){var i=t.lines[t.index++];n.lines.push(i),t.offset++}}function _n(n,t){for(;t.index<t.lines.length;){var e=t.lines[t.index++];n.lines.push(e)}}function j(n){for(var t=[],e=n.lines[n.index][0];n.index<n.lines.length;){var i=n.lines[n.index];if(e==="-"&&i[0]==="+"&&(e="+"),e===i[0])t.push(i),n.index++;else break}return t}function Zi(n,t){for(var e=[],i=[],s=0,r=!1,a=!1;s<t.length&&n.index<n.lines.length;){var o=n.lines[n.index],l=t[s];if(l[0]==="+")break;if(r=r||o[0]!==" ",i.push(l),s++,o[0]==="+")for(a=!0;o[0]==="+";)e.push(o),o=n.lines[++n.index];l.substr(1)===o.substr(1)?(e.push(o),n.index++):a=!0}if((t[s]||"")[0]==="+"&&r&&(a=!0),a)return e;for(;s<t.length;)i.push(t[s++]);return{merged:i,changes:e}}function En(n){return n.reduce(function(t,e){return t&&e[0]==="-"},!0)}function Sn(n,t,e){for(var i=0;i<e;i++){var s=t[t.length-e+i].substr(1);if(n.lines[n.index+i]!==" "+s)return!1}return n.index+=e,!0}function dt(n){var t=0,e=0;return n.forEach(function(i){if(typeof i!="string"){var s=dt(i.mine),r=dt(i.theirs);t!==void 0&&(s.oldLines===r.oldLines?t+=s.oldLines:t=void 0),e!==void 0&&(s.newLines===r.newLines?e+=s.newLines:e=void 0)}else e!==void 0&&(i[0]==="+"||i[0]===" ")&&e++,t!==void 0&&(i[0]==="-"||i[0]===" ")&&t++}),{oldLines:t,newLines:e}}});var Pn=N(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reversePatch=Nn;function An(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),e.push.apply(e,i)}return e}function Cn(n){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?An(Object(e),!0).forEach(function(i){er(n,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)):An(Object(e)).forEach(function(i){Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(e,i))})}return n}function er(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function Nn(n){return Array.isArray(n)?n.map(Nn).reverse():Cn(Cn({},n),{},{oldFileName:n.newFileName,oldHeader:n.newHeader,newFileName:n.oldFileName,newHeader:n.oldHeader,hunks:n.hunks.map(function(t){return{oldLines:t.newLines,oldStart:t.newStart,newLines:t.oldLines,newStart:t.oldStart,linedelimiters:t.linedelimiters,lines:t.lines.map(function(e){return e.startsWith("-")?"+".concat(e.slice(1)):e.startsWith("+")?"-".concat(e.slice(1)):e})}})})}});var kn=N(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.convertChangesToDMP=tr;function tr(n){for(var t=[],e,i,s=0;s<n.length;s++)e=n[s],e.added?i=1:e.removed?i=-1:i=0,t.push([i,e.value]);return t}});var Ln=N(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.convertChangesToXML=nr;function nr(n){for(var t=[],e=0;e<n.length;e++){var i=n[e];i.added?t.push("<ins>"):i.removed&&t.push("<del>"),t.push(ir(i.value)),i.added?t.push("</ins>"):i.removed&&t.push("</del>")}return t.join("")}function ir(n){var t=n;return t=t.replace(/&/g,"&"),t=t.replace(/</g,"<"),t=t.replace(/>/g,">"),t=t.replace(/"/g,"""),t}});var On=N(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});Object.defineProperty(C,"Diff",{enumerable:!0,get:function(){return rr.default}});Object.defineProperty(C,"diffChars",{enumerable:!0,get:function(){return sr.diffChars}});Object.defineProperty(C,"diffWords",{enumerable:!0,get:function(){return Mn.diffWords}});Object.defineProperty(C,"diffWordsWithSpace",{enumerable:!0,get:function(){return Mn.diffWordsWithSpace}});Object.defineProperty(C,"diffLines",{enumerable:!0,get:function(){return Rn.diffLines}});Object.defineProperty(C,"diffTrimmedLines",{enumerable:!0,get:function(){return Rn.diffTrimmedLines}});Object.defineProperty(C,"diffSentences",{enumerable:!0,get:function(){return ar.diffSentences}});Object.defineProperty(C,"diffCss",{enumerable:!0,get:function(){return or.diffCss}});Object.defineProperty(C,"diffJson",{enumerable:!0,get:function(){return In.diffJson}});Object.defineProperty(C,"canonicalize",{enumerable:!0,get:function(){return In.canonicalize}});Object.defineProperty(C,"diffArrays",{enumerable:!0,get:function(){return lr.diffArrays}});Object.defineProperty(C,"applyPatch",{enumerable:!0,get:function(){return Dn.applyPatch}});Object.defineProperty(C,"applyPatches",{enumerable:!0,get:function(){return Dn.applyPatches}});Object.defineProperty(C,"parsePatch",{enumerable:!0,get:function(){return cr.parsePatch}});Object.defineProperty(C,"merge",{enumerable:!0,get:function(){return ur.merge}});Object.defineProperty(C,"reversePatch",{enumerable:!0,get:function(){return hr.reversePatch}});Object.defineProperty(C,"structuredPatch",{enumerable:!0,get:function(){return Me.structuredPatch}});Object.defineProperty(C,"createTwoFilesPatch",{enumerable:!0,get:function(){return Me.createTwoFilesPatch}});Object.defineProperty(C,"createPatch",{enumerable:!0,get:function(){return Me.createPatch}});Object.defineProperty(C,"formatPatch",{enumerable:!0,get:function(){return Me.formatPatch}});Object.defineProperty(C,"convertChangesToDMP",{enumerable:!0,get:function(){return dr.convertChangesToDMP}});Object.defineProperty(C,"convertChangesToXML",{enumerable:!0,get:function(){return pr.convertChangesToXML}});var rr=gr(O()),sr=Jt(),Mn=en(),Rn=xe(),ar=tn(),or=nn(),In=sn(),lr=an(),Dn=un(),cr=Ce(),ur=Tn(),hr=Pn(),Me=ct(),dr=kn(),pr=Ln();function gr(n){return n&&n.__esModule?n:{default:n}}});var _r={};jn(_r,{default:()=>$e});module.exports=Kn(_r);var P=require("obsidian");var S=require("obsidian");var Ct={mistral:"https://api.mistral.ai/v1",openai:"https://api.openai.com/v1",xai:"https://api.x.ai/v1",gemini:"https://generativelanguage.googleapis.com/v1beta/openai",openrouter:"https://openrouter.ai/api/v1",groq:"https://api.groq.com/openai/v1",anthropic:""},K=class{constructor(t){this.settings=t}updateSettings(t){this.settings=t}async chat(t,e){var s,r;return(r=(s=(await this.chatWithTools(t,[],e)).choices[0])==null?void 0:s.message.content)!=null?r:""}async chatWithTools(t,e,i){return this.settings.provider==="anthropic"?this.callAnthropic(t,e):this.callOpenAICompat(t,e,i)}getProviderKey(){switch(this.settings.provider){case"openai":return this.settings.openaiApiKey;case"xai":return this.settings.xaiApiKey;case"gemini":return this.settings.geminiApiKey;case"openrouter":return this.settings.openrouterApiKey;case"groq":return this.settings.groqApiKey;default:return this.settings.mistralApiKey}}getProviderModel(){switch(this.settings.provider){case"openai":return this.settings.openaiModel;case"xai":return this.settings.xaiModel;case"gemini":return this.settings.geminiModel;case"openrouter":return this.settings.openrouterModel;case"groq":return this.settings.groqModel;default:return this.settings.mistralModel}}sanitizeMessages(t){return t.map(e=>{var s,r;let i={role:e.role,content:(s=e.content)!=null?s:null};return e.tool_call_id&&(i.tool_call_id=e.tool_call_id),(r=e.tool_calls)!=null&&r.length&&(i.tool_calls=e.tool_calls),i})}async callOpenAICompat(t,e,i){var h;let s=this.settings.provider,r=Ct[s],a=this.getProviderKey(),o=s==="mistral"&&i?i:this.getProviderModel(),l=this.sanitizeMessages(t),c={model:o,messages:l};e.length>0&&(c.tools=e,c.tool_choice="auto");let u=new Error("Request failed"),d=4;for(let p=0;p<d;p++){p>0&&await this.delay(Math.pow(2,p)*1e3);try{let g={Authorization:`Bearer ${a}`,"Content-Type":"application/json"};s==="openrouter"&&(g["HTTP-Referer"]="https://github.com/pennote-ai",g["X-Title"]="PenNote AI");let y=await fetch(`${r}/chat/completions`,{method:"POST",headers:g,body:JSON.stringify(c)});if(y.status===401)throw new Error(`Invalid API key for ${s}.`);if(y.status===429){if(p<d-1){let v=(h=y.headers.get("retry-after"))!=null?h:y.headers.get("x-ratelimit-reset-requests"),w=v?this.parseRetryAfter(v):Math.pow(2,p+1)*2e3;u=new Error(`Rate limit exceeded for ${s}. Retrying in ${Math.round(w/1e3)}s...`),await this.delay(w);continue}throw new Error(`Rate limit exceeded for ${s}. Please wait before retrying.`)}if(!y.ok){let v=await y.text().catch(()=>"");throw new Error(`${s} API error: HTTP ${y.status} \u2014 ${v.slice(0,300)}`)}return y.json()}catch(g){if(u=g instanceof Error?g:new Error(String(g)),u.message.includes("Invalid API key")||!this.isRetryable(u))throw u}}throw u}async callAnthropic(t,e){var h;let i=this.settings.anthropicApiKey,s=this.settings.anthropicModel,r="",a=t.filter(p=>{var g;return p.role==="system"?(r=(g=p.content)!=null?g:"",!1):!0}),o=this.convertMessagesToAnthropic(a),l=e.map(p=>({name:p.function.name,description:p.function.description,input_schema:p.function.parameters})),c={model:s,max_tokens:8192,messages:o,...r?{system:r}:{},...l.length>0?{tools:l,tool_choice:{type:"auto"}}:{}},u=new Error("Request failed"),d=4;for(let p=0;p<d;p++){p>0&&await this.delay(Math.pow(2,p)*1e3);try{let g=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"x-api-key":i,"anthropic-version":"2023-06-01","Content-Type":"application/json"},body:JSON.stringify(c)});if(g.status===401)throw new Error("Invalid Anthropic API key.");if(g.status===429){if(p<d-1){let v=(h=g.headers.get("retry-after"))!=null?h:g.headers.get("anthropic-ratelimit-requests-reset"),w=v?this.parseRetryAfter(v):Math.pow(2,p+1)*2e3;u=new Error(`Anthropic rate limit exceeded. Retrying in ${Math.round(w/1e3)}s...`),await this.delay(w);continue}throw new Error("Anthropic rate limit exceeded. Please wait before retrying.")}if(!g.ok){let v=await g.text().catch(()=>"");throw new Error(`Anthropic API error: HTTP ${g.status} \u2014 ${v.slice(0,300)}`)}let y=await g.json();return this.normalizeAnthropicResponse(y)}catch(g){if(u=g instanceof Error?g:new Error(String(g)),u.message.includes("Invalid Anthropic")||!this.isRetryable(u))throw u}}throw u}convertMessagesToAnthropic(t){var i,s,r,a;let e=[];for(let o=0;o<t.length;o++){let l=t[o];if(l.role==="tool"){let c=[];for(;o<t.length&&t[o].role==="tool";)c.push({type:"tool_result",tool_use_id:(i=t[o].tool_call_id)!=null?i:"",content:(s=t[o].content)!=null?s:""}),o++;o--,e.push({role:"user",content:c});continue}if(l.role==="assistant"&&((r=l.tool_calls)!=null&&r.length)){let c=[];l.content&&c.push({type:"text",text:l.content});for(let u of l.tool_calls){let d={};try{d=JSON.parse(u.function.arguments||"{}")}catch(h){}c.push({type:"tool_use",id:u.id,name:u.function.name,input:d})}e.push({role:"assistant",content:c});continue}e.push({role:l.role,content:(a=l.content)!=null?a:""})}return e}normalizeAnthropicResponse(t){var r,a,o;let e=null,i=[];for(let l of t.content)l.type==="text"&&l.text?e=(e!=null?e:"")+l.text:l.type==="tool_use"&&i.push({id:(r=l.id)!=null?r:"",type:"function",function:{name:(a=l.name)!=null?a:"",arguments:JSON.stringify((o=l.input)!=null?o:{})}});let s=t.stop_reason==="tool_use"?"tool_calls":"stop";return{id:t.id,choices:[{index:0,message:{role:"assistant",content:e,...i.length>0?{tool_calls:i}:{}},finish_reason:s}],usage:{prompt_tokens:t.usage.input_tokens,completion_tokens:t.usage.output_tokens,total_tokens:t.usage.input_tokens+t.usage.output_tokens}}}async testConnection(){let t=this.settings.provider;if(t==="anthropic"){let a=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":this.settings.anthropicApiKey,"anthropic-version":"2023-06-01"}});if(a.status===401)throw new Error("Invalid API key.");if(!a.ok)throw new Error(`Anthropic API error: HTTP ${a.status}`);return}let e=Ct[t],i=this.getProviderKey(),s=`${e}/models`;t==="openrouter"&&(s="https://openrouter.ai/api/v1/models");let r=await fetch(s,{headers:{Authorization:`Bearer ${i}`}});if(r.status===401)throw new Error("Invalid API key.");if(!r.ok)throw new Error(`${t} API error: HTTP ${r.status}`)}isRetryable(t){return t.message.includes("rate limit")||t.message.includes("Retrying in")||t.message.includes("502")||t.message.includes("503")||t.message.includes("504")||t.message.includes("network")}parseRetryAfter(t){let e=Number(t);if(!isNaN(e)&&e>0)return Math.min(e*1e3,6e4);let i=Date.parse(t);return isNaN(i)?8e3:Math.min(Math.max(i-Date.now(),1e3),6e4)}delay(t){return new Promise(e=>setTimeout(e,t))}};var Nt={provider:"mistral",mistralApiKey:"",mistralModel:"mistral-large-latest",openaiApiKey:"",openaiModel:"gpt-4o",xaiApiKey:"",xaiModel:"grok-2-latest",geminiApiKey:"",geminiModel:"gemini-2.5-pro",anthropicApiKey:"",anthropicModel:"claude-opus-4-6",openrouterApiKey:"",openrouterModel:"anthropic/claude-opus-4-5",groqApiKey:"",groqModel:"moonshotai/kimi-k2-instruct",searchResultLimit:5,crawlTimeoutMs:15e3,maxAgentIterations:10,autoConfirmThreshold:"small-changes",methodologyRootFolder:"Pentest",methodologyTag:"methodology",enableScheduledRefresh:!1,refreshIntervalDays:7,playwrightEnabled:!0,contextWindowTokenBudget:8e3,debugMode:!1},fe=class extends S.PluginSettingTab{constructor(e,i){super(e,i);this.plugin=i}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"PenNote AI"}),e.createEl("h3",{text:"Provider"}),new S.Setting(e).setName("Active Provider").setDesc("Select the LLM provider to use for all agent operations.").addDropdown(s=>s.addOption("mistral","Mistral AI").addOption("openai","OpenAI").addOption("anthropic","Anthropic (Claude)").addOption("gemini","Google Gemini").addOption("xai","xAI (Grok)").addOption("groq","Groq").addOption("openrouter","OpenRouter").setValue(this.plugin.settings.provider).onChange(async r=>{this.plugin.settings.provider=r,await this.plugin.saveSettings(),this.display()}));let i=this.plugin.settings.provider;i==="mistral"&&(new S.Setting(e).setName("Mistral API Key").setDesc("Your Mistral API key from console.mistral.ai").addText(s=>{s.setPlaceholder("Enter API key...").setValue(this.plugin.settings.mistralApiKey).onChange(async r=>{this.plugin.settings.mistralApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("Function calling requires mistral-large-latest or mistral-medium-latest.").addDropdown(s=>s.addOption("mistral-large-latest","mistral-large-latest (recommended)").addOption("mistral-medium-latest","mistral-medium-latest").addOption("mistral-small-latest","mistral-small-latest").setValue(this.plugin.settings.mistralModel).onChange(async r=>{this.plugin.settings.mistralModel=r,await this.plugin.saveSettings()}))),i==="openai"&&(new S.Setting(e).setName("OpenAI API Key").setDesc("Your OpenAI API key from platform.openai.com").addText(s=>{s.setPlaceholder("sk-...").setValue(this.plugin.settings.openaiApiKey).onChange(async r=>{this.plugin.settings.openaiApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("e.g. gpt-4o, gpt-4-turbo, gpt-4o-mini").addText(s=>s.setPlaceholder("gpt-4o").setValue(this.plugin.settings.openaiModel).onChange(async r=>{r.trim()&&(this.plugin.settings.openaiModel=r.trim(),await this.plugin.saveSettings())}))),i==="anthropic"&&(new S.Setting(e).setName("Anthropic API Key").setDesc("Your Anthropic API key from console.anthropic.com").addText(s=>{s.setPlaceholder("sk-ant-...").setValue(this.plugin.settings.anthropicApiKey).onChange(async r=>{this.plugin.settings.anthropicApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("e.g. claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5").addText(s=>s.setPlaceholder("claude-opus-4-6").setValue(this.plugin.settings.anthropicModel).onChange(async r=>{r.trim()&&(this.plugin.settings.anthropicModel=r.trim(),await this.plugin.saveSettings())}))),i==="gemini"&&(new S.Setting(e).setName("Gemini API Key").setDesc("Your Gemini API key from aistudio.google.com").addText(s=>{s.setPlaceholder("Enter API key...").setValue(this.plugin.settings.geminiApiKey).onChange(async r=>{this.plugin.settings.geminiApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("e.g. gemini-2.5-pro, gemini-2.5-flash, gemini-2.0-flash").addText(s=>s.setPlaceholder("gemini-2.5-pro").setValue(this.plugin.settings.geminiModel).onChange(async r=>{r.trim()&&(this.plugin.settings.geminiModel=r.trim(),await this.plugin.saveSettings())}))),i==="xai"&&(new S.Setting(e).setName("xAI API Key").setDesc("Your xAI API key from console.x.ai").addText(s=>{s.setPlaceholder("xai-...").setValue(this.plugin.settings.xaiApiKey).onChange(async r=>{this.plugin.settings.xaiApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("e.g. grok-2-latest, grok-2-mini").addText(s=>s.setPlaceholder("grok-2-latest").setValue(this.plugin.settings.xaiModel).onChange(async r=>{r.trim()&&(this.plugin.settings.xaiModel=r.trim(),await this.plugin.saveSettings())}))),i==="groq"&&(new S.Setting(e).setName("Groq API Key").setDesc("Your Groq API key from console.groq.com/keys").addText(s=>{s.setPlaceholder("gsk_...").setValue(this.plugin.settings.groqApiKey).onChange(async r=>{this.plugin.settings.groqApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("e.g. moonshotai/kimi-k2-instruct, llama-3.3-70b-versatile, mixtral-8x7b-32768").addText(s=>s.setPlaceholder("moonshotai/kimi-k2-instruct").setValue(this.plugin.settings.groqModel).onChange(async r=>{r.trim()&&(this.plugin.settings.groqModel=r.trim(),await this.plugin.saveSettings())}))),i==="openrouter"&&(new S.Setting(e).setName("OpenRouter API Key").setDesc("Your OpenRouter API key from openrouter.ai/keys").addText(s=>{s.setPlaceholder("sk-or-...").setValue(this.plugin.settings.openrouterApiKey).onChange(async r=>{this.plugin.settings.openrouterApiKey=r.trim(),await this.plugin.saveSettings()}),s.inputEl.type="password",s.inputEl.style.width="100%"}),new S.Setting(e).setName("Model").setDesc("Full model ID from openrouter.ai/models \u2014 e.g. anthropic/claude-opus-4-5, openai/gpt-4o, google/gemini-2.5-pro").addText(s=>s.setPlaceholder("anthropic/claude-opus-4-5").setValue(this.plugin.settings.openrouterModel).onChange(async r=>{r.trim()&&(this.plugin.settings.openrouterModel=r.trim(),await this.plugin.saveSettings())}))),new S.Setting(e).setName("Test Connection").setDesc("Verify the active provider API key.").addButton(s=>s.setButtonText("Test").onClick(async()=>{try{await new K(this.plugin.settings).testConnection(),new S.Notice(`${i} connection successful.`)}catch(r){new S.Notice(`Connection failed: ${r instanceof Error?r.message:String(r)}`)}})),e.createEl("h3",{text:"Search & Crawl"}),new S.Setting(e).setName("Search Result Limit").setDesc("Maximum number of DuckDuckGo results to fetch per query.").addSlider(s=>s.setLimits(3,10,1).setValue(this.plugin.settings.searchResultLimit).setDynamicTooltip().onChange(async r=>{this.plugin.settings.searchResultLimit=r,await this.plugin.saveSettings()})),new S.Setting(e).setName("Crawl Timeout (ms)").setDesc("Maximum time to wait for a page to load. Default 15000.").addText(s=>s.setValue(String(this.plugin.settings.crawlTimeoutMs)).onChange(async r=>{let a=parseInt(r);!isNaN(a)&&a>=3e3&&(this.plugin.settings.crawlTimeoutMs=a,await this.plugin.saveSettings())})),new S.Setting(e).setName("Enable Playwright Crawler").setDesc("Use headless Chromium for JS-heavy pages. Requires playwright-core installed.").addToggle(s=>s.setValue(this.plugin.settings.playwrightEnabled).onChange(async r=>{this.plugin.settings.playwrightEnabled=r,await this.plugin.saveSettings()})),e.createEl("h3",{text:"Agent"}),new S.Setting(e).setName("Max Agent Iterations").setDesc("Maximum tool-call cycles per agent run to prevent runaway API usage.").addSlider(s=>s.setLimits(3,20,1).setValue(this.plugin.settings.maxAgentIterations).setDynamicTooltip().onChange(async r=>{this.plugin.settings.maxAgentIterations=r,await this.plugin.saveSettings()})),new S.Setting(e).setName("Auto-Confirm Writes").setDesc("When to apply changes without showing the diff review modal.").addDropdown(s=>s.addOption("never","Never (always review)").addOption("small-changes","Small changes only").addOption("always","Always (no review)").setValue(this.plugin.settings.autoConfirmThreshold).onChange(async r=>{this.plugin.settings.autoConfirmThreshold=r,await this.plugin.saveSettings()})),new S.Setting(e).setName("Context Window Token Budget").setDesc("Max tokens from existing note injected into LLM context. Default 8000.").addText(s=>s.setValue(String(this.plugin.settings.contextWindowTokenBudget)).onChange(async r=>{let a=parseInt(r);!isNaN(a)&&a>=1e3&&(this.plugin.settings.contextWindowTokenBudget=a,await this.plugin.saveSettings())})),e.createEl("h3",{text:"Vault"}),new S.Setting(e).setName("Methodology Root Folder").setDesc("Folder containing pentest methodology notes. Used for gap analysis and scheduled refresh.").addText(s=>s.setPlaceholder("Pentest").setValue(this.plugin.settings.methodologyRootFolder).onChange(async r=>{this.plugin.settings.methodologyRootFolder=r.trim(),await this.plugin.saveSettings()})),new S.Setting(e).setName("Methodology Tag").setDesc("Tag applied to methodology notes for scoped operations (without #).").addText(s=>s.setPlaceholder("methodology").setValue(this.plugin.settings.methodologyTag).onChange(async r=>{this.plugin.settings.methodologyTag=r.trim().replace(/^#/,""),await this.plugin.saveSettings()})),e.createEl("h3",{text:"Scheduled Refresh"}),new S.Setting(e).setName("Enable Scheduled Refresh").setDesc("Periodically re-enrich notes tagged with the methodology tag.").addToggle(s=>s.setValue(this.plugin.settings.enableScheduledRefresh).onChange(async r=>{this.plugin.settings.enableScheduledRefresh=r,await this.plugin.saveSettings()})),new S.Setting(e).setName("Refresh Interval (days)").setDesc("How often to check for stale notes.").addSlider(s=>s.setLimits(1,30,1).setValue(this.plugin.settings.refreshIntervalDays).setDynamicTooltip().onChange(async r=>{this.plugin.settings.refreshIntervalDays=r,await this.plugin.saveSettings()})),new S.Setting(e).setName("Debug Mode").setDesc("Log verbose output to the browser console.").addToggle(s=>s.setValue(this.plugin.settings.debugMode).onChange(async r=>{this.plugin.settings.debugMode=r,await this.plugin.saveSettings()}))}};var Pt=`You are a specialized offensive security research assistant embedded in Obsidian.
Your task is to help a penetration tester maintain accurate, up-to-date methodology notes.
You have access to search and crawl tools to gather verified information from the web, and vault tools to read and write notes.
Rules:
- Always verify information from at least 2 sources before writing to a note
- Prefer authoritative sources: GitHub repositories, HackTricks, ired.team, PayloadsAllTheThings, exploit-db, GTFOBins, LOLBAS
- Preserve all existing note content unless the user explicitly asks you to replace or remove it
- Write in consistent Markdown with proper heading hierarchy (no heading jumps)
- Use fenced code blocks with a language identifier for all commands and payloads
- Do not invent commands or payloads you have not verified from a crawled source
- When adding commands always include: tool name, full syntax, key flags with explanations, and what the output indicates
- Mark deprecated tools or superseded techniques with a clear note
- Never write content that targets live production systems without authorization context`;function kt(){let n=new Date().getFullYear(),t=n-1;return`You are a search query specialist for offensive security research.
Given a note topic and a user instruction, generate an array of 4 to 6 advanced DuckDuckGo search queries.
Requirements:
- Use site-specific operators where appropriate: site:github.com, site:book.hacktricks.xyz, site:exploit-db.com, site:ired.team
- Include exact technical terminology, tool names, and flag names used by security professionals
- Add recency hints: "${t}", "${n}", after:${t}-01-01
- Vary the queries: one broad overview, two specific technique queries, one tool-specific query, one source-specific query
- Include CVE identifiers and exploit-db references where applicable
- Reference key resources: PayloadsAllTheThings, GTFOBins, LOLBAS, ired.team, HackTricks
Return ONLY a valid JSON array of strings with no surrounding text, markdown, or explanation.
Example output: ["query one", "query two", "query three", "query four"]`}var Lt=`You are PenNote AI \u2014 an agentic penetration testing note assistant embedded in Obsidian.
You behave like a coding agent (e.g., GitHub Copilot Agent): you UNDERSTAND structure, REASON before acting, MAKE PRECISE CHANGES, and VERIFY facts before writing.
Each message includes a [Current date: YYYY-MM-DD] header. Use it when formulating search queries (prefer results from the current year), evaluating whether content is outdated, and deciding if tools, CVEs, or techniques need refreshing.
## Core Behaviour
**Think before you act.**
Before modifying a note:
1. Call read_note to get the latest content
2. Identify exactly which section or bullet needs to change
3. Use the most surgical tool possible:
- Single section replacement \u2192 patch_note_section
- Single bullet add/fix \u2192 upsert_note_bullet
- Append new content \u2192 write_to_note (mode: append)
- Only use replace when the user explicitly says "rewrite the whole note"
4. Verify technical facts with search_web + crawl_url BEFORE writing them
5. After writing, confirm exactly what changed
**Never guess. Never hallucinate.**
If the user asks you to add or verify a command, tool, CVE, or technique:
- Search for it first (site:github.com, site:book.hacktricks.xyz, site:ired.team, site:exploit-db.com)
- Crawl the best result to read the actual content
- Only then write verified, accurate content to the note
## Tool Selection Guide
| User request | Correct tool |
|---|---|
| "Add a section about X" | patch_note_section (creates it if missing) |
| "Update the X section" | read_note first \u2192 patch_note_section |
| "Add a bullet about Y to section Z" | upsert_note_bullet |
| "Fix/update bullet about Y" | upsert_note_bullet with match_prefix |
| "Add X to the end of the note" | write_to_note (append) |
| "Verify if [command] is still current" | search_web \u2192 crawl_url \u2192 reply with findings |
| "Check if my notes on X are accurate" | read_note \u2192 search_web \u2192 compare \u2192 report |
| "Create a new note" | create_note |
| "What notes do I have about X" | list_vault_notes |
## Active Note
The message context always includes [Active note: path] and content. When calling any note tool (read_note, patch_note_section, upsert_note_bullet, write_to_note), use that exact path if the user has not specified a different one. Never invent a path.
## File Creation Policy
NEVER call create_note on your own initiative. Only call create_note when the user has explicitly asked to "create a new note", "make a new note", or similar. If you think a new note would be helpful but the user hasn't asked, tell them and ask for confirmation instead.
## Writing Standards
- All commands in fenced code blocks with language: \`\`\`bash, \`\`\`python, etc.
- Include flag explanations inline: \`nmap -sV\` \u2014 service version detection
- Mark deprecated items: ~~tool name~~ (deprecated \u2014 use X instead)
- Never change existing content unless explicitly asked or a fact is demonstrably wrong
- Preserve all comments, checkboxes, and formatting the user has written
## Verification Mode
When user says "verify", "check", "is this current", or "validate":
1. Read the relevant section from the note
2. Search for current information from authoritative sources
3. Compare what the note says vs what sources say
4. Report discrepancies clearly: "Your note says X, but the current syntax is Y"
5. Ask the user before making any changes based on verification findings
## Response Format
- For plain questions: answer directly and concisely
- After modifying a note: briefly state EXACTLY what you changed ("Updated the Port Scanning section \u2014 replaced the nmap flags with the current syntax from nmap.org")
- For verification: present a structured comparison
- Never dump the entire note content back to the user`,Mt=`You are a task planner for an offensive security research agent.
Given a user instruction and current note content, produce a concise execution plan.
Return a JSON object with this exact shape:
{
"mode": "enrich|gap-analysis|add-command|search-update|checklist",
"steps": ["step 1 description", "step 2 description"],
"estimatedSearches": 3
}
Keep each step to a maximum of 8 words. Return only the JSON object with no surrounding text.`;var Rt=(n,t,e)=>`Current date: ${new Date().toISOString().split("T")[0]}
You are enriching a penetration testing methodology note located at: ${e}
Current note content:
\`\`\`markdown
${n}
\`\`\`
User instruction: ${t}
Use the available tools to search the web for recent, authoritative information, crawl relevant pages, and then write enriched content back to the note. Always verify across multiple sources before writing. Prefer sources and techniques published in ${new Date().getFullYear()} \u2014 do not add outdated or deprecated content.`;var me=class{constructor(t){this.client=t}async build(t,e){let i=[{role:"system",content:kt()},{role:"user",content:`Note topic: ${t}
User instruction: ${e}
Generate the search queries now.`}],s=await this.client.chat(i,"mistral-small-latest");return this.parseQueries(s)}async buildFromContent(t,e){let i=this.extractTopic(t);return this.build(i,e)}parseQueries(t){let e=t.trim(),i=e.indexOf("["),s=e.lastIndexOf("]");if(i===-1||s===-1)return this.fallbackExtract(e);try{let r=JSON.parse(e.slice(i,s+1));if(Array.isArray(r))return r.filter(a=>typeof a=="string"&&a.trim().length>0)}catch(r){return this.fallbackExtract(e)}return this.fallbackExtract(e)}fallbackExtract(t){return t.split(`
`).map(e=>e.replace(/^[\d\-\.\*\s"']+/,"").replace(/["',]+$/,"").trim()).filter(e=>e.length>5)}extractTopic(t){let e=t.split(`
`);for(let s of e){let r=s.match(/^#{1,3}\s+(.+)/);if(r)return r[1].trim()}let i=t.split(/\s+/).slice(0,20).join(" ");return i.length>0?i:"penetration testing methodology"}};var Ot=require("obsidian");var ne=[{ua:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",profile:{platform:"Win32",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1920,height:1080}}},{ua:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",profile:{platform:"Win32",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1440,height:900}}},{ua:"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",profile:{platform:"MacIntel",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1512,height:982}}},{ua:"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15",profile:{platform:"MacIntel",vendor:"Apple Computer, Inc.",languages:["en-US","en"],viewport:{width:1512,height:982}}},{ua:"Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0",profile:{platform:"Linux x86_64",vendor:"",languages:["en-US","en"],viewport:{width:1920,height:1080}}},{ua:"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",profile:{platform:"Linux x86_64",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1920,height:1080}}},{ua:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",profile:{platform:"Win32",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1920,height:1080}}},{ua:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",profile:{platform:"Win32",vendor:"",languages:["en-US","en"],viewport:{width:1680,height:1050}}},{ua:"Mozilla/5.0 (Macintosh; Intel Mac OS X 14.4; rv:125.0) Gecko/20100101 Firefox/125.0",profile:{platform:"MacIntel",vendor:"",languages:["en-US","en"],viewport:{width:1280,height:800}}},{ua:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",profile:{platform:"Win32",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1366,height:768}}}];function It(){return ne[Math.floor(Math.random()*ne.length)].ua}function Dt(n){let t=ne.find(e=>e.ua===n);return t?t.profile:{platform:"Win32",vendor:"Google Inc.",languages:["en-US","en"],viewport:{width:1920,height:1080}}}function Ve(){return ne[Math.floor(Math.random()*ne.length)]}function ie(n){return{"User-Agent":n,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8","Accept-Language":"en-US,en;q=0.9","Accept-Encoding":"gzip, deflate, br",Connection:"keep-alive","Upgrade-Insecure-Requests":"1","Sec-Fetch-Dest":"document","Sec-Fetch-Mode":"navigate","Sec-Fetch-Site":"none","Sec-Fetch-User":"?1",DNT:"1",Referer:"https://www.google.com/"}}var zn="https://html.duckduckgo.com/html/",ye=class{constructor(){this.cache=new Map;this.cacheTtlMs=5*60*1e3}async search(t,e=5){let i=`${t}::${e}`,s=this.cache.get(i);if(s&&Date.now()-s.timestamp<this.cacheTtlMs)return s.results;let r=It(),a=ie(r),o=new URLSearchParams({q:t,b:"",kl:""}),l=await(0,Ot.requestUrl)({url:zn,method:"POST",headers:{...a,"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),throw:!1});if(l.status<200||l.status>=300)throw new Error(`DuckDuckGo search failed: HTTP ${l.status}`);let c=l.text,u=this.parseResults(c,e);return this.cache.set(i,{results:u,timestamp:Date.now()}),u}clearCache(){this.cache.clear()}parseResults(t,e){var a,o,l,c,u;let i=new DOMParser().parseFromString(t,"text/html"),s=[],r=Array.from(i.querySelectorAll("div.result.results_links, div.result.results_links_deep, div.result.web-result"));for(let d of r){if(s.length>=e)break;let h=d.querySelector("h2.result__title > a.result__a");if(!h)continue;let p=(a=h.getAttribute("href"))!=null?a:"",g=this.extractUddgUrl(p);if(!g)continue;let y=(l=(o=h.textContent)==null?void 0:o.trim())!=null?l:"";if(!y)continue;let v=d.querySelector("a.result__snippet"),w=(u=(c=v==null?void 0:v.textContent)==null?void 0:c.trim())!=null?u:"";s.push({title:y,url:g,snippet:w})}return s.length>0?s:this.regexFallbackParse(t,e)}extractUddgUrl(t){if(!t)return"";if(t.startsWith("http://")||t.startsWith("https://"))try{let i=new URL(t).searchParams.get("uddg");return i?decodeURIComponent(i):t}catch(e){return t}if(t.startsWith("//"))try{let i=new URL("https:"+t).searchParams.get("uddg");if(i)return decodeURIComponent(i)}catch(e){return""}if(t.startsWith("/l/"))try{let i=new URL("https://duckduckgo.com"+t).searchParams.get("uddg");if(i)return decodeURIComponent(i)}catch(e){return""}return""}regexFallbackParse(t,e){var u;let i=[],s=/<a[^>]+class="[^"]*result__a[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g,r=/<a[^>]+class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/a>/g,a=[],o;for(;(o=r.exec(t))!==null;)a.push(o[1].replace(/<[^>]+>/g,"").trim());let l,c=0;for(;(l=s.exec(t))!==null&&i.length<e;){let d=l[1],h=l[2],p=this.extractUddgUrl(d);if(!p)continue;let g=h.replace(/<[^>]+>/g,"").trim();g&&(i.push({title:g,url:p,snippet:(u=a[c])!=null?u:""}),c++)}return i}};var qt=require("obsidian");function Xe(n,t){var r,a,o,l,c,u,d;let e="",i="",s=[];try{let h=new DOMParser().parseFromString(n,"text/html");e=(o=(a=(r=h.querySelector("title"))==null?void 0:r.textContent)==null?void 0:a.trim())!=null?o:"";let p=h.querySelectorAll("pre, code");for(let y of Array.from(p).slice(0,20)){let v=(c=(l=y.textContent)==null?void 0:l.trim())!=null?c:"";v.length>10&&s.push(v)}let g=Zn();if(g){let v=new g(h).parse();v&&(e=(u=v.title)!=null?u:e,i=(d=v.textContent)!=null?d:"")}else i=ei(h)}catch(h){i=ti(n).slice(0,12e3)}return i=ni(i).slice(0,12e3),{url:t,title:e,content:i,codeBlocks:s,timestamp:Date.now()}}function Zn(){var n,t,e;try{let i=Ut();return(e=(t=i.Readability)!=null?t:(n=i.default)==null?void 0:n.Readability)!=null?e:null}catch(i){return null}}function ei(n){var i,s,r,a;let t=["nav","header","footer","aside","script","style","noscript",".nav",".header",".footer",".sidebar",".advertisement",".cookie-banner"];for(let o of t)n.querySelectorAll(o).forEach(l=>l.remove());let e=(i=n.querySelector("main, article, .content, .post-content, .entry-content, #content"))!=null?i:n.body;return(a=(r=e==null?void 0:e.textContent)!=null?r:(s=n.body)==null?void 0:s.textContent)!=null?a:""}function ti(n){return n.replace(/<[^>]+>/g," ").replace(/&[a-z]+;/gi," ")}function ni(n){return n.replace(/\r\n/g,`
`).replace(/[\t ]+/g," ").replace(/\n{3,}/g,`
`).trim()}var ii=`
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
window.chrome = { runtime: {} };
`,ve=class{constructor(t){this.domainMap=new Map;this.playwrightEnabled=t.playwrightEnabled,this.timeoutMs=t.crawlTimeoutMs}updateSettings(t){this.playwrightEnabled=t.playwrightEnabled,this.timeoutMs=t.crawlTimeoutMs}async crawl(t){if(await this.respectDomainCooldown(t),this.playwrightEnabled)try{return await this.crawlWithPlaywright(t)}catch(e){return await this.crawlWithFetch(t)}return this.crawlWithFetch(t)}async crawlWithPlaywright(t){let e=this.loadPlaywright();if(!e)return this.crawlWithFetch(t);let i=Ve(),s=Dt(i.ua),r=await e.chromium.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-blink-features=AutomationControlled"]});try{let a=await r.newContext({userAgent:i.ua,viewport:s.viewport,locale:"en-US",timezoneId:"America/New_York",extraHTTPHeaders:ie(i.ua)}),o=await a.newPage();await o.addInitScript(ii),await o.addInitScript(`Object.defineProperty(navigator, 'platform', { get: () => '${s.platform}' });
Object.defineProperty(navigator, 'vendor', { get: () => '${s.vendor}' });
Object.defineProperty(navigator, 'languages', { get: () => ${JSON.stringify(s.languages)} });`),await o.goto(t,{waitUntil:"networkidle",timeout:this.timeoutMs});let l=800+Math.floor(Math.random()*1700);await o.waitForTimeout(l);let c=await o.content();return await a.close(),Xe(c,t)}finally{await r.close()}}async crawlWithFetch(t){let e=Ve(),i=ie(e.ua),s=await(0,qt.requestUrl)({url:t,method:"GET",headers:i,throw:!1});if(s.status<200||s.status>=300)throw new Error(`HTTP ${s.status}`);return Xe(s.text,t)}async respectDomainCooldown(t){try{let e=new URL(t).hostname,i=Date.now(),s=this.domainMap.get(e);if(s){let r=i-s.lastCrawlTime;r<5e3&&await new Promise(a=>setTimeout(a,5e3-r))}this.domainMap.set(e,{lastCrawlTime:Date.now()})}catch(e){}}loadPlaywright(){try{return require("playwright-core")}catch(t){return null}}};var we=class{constructor(t,e){this.data={enrichmentHistory:{},crawlCache:{}};t&&(this.data=t),this.saveCallback=e}async addEnrichmentRecord(t){let e=t.noteId;this.data.enrichmentHistory[e]||(this.data.enrichmentHistory[e]=[]),this.data.enrichmentHistory[e].unshift(t),this.data.enrichmentHistory[e].length>10&&(this.data.enrichmentHistory[e]=this.data.enrichmentHistory[e].slice(0,10)),await this.save()}getEnrichmentHistory(t){var e;return(e=this.data.enrichmentHistory[t])!=null?e:[]}getPreviousQueries(t){return this.getEnrichmentHistory(t).flatMap(e=>e.queriesUsed)}getPreviousUrls(t){return this.getEnrichmentHistory(t).flatMap(e=>e.urlsCrawled)}async setCrawlCache(t,e){this.data.crawlCache[t]={content:e,timestamp:Date.now()},await this.save()}getCrawlCache(t){let e=this.data.crawlCache[t];return e?Date.now()-e.timestamp>864e5?(delete this.data.crawlCache[t],null):e.content:null}async pruneExpiredCache(){let t=Date.now(),e=!1;for(let i of Object.keys(this.data.crawlCache))t-this.data.crawlCache[i].timestamp>864e5&&(delete this.data.crawlCache[i],e=!0);e&&await this.save()}getData(){return this.data}async save(){await this.saveCallback(this.data)}};var be=class{constructor(t){this.index=new Map;this.app=t}async buildIndex(){let t=this.app.vault.getMarkdownFiles();await Promise.all(t.map(e=>this.indexFile(e)))}async indexFile(t){var e,i,s;try{let r=await this.app.vault.read(t),a=this.app.metadataCache.getFileCache(t),o=[];if(a!=null&&a.tags&&o.push(...a.tags.map(u=>u.tag.replace(/^#/,""))),(e=a==null?void 0:a.frontmatter)!=null&&e.tags){let u=a.frontmatter.tags;Array.isArray(u)?o.push(...u.map(d=>String(d).replace(/^#/,""))):typeof u=="string"&&o.push(u.replace(/^#/,""))}let l=[];a!=null&&a.headings&&l.push(...a.headings.map(u=>u.heading));let c=[];if(a!=null&&a.links)for(let u of a.links){let d=this.app.metadataCache.getFirstLinkpathDest(u.link,t.path);d&&c.push(d.path)}this.index.set(t.path,{path:t.path,title:(s=(i=a==null?void 0:a.frontmatter)==null?void 0:i.title)!=null?s:t.basename,tags:[...new Set(o)],headings:l,linkedPaths:c,lastModified:t.stat.mtime})}catch(r){}}removeFile(t){this.index.delete(t)}getEntry(t){return this.index.get(t)}getByTag(t){let e=t.replace(/^#/,"");return Array.from(this.index.values()).filter(i=>i.tags.includes(e))}getByFolder(t){let e=t.endsWith("/")?t:t+"/";return Array.from(this.index.values()).filter(i=>i.path.startsWith(e)||i.path.startsWith(t))}getSummary(t){let e=this.index.get(t);return e?[`Title: ${e.title}`,`Tags: ${e.tags.join(", ")||"none"}`,`Sections: ${e.headings.join(", ")||"none"}`].join(`
`):""}all(){return Array.from(this.index.values())}};var Ye=[{type:"function",function:{name:"search_web",description:"Search DuckDuckGo for penetration testing information. Use advanced operators for precision.",parameters:{type:"object",properties:{query:{type:"string",description:`Advanced search query. Use operators: site:, intitle:, after:, "exact phrase". Add site:github.com, site:book.hacktricks.xyz, site:ired.team, site:exploit-db.com as appropriate. For recency use after:${new Date().getFullYear()-1}-01-01 to filter results from ${new Date().getFullYear()-1} onward.`},num_results:{type:"number",description:"Number of results to return. Default 5, maximum 10."}},required:["query"]}}},{type:"function",function:{name:"crawl_url",description:"Visit a URL and extract its full text content. Use this to verify facts, get exact command syntax, and read source material before writing to a note.",parameters:{type:"object",properties:{url:{type:"string",description:"Full URL starting with https://"}},required:["url"]}}},{type:"function",function:{name:"read_note",description:"Read the full current content of a note. Always call this before patching it so you have the latest version.",parameters:{type:"object",properties:{path:{type:"string",description:"Vault-relative path, e.g. Pentest/Recon.md"}},required:["path"]}}},{type:"function",function:{name:"patch_note_section",description:"Surgically replace the body of a specific section (identified by its heading) in a note. The heading line itself is preserved; only the content below it is replaced. If the heading does not exist, a new section is appended. Use this for targeted edits \u2014 NOT for full rewrites. Always call read_note first.",parameters:{type:"object",properties:{path:{type:"string",description:"Vault-relative path to the note"},heading:{type:"string",description:"Exact heading text WITHOUT the # symbols, e.g. 'Port Scanning' or 'Privilege Escalation'"},new_body:{type:"string",description:"The new Markdown content body to place under that heading. Full well-formed Markdown."},heading_level:{type:"number",description:"Heading level 1-6 used ONLY when creating a new section. Default 2."}},required:["path","heading","new_body"]}}},{type:"function",function:{name:"upsert_note_bullet",description:"Add a new bullet point to a section, or replace an existing bullet that matches a provided keyword. Use this for precise single-point additions or corrections within a list \u2014 avoids touching the rest of the section. Always call read_note first.",parameters:{type:"object",properties:{path:{type:"string",description:"Vault-relative path to the note"},heading:{type:"string",description:"Exact heading text WITHOUT # symbols identifying where to add the bullet"},bullet_text:{type:"string",description:"Full text of the bullet point WITHOUT the leading dash, e.g. '`nmap -sV -p 443` \u2014 service version detection on HTTPS'"},match_prefix:{type:"string",description:"Optional: partial text of an existing bullet to find and replace. If omitted, new bullet is appended to the section."}},required:["path","heading","bullet_text"]}}},{type:"function",function:{name:"write_to_note",description:"Write Markdown content to a note. Prefer patch_note_section or upsert_note_bullet for surgical edits. Use this only for append (add to end) or full replace when the entire note needs rewriting.",parameters:{type:"object",properties:{path:{type:"string",description:"Vault-relative path to the note file"},content:{type:"string",description:"Markdown content to write"},mode:{type:"string",enum:["append","prepend","replace"],description:"append: add to end. prepend: add to start. replace: overwrite entire note (use sparingly)."}},required:["path","content","mode"]}}},{type:"function",function:{name:"create_note",description:"Create a brand new Markdown note at the specified path with initial content.",parameters:{type:"object",properties:{path:{type:"string",description:"Full vault-relative path including .md extension"},content:{type:"string",description:"Initial Markdown content"}},required:["path","content"]}}},{type:"function",function:{name:"list_vault_notes",description:"List notes matching an optional tag or folder prefix.",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter by tag name without the # symbol"},folder:{type:"string",description:"Filter by folder path prefix, e.g. Pentest"}},required:[]}}}];function Gt(n){return n.length===0?"":`## References
`+n.map(e=>`- [${e.title}](${e.url}) \u2014 accessed ${e.date}`).join(`
`)+`
`}function Je(n,t,e){let i=/^---\n([\s\S]*?)\n---/,s=new RegExp(`^${t}:.*$`,"m");return i.test(n)?s.test(n)?n.replace(s,`${t}: ${e}`):n.replace(i,(r,a)=>`---
${a}
${t}: ${e}
---`):`---
${t}: ${e}
---
${n}`}function Qe(n){let t=n.split(`
`),e=[];for(let i=0;i<t.length;i++){let s=t[i].match(/^(#{1,6})\s(.+)/);if(!s)continue;let r=s[1].length,a=s[2].trim(),o=t.length;for(let l=i+1;l<t.length;l++){let c=t[l].match(/^(#{1,6})\s/);if(c&&c[1].length<=r){o=l;break}}e.push({heading:a,level:r,startLine:i,endLine:o,content:t.slice(i+1,o).join(`
`).trim()})}return e}function jt(n,t,e,i=2){let s=n.split(`
`),a=Qe(n).find(d=>d.heading.toLowerCase().trim()===t.toLowerCase().trim());if(!a){let d="#".repeat(i);return n.trimEnd()+`
${d} ${t}
${e.trim()}
`}let o=s[a.startLine],l=s.slice(0,a.startLine),c=s.slice(a.endLine),u=[o,"",e.trim(),""];return[...l,...u,...c].join(`
`).replace(/\n{3,}/g,`
`)}function Vt(n,t,e,i){var c,u;let r=Qe(n).find(d=>d.heading.toLowerCase().trim()===t.toLowerCase().trim());if(!r)return n.trimEnd()+`
## ${t}
- ${e.trim()}
`;let a=n.split(`
`),o=a.slice(r.startLine+1,r.endLine);if(i){let d=o.findIndex(h=>h.match(/^\s*-\s+/)&&h.toLowerCase().includes(i.toLowerCase()));if(d!==-1){let h=(u=(c=o[d].match(/^(\s*)/))==null?void 0:c[1])!=null?u:"";return o[d]=`${h}- ${e.trim()}`,[...a.slice(0,r.startLine+1),...o,...a.slice(r.endLine)].join(`
`)}}let l=o.length;return o.splice(l,0,`- ${e.trim()}`),[...a.slice(0,r.startLine+1),...o,...a.slice(r.endLine)].join(`
`)}function Kt(n){let t=Qe(n);return t.length===0?"(no headings)":t.map(e=>`${" ".repeat(e.level-1)}- ${"#".repeat(e.level)} ${e.heading} [line ${e.startLine+1}]`).join(`
`)}var _e=class{constructor(){this.turns=[];this.totalPromptTokens=0;this.totalCompletionTokens=0}addMessage(t){this.turns.push(t),this.turns.length>20*2&&(this.turns=this.turns.slice(-20*2))}getHistory(){return[...this.turns]}recordUsage(t,e){this.totalPromptTokens+=t,this.totalCompletionTokens+=e}getTotalTokens(){return{prompt:this.totalPromptTokens,completion:this.totalCompletionTokens,total:this.totalPromptTokens+this.totalCompletionTokens}}clear(){this.turns=[],this.totalPromptTokens=0,this.totalCompletionTokens=0}size(){return this.turns.length}isEmpty(){return this.turns.length===0}};var re=class{constructor(t,e,i){this.client=t;this.toolRunner=e;this.maxIterations=i;this.contextInjected=!1;this.sessionMemory=new _e}async run(t,e,i,s){var g,y,v,w,E,A,m;this.sessionMemory.clear();let r=[],a=[],o=[],l=(_,f)=>{let b={type:_,message:f,timestamp:Date.now()};r.push(b),s==null||s(b)},c={role:"system",content:Pt},u={role:"user",content:Rt(e,t,i)};this.sessionMemory.addMessage(c),this.sessionMemory.addMessage(u);let d=0,h="",p={promptTokens:0,completionTokens:0,totalTokens:0};for(l("think","Agent started. Planning approach...");d<this.maxIterations;){d++;let _=this.sessionMemory.getHistory(),f=await this.client.chatWithTools(_,Ye);f.usage&&(p.promptTokens+=f.usage.prompt_tokens,p.completionTokens+=f.usage.completion_tokens,p.totalTokens+=f.usage.total_tokens,this.sessionMemory.recordUsage(f.usage.prompt_tokens,f.usage.completion_tokens));let b=f.choices[0];if(!b)break;let x=b.message;if(this.sessionMemory.addMessage({role:"assistant",content:(g=x.content)!=null?g:null,tool_calls:(y=x.tool_calls)!=null&&y.length?x.tool_calls:void 0}),b.finish_reason==="stop"||!((v=x.tool_calls)!=null&&v.length)){h=(w=x.content)!=null?w:"",l("think","Agent completed reasoning.");break}for(let T of(E=x.tool_calls)!=null?E:[])await this.executeToolCall(T,r,a,o,l)}if(d>=this.maxIterations&&!h){l("think","Iteration limit reached, generating final response...");try{let _=await this.client.chatWithTools(this.sessionMemory.getHistory(),[]);_.usage&&(p.promptTokens+=_.usage.prompt_tokens,p.completionTokens+=_.usage.completion_tokens,p.totalTokens+=_.usage.total_tokens),h=(m=(A=_.choices[0])==null?void 0:A.message.content)!=null?m:""}catch(_){h=""}h||(l("error",`Max iterations (${this.maxIterations}) reached without a response.`),h="The agent exhausted its iteration budget. Try rephrasing or increasing Max Agent Iterations in settings.")}return{finalContent:h,logs:r,tokenUsage:p,queriesUsed:a,urlsCrawled:o}}async executeToolCall(t,e,i,s,r){var c,u,d;let a=t.function.name,o={};try{o=JSON.parse(t.function.arguments)}catch(h){r("error",`Failed to parse arguments for tool: ${a}`)}if(a==="search_web"){let h=String((c=o.query)!=null?c:"");r("search",`Searching: ${h}`),h&&i.push(h)}else if(a==="crawl_url"){let h=String((u=o.url)!=null?u:"");r("crawl",`Crawling: ${h}`),h&&s.push(h)}else a==="write_to_note"||a==="create_note"?r("write",`Writing to note: ${String((d=o.path)!=null?d:"")}`):r("think",`Executing: ${a}`);let l=await this.toolRunner.execute(a,o);this.sessionMemory.addMessage({role:"tool",content:l.data,tool_call_id:t.id}),l.success||r("error",`Tool ${a} failed: ${l.data}`)}resetSession(){this.sessionMemory.clear()}async chatTurn(t,e,i,s){var y,v,w,E,A,m,_;let r=[],a=[],o=[],l=(f,b)=>{let x={type:f,message:b,timestamp:Date.now()};r.push(x),s==null||s(x)};this.sessionMemory.isEmpty()&&this.sessionMemory.addMessage({role:"system",content:Lt});let u=new Date().toISOString().split("T")[0],d;if(!this.contextInjected&&e&&i){let f=Kt(e),b=e.length>3e3?e.slice(0,3e3)+`
... (truncated \u2014 use read_note for full content)`:e;d=`[Current date: ${u}]
[Active note: ${i}]
[Section outline:
${f}
]
[Note content (first 3000 chars):
\`\`\`markdown
${b}
\`\`\`]
User: ${t}`,this.contextInjected=!0}else i?d=`[Current date: ${u}]
[Active note: ${i}]
User: ${t}`:d=`[Current date: ${u}]
User: ${t}`;this.sessionMemory.addMessage({role:"user",content:d});let h=0,p="",g={promptTokens:0,completionTokens:0,totalTokens:0};for(;h<this.maxIterations;){h++;let f=this.sessionMemory.getHistory(),b=await this.client.chatWithTools(f,Ye);b.usage&&(g.promptTokens+=b.usage.prompt_tokens,g.completionTokens+=b.usage.completion_tokens,g.totalTokens+=b.usage.total_tokens,this.sessionMemory.recordUsage(b.usage.prompt_tokens,b.usage.completion_tokens));let x=b.choices[0];if(!x)break;let T=x.message;if(this.sessionMemory.addMessage({role:"assistant",content:(y=T.content)!=null?y:null,tool_calls:(v=T.tool_calls)!=null&&v.length?T.tool_calls:void 0}),x.finish_reason==="stop"||!((w=T.tool_calls)!=null&&w.length)){p=(E=T.content)!=null?E:"";break}for(let M of(A=T.tool_calls)!=null?A:[])await this.executeToolCall(M,r,a,o,l)}if(h>=this.maxIterations&&!p){try{let f=await this.client.chatWithTools(this.sessionMemory.getHistory(),[]);f.usage&&(g.promptTokens+=f.usage.prompt_tokens,g.completionTokens+=f.usage.completion_tokens,g.totalTokens+=f.usage.total_tokens),p=(_=(m=f.choices[0])==null?void 0:m.message.content)!=null?_:""}catch(f){p=""}p||(p="The agent exhausted its iteration budget. Try rephrasing or increasing Max Agent Iterations in settings.")}return{finalContent:p,logs:r,tokenUsage:g,queriesUsed:a,urlsCrawled:o}}resetChat(){this.sessionMemory.clear(),this.contextInjected=!1}};var zt=require("obsidian");var se=class{constructor(t,e,i,s){this.app=t;this.searcher=e;this.crawler=i;this.searchLimit=s;this.activeFilePath="";this.allowCreateNote=!1}async execute(t,e){var i,s,r,a,o,l,c,u,d,h,p,g,y,v,w,E;switch(t){case"search_web":return this.searchWeb(String((i=e.query)!=null?i:""),Number((s=e.num_results)!=null?s:this.searchLimit));case"crawl_url":return this.crawlUrl(String((r=e.url)!=null?r:""));case"read_note":return this.readNote(String((a=e.path)!=null?a:""));case"patch_note_section":return this.patchNoteSection(String((o=e.path)!=null?o:""),String((l=e.heading)!=null?l:""),String((c=e.new_body)!=null?c:""),Number((u=e.heading_level)!=null?u:2));case"upsert_note_bullet":return this.upsertNoteBullet(String((d=e.path)!=null?d:""),String((h=e.heading)!=null?h:""),String((p=e.bullet_text)!=null?p:""),e.match_prefix!==void 0?String(e.match_prefix):void 0);case"write_to_note":return this.writeToNote(String((g=e.path)!=null?g:""),String((y=e.content)!=null?y:""),String((v=e.mode)!=null?v:"append"));case"create_note":return this.allowCreateNote?this.createNote(String((w=e.path)!=null?w:""),String((E=e.content)!=null?E:"")):{success:!1,data:"create_note is not permitted without explicit user approval. Tell the user you need their permission to create a new note, and ask them to confirm."};case"list_vault_notes":return this.listVaultNotes(e.tag!==void 0?String(e.tag):void 0,e.folder!==void 0?String(e.folder):void 0);default:return{success:!1,data:`Unknown tool: ${t}`}}}async searchWeb(t,e){if(!t)return{success:!1,data:"No query provided"};try{let i=await this.searcher.search(t,Math.min(e,10));return i.length===0?{success:!0,data:"No results found for that query."}:{success:!0,data:i.map((r,a)=>`${a+1}. [${r.title}](${r.url})
${r.snippet}`).join(`
`)}}catch(i){return{success:!1,data:`Search error: ${String(i)}`}}}async crawlUrl(t){if(!t||!t.startsWith("http"))return{success:!1,data:"Invalid URL. Must start with http."};try{let e=await this.crawler.crawl(t),i=`Title: ${e.title}
Content:
${e.content}`;if(e.codeBlocks.length>0){let s=e.codeBlocks.slice(0,5).map(r=>`\`\`\`
${r}
\`\`\``).join(`
`);i+=`
Code Blocks:
${s}`}return{success:!0,data:i.slice(0,8e3)}}catch(e){return{success:!1,data:`Crawl error: ${String(e)}`}}}resolveFile(t){var r;let e=t.trim()||this.activeFilePath;if(!e)return null;let i=e.endsWith(".md")?e:e+".md",s=(r=this.app.vault.getAbstractFileByPath(i))!=null?r:this.app.vault.getAbstractFileByPath(e);return s instanceof zt.TFile?s:null}async readNote(t){let e=this.resolveFile(t);return e?{success:!0,data:await this.app.vault.read(e)}:{success:!1,data:`Note not found: ${t}`}}async patchNoteSection(t,e,i,s){if(!e.trim())return{success:!1,data:"heading is required"};let r=t.endsWith(".md")?t:t+".md",a=this.resolveFile(r);if(!a)return{success:!1,data:`Note not found: ${r}`};try{let o=await this.app.vault.read(a),l=jt(o,e,i,Math.min(Math.max(s||2,1),6));return await this.app.vault.modify(a,l),{success:!0,data:`Patched section "${e}" in ${r}`}}catch(o){return{success:!1,data:`Patch error: ${String(o)}`}}}async upsertNoteBullet(t,e,i,s){if(!e.trim())return{success:!1,data:"heading is required"};let r=t.endsWith(".md")?t:t+".md",a=this.resolveFile(r);if(!a)return{success:!1,data:`Note not found: ${r}`};try{let o=await this.app.vault.read(a),l=Vt(o,e,i,s);return await this.app.vault.modify(a,l),{success:!0,data:`${s?`Updated bullet matching "${s}"`:"Added bullet"} in section "${e}" of ${r}`}}catch(o){return{success:!1,data:`Upsert error: ${String(o)}`}}}async writeToNote(t,e,i){let s=this.resolveFile(t);if(!s)return{success:!1,data:`Note not found: ${t}. Use create_note to create it first.`};try{let r=await this.app.vault.read(s),a;return i==="append"?a=r.trimEnd()+`
`+e.trim()+`
`:i==="prepend"?a=e.trim()+`
`+r.trimStart():a=e,await this.app.vault.modify(s,a),{success:!0,data:`Successfully wrote to ${s.path} (mode: ${i})`}}catch(r){return{success:!1,data:`Write error: ${String(r)}`}}}async createNote(t,e){let i=t.endsWith(".md")?t:t+".md";if(this.app.vault.getAbstractFileByPath(i))return{success:!1,data:`Note already exists: ${i}. Use write_to_note to modify it.`};try{let r=i.split("/").slice(0,-1).join("/");return r&&(this.app.vault.getAbstractFileByPath(r)||await this.app.vault.createFolder(r)),await this.app.vault.create(i,e),{success:!0,data:`Created note: ${i}`}}catch(r){return{success:!1,data:`Create error: ${String(r)}`}}}listVaultNotes(t,e){let s=this.app.vault.getMarkdownFiles();if(e){let a=e.endsWith("/")?e:e+"/";s=s.filter(o=>o.path.startsWith(a)||o.path.startsWith(e))}if(t){let a=t.replace(/^#/,"");s=s.filter(o=>{var h,p,g,y;let l=this.app.metadataCache.getFileCache(o),c=(p=(h=l==null?void 0:l.tags)==null?void 0:h.map(v=>v.tag.replace(/^#/,"")))!=null?p:[],u=(y=(g=l==null?void 0:l.frontmatter)==null?void 0:g.tags)!=null?y:[];return[...c,...Array.isArray(u)?u:[u]].map(v=>String(v).replace(/^#/,"")).includes(a)})}if(s.length===0)return{success:!0,data:"No notes found matching the criteria."};let r=s.map(a=>`- ${a.path}`).join(`
`);return{success:!0,data:`Found ${s.length} notes:
${r}`}}};var Ee=class{constructor(t){this.client=t}async plan(t,e){let i=[{role:"system",content:Mt},{role:"user",content:`User instruction: ${t}
Note content (first 500 chars):
${e.slice(0,500)}`}],s=await this.client.chat(i,"mistral-small-latest");return this.parsePlan(s,t)}parsePlan(t,e){let i=t.indexOf("{"),s=t.lastIndexOf("}");if(i!==-1&&s!==-1)try{let r=JSON.parse(t.slice(i,s+1));if(this.isValidPlan(r))return r}catch(r){}return this.defaultPlan(e)}isValidPlan(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.mode=="string"&&Array.isArray(e.steps)&&typeof e.estimatedSearches=="number"}defaultPlan(t){let e=t.toLowerCase(),i="enrich";return e.includes("gap")||e.includes("missing")?i="gap-analysis":e.includes("checklist")||e.includes("checkbox")?i="checklist":e.includes("command")||e.includes("tool")||e.includes("syntax")?i="add-command":(e.includes("update")||e.includes("refresh"))&&(i="search-update"),{mode:i,steps:["Search for relevant information","Crawl top results","Write enriched content"],estimatedSearches:3}}};var Re=null;function fr(){if(!Re)try{Re=On()}catch(n){Re=null}return Re}function yt(n,t){let e=fr();return e?e.diffLines(n,t).map(s=>({type:s.added?"added":s.removed?"removed":"unchanged",value:s.value})):mr(n,t)}function vt(n,t){return t.filter(e=>e.type!=="removed").map(e=>e.value).join("")}function wt(n){let t=0,e=0;for(let i of n){let s=i.value.split(`
`).filter(r=>r.trim().length>0).length;i.type==="added"&&(t+=s),i.type==="removed"&&(e+=s)}return{added:t,removed:e}}function Hn(n,t=20){let{added:e,removed:i}=wt(n);return e+i<=t}function mr(n,t){let e=n.split(`
`),i=t.split(`
`),s=new Set(e),r=new Set(i),a=[];for(let o of e)r.has(o)?a.push({type:"unchanged",value:o+`
`}):a.push({type:"removed",value:o+`
`});for(let o of i)s.has(o)||a.push({type:"added",value:o+`
`});return a}var bt=[{id:"recon",name:"Reconnaissance",tags:["recon","osint","enumeration"],sections:["Passive Reconnaissance","Active Reconnaissance","DNS Enumeration","Subdomain Discovery","Port Scanning","Service Version Detection","Web Technology Fingerprinting","OSINT"],defaultChecklist:["Perform passive recon using OSINT (Shodan, Censys, SecurityTrails)","Enumerate subdomains with amass and subfinder","Run full port scan with nmap -p- -sV -sC","Identify web technologies with whatweb or httpx","Check DNS records: A, MX, TXT, SPF, DMARC, DKIM","Search for leaked credentials on breach aggregators","Check GitHub for exposed secrets or internal references","Enumerate virtual hosts"]},{id:"web-application",name:"Web Application Testing",tags:["web","webapp","http"],sections:["Authentication Testing","Authorization Testing","Input Validation","SQL Injection","Cross-Site Scripting (XSS)","Server-Side Request Forgery (SSRF)","XML External Entity (XXE)","Insecure Direct Object Reference (IDOR)","Business Logic Testing","File Upload Testing","API Testing","Session Management"],defaultChecklist:["Map all endpoints with gobuster or ffuf","Test authentication flows for bypass vulnerabilities","Check all input fields for SQL injection with sqlmap","Test for reflected, stored, and DOM XSS","Check for SSRF via URL parameters and headers","Test file upload for unrestricted file types","Review API endpoints for broken object level authorization","Test JWT tokens for weak secrets and algorithm confusion","Check for CORS misconfiguration","Test password reset flow for predictable tokens"]},{id:"initial-access-network",name:"Initial Access \u2014 Network",tags:["initial-access","network","perimeter"],sections:["Service Exploitation","Credential Attacks","VPN and Remote Access Testing","Email Phishing","SMB Vulnerabilities","RDP Vulnerabilities"],defaultChecklist:["Run vulnerability scan against all discovered services","Test for default and weak credentials on exposed services","Check for EternalBlue / MS17-010 on Windows hosts","Test RDP for BlueKeep and DejaBlue","Enumerate SMB shares and null session access","Check for Responder / LLMNR/NBT-NS poisoning opportunities","Test VPN endpoints for credential stuffing"]},{id:"privilege-escalation-linux",name:"Privilege Escalation \u2014 Linux",tags:["privesc","linux","local"],sections:["SUID / SGID Binaries","Sudo Misconfigurations","Writable Paths and Cron Jobs","Kernel Exploits","Service Misconfigurations","Capabilities","NFS and Shared Directories","Password Reuse and Credentials in Files"],defaultChecklist:["Run linpeas.sh for automated enumeration","Check sudo -l for allowed commands","Find SUID/SGID binaries: find / -perm -4000 2>/dev/null","Enumerate cron jobs and writable cron directories","Check for writable /etc/passwd or /etc/shadow","Inspect running processes and their owners with pspy","Check for readable private SSH keys","Enumerate NFS exports for no_root_squash","Check kernel version against known exploits","Review capabilities: getcap -r / 2>/dev/null"]},{id:"privilege-escalation-windows",name:"Privilege Escalation \u2014 Windows",tags:["privesc","windows","local"],sections:["Service Misconfigurations","Unquoted Service Paths","Registry Autoruns","Token Impersonation","AlwaysInstallElevated","DLL Hijacking","Stored Credentials","Kernel Exploits"],defaultChecklist:["Run winpeas.exe or PowerUp.ps1 for automated enumeration","Check for unquoted service paths","Enumerate services with weak permissions using accesschk","Check AlwaysInstallElevated registry keys","Inspect scheduled tasks for writable binary paths","Look for credentials in registry with reg query","Check for stored credentials with cmdkey /list","Enumerate token privileges for impersonation opportunities","Check for DLL hijacking in service binary paths","Review autoruns with Autoruns64.exe or reg query HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"]},{id:"active-directory",name:"Active Directory",tags:["ad","active-directory","windows","kerberos"],sections:["Domain Enumeration","Kerberoasting","AS-REP Roasting","Pass the Hash","Pass the Ticket","Lateral Movement","ACL Abuse","DCSync","ADCS Abuse","GPO Abuse","BloodHound Analysis"],defaultChecklist:["Run BloodHound / SharpHound to map domain","Enumerate domain users, groups, and computers with ldapsearch or PowerView","Kerberoast: GetUserSPNs.py or Invoke-Kerberoast","AS-REP Roast users with no pre-auth required","Check for ACL paths to Domain Admin in BloodHound","Enumerate ADCS templates with certipy find","Check for ESC1-ESC8 certificate template vulnerabilities","Attempt DCSync if SeReplication privilege obtained","Enumerate unconstrained delegation hosts","Check for constrained delegation with S4U2Proxy abuse","Look for LAPS passwords in AD attributes","Enumerate GPO permissions for writable policies"]},{id:"lateral-movement",name:"Lateral Movement",tags:["lateral-movement","pivoting","post-exploitation"],sections:["Pass the Hash / Pass the Key","Remote Service Execution","WMI and WinRM","SMB Lateral Movement","DCOM","Tunneling and Pivoting"],defaultChecklist:["Use CrackMapExec to spray hashes across subnet","Test WinRM access with Evil-WinRM","Attempt PSExec / SMBExec for remote code execution","Use WMIExec for fileless lateral movement","Set up SOCKS proxy via Chisel or Ligolo-ng","Configure proxychains for traffic routing through pivot","Use impacket-smbclient to enumerate share access with new credentials"]},{id:"post-exploitation",name:"Post-Exploitation",tags:["post-exploitation","persistence","exfil"],sections:["Credential Harvesting","Persistence Mechanisms","Defense Evasion","Data Exfiltration","Covering Tracks"],defaultChecklist:["Dump LSASS with mimikatz sekurlsa::logonpasswords","Dump SAM/SYSTEM hive for offline cracking","Extract credentials from browser stores","Search for sensitive files: passwords, keys, configs","Establish persistence via registry run keys or scheduled tasks","Exfiltrate data over DNS, HTTPS, or allowed protocols","Clear Windows event logs if within scope","Remove added user accounts and reverse configuration changes"]},{id:"cloud-aws",name:"Cloud \u2014 AWS",tags:["cloud","aws","amazon"],sections:["IAM Enumeration","S3 Bucket Assessment","EC2 Instance Metadata","Lambda and Serverless","RDS and Database Services","CloudTrail and Logging Review","Privilege Escalation in AWS"],defaultChecklist:["Enumerate IAM users, roles, and policies with pacu or enumerate-iam","Check for public S3 buckets and sensitive object ACLs","Access EC2 metadata at http://169.254.169.254/latest/meta-data/","Extract IAM role credentials from instance metadata","Check for IMDSv1 (unauthenticated metadata access)","Enumerate Lambda functions and their environment variables","Look for overly permissive IAM policies allowing privilege escalation","Check CloudTrail for disabled logging or log deletion","Enumerate secrets in Secrets Manager and Parameter Store","Check for public RDS snapshots"]}],Ie=class{getAll(){return bt}getById(t){return bt.find(e=>e.id===t)}detectTemplate(t){let e=t.toLowerCase(),i,s=0;for(let r of bt){let a=0;for(let o of r.tags)e.includes(o)&&(a+=2);for(let o of r.sections)e.includes(o.toLowerCase())&&(a+=1);a>s&&(s=a,i=r)}return s>=2?i:void 0}getMissingGaps(t,e){let i=t.toLowerCase();return e.sections.filter(s=>!i.includes(s.toLowerCase()))}};var _t="PENNOTE_CODE_FENCE_";function De(n){var r,a,o,l,c,u;let t=yr(n),i=vr(n,t).split(`
`),s=[];for(let d of i){let h=d.trim();if(h.startsWith(_t)){s.push(d);continue}if(h.startsWith("#")){s.push(d);continue}if(h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")){s.push(d);continue}if(h.startsWith("- ")||h.startsWith("* ")){let p=(a=(r=d.match(/^(\s*)/))==null?void 0:r[1])!=null?a:"",g=h.slice(2).trim();g.length>0?s.push(`${p}- [ ] ${g}`):s.push(d);continue}if(/^\d+\.\s/.test(h)){let p=(l=(o=d.match(/^(\s*)/))==null?void 0:o[1])!=null?l:"",g=h.replace(/^\d+\.\s*/,"").trim();g.length>0?s.push(`${p}- [ ] ${g}`):s.push(d);continue}if(h.length>0&&!h.startsWith("|")&&!h.startsWith(">")){let p=(u=(c=d.match(/^(\s*)/))==null?void 0:c[1])!=null?u:"";s.push(`${p}- [ ] ${h}`)}else s.push(d)}return wr(s.join(`
`),t)}function yr(n){let t=[],e=/```[\s\S]*?```/g,i;for(;(i=e.exec(n))!==null;)t.push(i[0]);return t}function vr(n,t){let e=n;for(let i=0;i<t.length;i++)e=e.replace(t[i],`${_t}${i}`);return e}function wr(n,t){let e=n;for(let i=0;i<t.length;i++)e=e.replace(`${_t}${i}`,t[i]);return e}var Oe=require("obsidian"),Z="pennote-ai-panel",br={search:"\u25CB",crawl:"\u25CB",think:"\u25CB",write:"\u25CB",error:"\u2715",plan:"\u25CB"},de=class extends Oe.ItemView{constructor(e,i){super(e);this.onSendMessage=i;this.planTrackerEl=null;this.planStepListEl=null;this.planCurrentStepEl=null;this.attachedFileContent=null;this.attachedFileName=null}getViewType(){return Z}getDisplayText(){return"PenNote AI"}getIcon(){return"shield"}async onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("pennote-panel");let i=e.createDiv({cls:"pennote-panel-header"});i.createSpan({cls:"pennote-header-title",text:"\u25C8 PenNote AI"}),i.createEl("button",{cls:"pennote-header-btn",text:"Clear"}).addEventListener("click",()=>this.clearChat());let r=e.createDiv({cls:"pennote-chat-controls"});this.modeSelect=r.createEl("select",{cls:"pennote-mode-compact"});let a=[{value:"chat",label:"\u203A Chat"},{value:"enrich",label:"+ Enrich note"},{value:"gap-analysis",label:"\u25CE Gap analysis"},{value:"add-command",label:"$ Add command"},{value:"search-update",label:"\u21BB Search update"}];for(let u of a){let d=this.modeSelect.createEl("option",{text:u.label});d.value=u.value}this.chatContainer=e.createDiv({cls:"pennote-chat-messages"}),this.attachBadge=e.createDiv({cls:"pennote-attach-badge"}),this.attachBadge.style.display="none";let o=e.createDiv({cls:"pennote-chat-input-row"});this.fileInputEl=document.createElement("input"),this.fileInputEl.type="file",this.fileInputEl.accept=".txt,.md,.log,.csv,.json,.xml,.html,.pdf",this.fileInputEl.style.display="none",o.appendChild(this.fileInputEl),this.fileInputEl.addEventListener("change",()=>void this.handleFileAttach());let l=o.createEl("button",{cls:"pennote-attach-btn",text:"+"});l.title="Attach a text file or PDF",l.addEventListener("click",()=>{this.fileInputEl.value="",this.fileInputEl.click()}),this.chatInput=o.createEl("textarea",{cls:"pennote-chat-textarea"}),this.chatInput.placeholder="Ask anything or give an instruction\u2026",this.chatInput.rows=1,this.chatInput.addEventListener("input",()=>this.autoResize()),this.chatInput.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn=o.createEl("button",{cls:"pennote-send-btn",text:"Send"}),this.sendBtn.addEventListener("click",()=>void this.handleSend());let c=e.createDiv({cls:"pennote-footer"});this.statusEl=c.createSpan({cls:"pennote-status-text",text:"Ready"}),this.tokenEl=c.createSpan({cls:"pennote-token-usage"})}async onClose(){}appendChatMessage(e){var s;e.role==="assistant"&&((s=this.chatContainer.querySelector(".pennote-chat-bubble.loading"))==null||s.remove());let i=this.chatContainer.createDiv({cls:`pennote-chat-bubble ${e.role}${e.isLoading?" loading":""}`});e.role==="assistant"?Oe.MarkdownRenderer.render(this.app,e.text,i,"",this):i.setText(e.text),this.chatContainer.scrollTop=this.chatContainer.scrollHeight}appendErrorWithRetry(e,i){var a;(a=this.chatContainer.querySelector(".pennote-chat-bubble.loading"))==null||a.remove();let s=this.chatContainer.createDiv({cls:"pennote-chat-bubble assistant pennote-error-bubble"});s.createSpan({cls:"pennote-error-text",text:e}),s.createEl("button",{cls:"pennote-retry-btn",text:"\u21BB Retry"}).addEventListener("click",()=>{s.remove(),i()}),this.chatContainer.scrollTop=this.chatContainer.scrollHeight}appendDiffSummary(e,i,s){let r=this.chatContainer.createDiv({cls:"pennote-chat-bubble pennote-diff-bubble"});r.createSpan({cls:"pennote-diff-label",text:"Note updated"}),e>0&&r.createSpan({cls:"pennote-diff-added",text:`+${e}`}),i>0&&r.createSpan({cls:"pennote-diff-removed",text:`-${i}`}),r.createSpan({cls:"pennote-diff-file",text:s}),this.chatContainer.scrollTop=this.chatContainer.scrollHeight}startPlanTracker(){var i,s;(i=this.chatContainer.querySelector(".pennote-chat-bubble.loading"))==null||i.remove(),(s=this.planTrackerEl)==null||s.remove(),this.planCurrentStepEl=null,this.planTrackerEl=this.chatContainer.createDiv({cls:"pennote-plan-tracker"});let e=this.planTrackerEl.createDiv({cls:"pennote-plan-header"});e.createSpan({cls:"pennote-plan-pulse"}),e.createSpan({text:"Working\u2026"}),this.planStepListEl=this.planTrackerEl.createDiv({cls:"pennote-plan-steps"}),this.chatContainer.scrollTop=this.chatContainer.scrollHeight}pushPlanStep(e){var s;if(!this.planTrackerEl||!this.planStepListEl)return;if(this.planCurrentStepEl){this.planCurrentStepEl.removeClass("current"),this.planCurrentStepEl.addClass("done");let r=this.planCurrentStepEl.querySelector(".pennote-step-icon");r&&r.textContent!=="\u2715"&&(r.textContent="\u2713")}let i=this.planStepListEl.createDiv({cls:`pennote-plan-step current step-${e.type}`});i.createSpan({cls:"pennote-step-icon",text:(s=br[e.type])!=null?s:"\u25CB"}),i.createSpan({cls:"pennote-step-text",text:e.message}),this.planCurrentStepEl=i,this.chatContainer.scrollTop=this.chatContainer.scrollHeight}finishPlanTracker(){if(!this.planTrackerEl)return;if(this.planCurrentStepEl){this.planCurrentStepEl.removeClass("current"),this.planCurrentStepEl.addClass("done");let i=this.planCurrentStepEl.querySelector(".pennote-step-icon");i&&i.textContent!=="\u2715"&&(i.textContent="\u2713")}let e=this.planTrackerEl.querySelector(".pennote-plan-header");e&&(e.empty(),e.createEl("span",{cls:"pennote-plan-done-icon",text:"\u2713"}),e.createEl("span",{text:" Done"})),this.planTrackerEl=null,this.planStepListEl=null,this.planCurrentStepEl=null}appendLog(e){this.planTrackerEl&&this.pushPlanStep(e)}showThinking(){var e;this.planTrackerEl||((e=this.chatContainer.querySelector(".pennote-chat-bubble.loading"))==null||e.remove(),this.chatContainer.createDiv({cls:"pennote-chat-bubble assistant loading"}).setText("Thinking\u2026"),this.chatContainer.scrollTop=this.chatContainer.scrollHeight)}setStatus(e){this.statusEl.setText(e)}setTokenUsage(e){this.tokenEl.setText(`${e.totalTokens.toLocaleString()} tokens (\u2191${e.promptTokens.toLocaleString()} \u2193${e.completionTokens.toLocaleString()})`)}setInputEnabled(e){this.chatInput.disabled=!e,this.sendBtn.disabled=!e,this.statusEl.setText(e?"Ready":"Running\u2026")}clearLog(){}clearChat(){this.chatContainer.empty(),this.tokenEl.setText(""),this.statusEl.setText("Ready"),this.clearAttachment(),this.planTrackerEl=null,this.planStepListEl=null,this.planCurrentStepEl=null}async handleSend(){let e=this.chatInput.value.trim();if(!e||this.sendBtn.disabled)return;let i=e;this.attachedFileContent&&this.attachedFileName&&(i+=this.buildAttachedContent(this.attachedFileContent,this.attachedFileName)),this.appendChatMessage({role:"user",text:e,timestamp:Date.now()}),this.chatInput.value="",this.autoResize(),this.clearAttachment(),this.setInputEnabled(!1);let s=this.modeSelect.value;try{await this.onSendMessage(i,s)}catch(r){this.appendChatMessage({role:"assistant",text:`Error: ${r instanceof Error?r.message:String(r)}`,timestamp:Date.now()})}finally{this.setInputEnabled(!0),this.chatInput.focus()}}async handleFileAttach(){var i;let e=(i=this.fileInputEl.files)==null?void 0:i[0];if(e){this.attachedFileName=e.name;try{e.name.toLowerCase().endsWith(".pdf")?this.attachedFileContent=await this.extractPdfText(e):this.attachedFileContent=await e.text(),this.showAttachBadge(e.name,this.attachedFileContent.length)}catch(s){this.attachedFileContent=null,this.showAttachError("Could not read file. Try a plain text format.")}}}async extractPdfText(e){let i=await e.arrayBuffer(),s=new Uint8Array(i),r="";for(let c=0;c<s.length;c++)r+=String.fromCharCode(s[c]);let a=[],o=/BT([\s\S]*?)ET/g,l;for(;(l=o.exec(r))!==null;){let c=l[1],u=/\(([^)]*)\)\s*(?:Tj|TJ|'|")/g,d;for(;(d=u.exec(c))!==null;){let p=d[1].replace(/\\(\d{3})/g,(g,y)=>String.fromCharCode(parseInt(y,8))).replace(/\\n/g," ").replace(/\\r/g," ");p.trim()&&a.push(p)}let h=/<([0-9a-fA-F]+)>\s*(?:Tj|TJ)/g;for(;(d=h.exec(c))!==null;){let p=d[1],g="";for(let y=0;y<p.length;y+=2){let v=parseInt(p.slice(y,y+2),16);v>31&&(g+=String.fromCharCode(v))}g.trim()&&a.push(g)}}return a.join(" ").replace(/\s+/g," ").trim()||"[No readable text found in PDF]"}buildAttachedContent(e,i){var c,u;let s=(u=(c=i.split(".").pop())==null?void 0:c.toLowerCase())!=null?u:"",r=s==="md"?"markdown":s,a=6e3;if(e.length<=a)return`
[Attached: ${i}]
\`\`\`${r}
${e}
\`\`\``;let o=[];for(let d=0;d<e.length&&o.length<4;d+=a)o.push(e.slice(d,d+a));let l=o.length;return o.map((d,h)=>`
[Attached: ${i} \u2014 Part ${h+1}/${l}]
\`\`\`${r}
${d}
\`\`\``).join("")}showAttachBadge(e,i){this.attachBadge.empty(),this.attachBadge.style.display="flex",this.attachBadge.createSpan({cls:"pennote-attach-icon",text:"\u22A1"}),this.attachBadge.createSpan({cls:"pennote-attach-name",text:`${e} (${i.toLocaleString()} chars)`}),this.attachBadge.createEl("button",{cls:"pennote-attach-remove",text:"\xD7"}).addEventListener("click",()=>this.clearAttachment())}showAttachError(e){this.attachBadge.empty(),this.attachBadge.style.display="flex",this.attachBadge.createSpan({cls:"pennote-attach-error",text:e}),this.attachBadge.createEl("button",{cls:"pennote-attach-remove",text:"\xD7"}).addEventListener("click",()=>this.clearAttachment())}clearAttachment(){this.attachedFileContent=null,this.attachedFileName=null,this.attachBadge.style.display="none",this.attachBadge.empty(),this.fileInputEl.value=""}autoResize(){this.chatInput.style.height="auto",this.chatInput.style.height=Math.min(this.chatInput.scrollHeight,120)+"px"}};var He=class{constructor(t){this.spinnerTimer=null;this.frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.frameIndex=0;this.statusBarItem=t.addStatusBarItem(),this.statusBarItem.addClass("pennote-status-bar"),this.statusBarItem.style.display="none"}setState(t){var i;if(this.stopSpinner(),t==="idle"){this.statusBarItem.style.display="none";return}let e={searching:"PenNote: Searching",crawling:"PenNote: Crawling",thinking:"PenNote: Thinking",writing:"PenNote: Writing"};this.statusBarItem.style.display="",this.startSpinner((i=e[t])!=null?i:"PenNote: Working")}startSpinner(t){this.frameIndex=0,this.spinnerTimer=window.setInterval(()=>{this.statusBarItem.setText(`${this.frames[this.frameIndex%this.frames.length]} ${t}`),this.frameIndex++},100)}stopSpinner(){this.spinnerTimer!==null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null)}destroy(){this.stopSpinner(),this.statusBarItem.remove()}};var Fn=require("obsidian"),Fe=class extends Fn.Modal{constructor(e,i,s){super(e);this.result=null;this.initialContext=i,this.onSubmit=s}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"PenNote AI"});let i=e.createDiv({cls:"pennote-modal-content"}),s=i.createEl("label",{text:"Mode"}),r=i.createEl("select",{cls:"pennote-mode-select"});s.htmlFor="pennote-mode",r.id="pennote-mode";let a=[{value:"enrich",label:"Enrich \u2014 add new techniques and updated information"},{value:"gap-analysis",label:"Gap Analysis \u2014 find and fill missing sections"},{value:"add-command",label:"Add Command \u2014 research and add tool commands"},{value:"search-update",label:"Search Update \u2014 refresh info from the web"},{value:"checklist",label:"Convert to Checklist \u2014 reformat selected text"}];for(let h of a){let p=r.createEl("option",{text:h.label});p.value=h.value}let o=i.createEl("label",{text:"Instruction"}),l=i.createEl("textarea",{cls:"pennote-instruction-input"});if(o.htmlFor="pennote-instruction",l.id="pennote-instruction",l.placeholder="Describe what you want to add, update, or improve in this note...",this.initialContext){let h=i.createDiv();h.createEl("label",{text:"Context (active note)"});let p=h.createEl("div");p.style.fontSize="11px",p.style.color="var(--text-muted)",p.style.maxHeight="60px",p.style.overflow="hidden",p.style.fontFamily="var(--font-monospace)",p.setText(this.initialContext.slice(0,200)+(this.initialContext.length>200?"...":""))}let c=i.createDiv({cls:"pennote-diff-actions"});c.createEl("button",{text:"Cancel"}).addEventListener("click",()=>this.close());let d=c.createEl("button",{text:"Run Agent"});d.style.fontWeight="600",d.addEventListener("click",()=>{let h=l.value.trim();if(!h){l.style.border="1px solid var(--color-red)";return}this.result={instruction:h,mode:r.value},this.close(),this.onSubmit(this.result)}),l.addEventListener("keydown",h=>{h.key==="Enter"&&(h.ctrlKey||h.metaKey)&&d.click()}),setTimeout(()=>l.focus(),50)}onClose(){this.contentEl.empty()}};var Bn=require("obsidian");var Be=class extends Bn.Modal{constructor(e,i,s,r){super(e);this.hunks=i,this.onAccept=s,this.onReject=r,this.modalEl.addClass("pennote-diff-modal")}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Review Proposed Changes"});let i=wt(this.hunks);e.createDiv({cls:"pennote-diff-summary"}).setText(`${i.added} lines added, ${i.removed} lines removed`);let r=e.createDiv({cls:"pennote-diff-container"});for(let c of this.hunks){let u=c.value.split(`
`);for(let d=0;d<u.length;d++){let h=u[d];if(d===u.length-1&&h==="")continue;let p=r.createDiv({cls:`pennote-diff-line ${c.type}`}),g=c.type==="added"?"+ ":c.type==="removed"?"- ":" ";p.setText(g+h)}}let a=e.createDiv({cls:"pennote-diff-actions"}),o=a.createEl("button",{text:"Reject"});o.addEventListener("click",()=>{this.close(),this.onReject()});let l=a.createEl("button",{text:"Accept Changes"});l.style.fontWeight="600",l.addEventListener("click",()=>{this.close(),this.onAccept()}),this.scope.register(["Ctrl"],"Enter",()=>(l.click(),!1)),this.scope.register([],"Escape",()=>(o.click(),!1))}onClose(){this.contentEl.empty()}};var $n="pennote-context-store",$e=class extends P.Plugin{constructor(){super(...arguments);this.scheduledRefreshTimer=null;this.isRunning=!1}async onload(){await this.loadSettings(),this.initServices(),this.addSettingTab(new fe(this.app,this)),this.registerView(Z,e=>new de(e,this.handleChatMessage.bind(this))),this.registerCommands(),this.registerEvents(),this.app.workspace.onLayoutReady(async()=>{await this.noteIndexer.buildIndex(),this.maybeActivatePanel()}),this.settings.enableScheduledRefresh&&this.scheduleRefresh()}onunload(){this.scheduledRefreshTimer!==null&&clearInterval(this.scheduledRefreshTimer)}async saveSettings(){await this.saveData(this.settings),this.llmClient.updateSettings(this.settings),this.crawler.updateSettings(this.settings),this.toolRunner=new se(this.app,this.searcher,this.crawler,this.settings.searchResultLimit),this.agentLoop=new re(this.llmClient,this.toolRunner,this.settings.maxAgentIterations)}initServices(){var s,r;this.llmClient=new K(this.settings),this.queryBuilder=new me(this.llmClient),this.searcher=new ye,this.crawler=new ve(this.settings),this.noteIndexer=new be(this.app),this.templateRegistry=new Ie,this.actionPlanner=new Ee(this.llmClient),this.toolRunner=new se(this.app,this.searcher,this.crawler,this.settings.searchResultLimit),this.agentLoop=new re(this.llmClient,this.toolRunner,this.settings.maxAgentIterations),this.progressIndicator=new He(this);let e=(r=(s=this.app).loadLocalStorage)==null?void 0:r.call(s,$n),i=null;if(e)try{i=JSON.parse(e)}catch(a){i=null}this.contextStore=new we(i,async a=>{var o,l;(l=(o=this.app).saveLocalStorage)==null||l.call(o,$n,JSON.stringify(a))})}registerCommands(){this.addCommand({id:"enrich-note",name:"Enrich current note",editorCallback:(e,i)=>{i.file&&this.openCommandModal(i.file,"enrich")}}),this.addCommand({id:"gap-analysis",name:"Analyze gaps in current note",editorCallback:(e,i)=>{i.file&&this.openCommandModal(i.file,"gap-analysis")}}),this.addCommand({id:"add-command",name:"Add tool command to current note",editorCallback:(e,i)=>{i.file&&this.openCommandModal(i.file,"add-command")}}),this.addCommand({id:"update-commands",name:"Update commands in current note",editorCallback:(e,i)=>{i.file&&this.openCommandModal(i.file,"search-update")}}),this.addCommand({id:"convert-checklist",name:"Convert selection to checklist",editorCallback:e=>{let i=e.getSelection();if(!i.trim()){new P.Notice("Select text first to convert to checklist.");return}let s=De(i);e.replaceSelection(s)}}),this.addCommand({id:"open-panel",name:"Open PenNote panel",callback:()=>this.activatePanel()}),this.addCommand({id:"run-instruction",name:"Run custom instruction",editorCallback:(e,i)=>{i.file&&this.openCommandModal(i.file)}}),this.addCommand({id:"scheduled-refresh-manual",name:"Run scheduled refresh now",callback:()=>this.runScheduledRefresh()})}registerEvents(){this.registerEvent(this.app.vault.on("modify",e=>{e instanceof P.TFile&&e.extension==="md"&&this.noteIndexer.indexFile(e)})),this.registerEvent(this.app.vault.on("create",e=>{e instanceof P.TFile&&e.extension==="md"&&this.noteIndexer.indexFile(e)})),this.registerEvent(this.app.vault.on("delete",e=>{e instanceof P.TFile&&this.noteIndexer.removeFile(e.path)})),this.registerEvent(this.app.workspace.on("editor-menu",(e,i,s)=>{e.addItem(r=>{r.setTitle("PenNote: Open chat").setIcon("message-square").onClick(()=>void this.activatePanel())}),e.addItem(r=>{r.setTitle("PenNote: Convert to checklist").setIcon("check-square").onClick(()=>{let a=i.getSelection();a.trim()&&i.replaceSelection(De(a))})}),s.file&&e.addItem(r=>{r.setTitle("PenNote: Enrich note").setIcon("shield").onClick(()=>this.openCommandModal(s.file))})})),this.registerEvent(this.app.workspace.on("file-menu",(e,i)=>{i instanceof P.TFile&&i.extension==="md"&&(e.addItem(s=>{s.setTitle("PenNote: Open chat").setIcon("message-square").onClick(()=>void this.activatePanel())}),e.addItem(s=>{s.setTitle("PenNote: Enrich note").setIcon("shield").onClick(()=>this.openCommandModal(i))}))}))}openCommandModal(e,i){let s=(()=>this.noteIndexer.getSummary(e.path)||e.basename)();new Fe(this.app,s,async r=>{await this.runAgent(e,r.instruction,r.mode)}).open()}async handleChatMessage(e,i){var d;let s=this.getPanelView();if(!s)return;if(!this.settings.mistralApiKey){s.appendChatMessage({role:"assistant",text:"[!] No Mistral API key configured. Go to Settings \u2192 PenNote AI to add your key.",timestamp:Date.now()});return}if(this.isRunning){s.appendChatMessage({role:"assistant",text:"Still working on the previous task \u2014 please wait a moment.",timestamp:Date.now()});return}this.isRunning=!0,this.progressIndicator.setState("thinking");let r=this.app.workspace.getActiveFile(),a="",o="";if(r)try{a=await this.app.vault.read(r),o=r.path}catch(h){}this.toolRunner.activeFilePath=o;let l=e.toLowerCase();if(this.toolRunner.allowCreateNote=/(create|make|new)\s+(a\s+)?(new\s+)?note|start\s+a\s+new\s+note/.test(l),!r&&!this.toolRunner.allowCreateNote){s.appendChatMessage({role:"assistant",text:"No active note is open. Please open a note in the editor first, or ask me to create a new one.",timestamp:Date.now()}),this.isRunning=!1,this.progressIndicator.setState("idle");return}let u=((d={enrich:"[Mode: enrich \u2014 add new techniques and updated information] ","gap-analysis":"[Mode: gap-analysis \u2014 find missing methodology sections and fill them] ","add-command":"[Mode: add-command \u2014 research and add tool commands with full syntax, flags, and examples] ","search-update":"[Mode: search-update \u2014 search the web and refresh outdated content] "}[i])!=null?d:"")+e;s.startPlanTracker();try{let h=await this.agentLoop.chatTurn(u,a,o,p=>{s.pushPlanStep(p);let g={search:"searching",crawl:"crawling",think:"thinking",write:"writing"};g[p.type]&&this.progressIndicator.setState(g[p.type])}).finally(()=>s.finishPlanTracker());if(r&&o)try{let p=await this.app.vault.read(r);if(p!==a){let g=yt(a,p),y=g.filter(w=>w.type==="added").reduce((w,E)=>w+E.value.split(`
`).length,0),v=g.filter(w=>w.type==="removed").reduce((w,E)=>w+E.value.split(`
`).length,0);s.appendDiffSummary(y,v,r.basename)}}catch(p){}s.appendChatMessage({role:"assistant",text:h.finalContent.trim()||"Done.",timestamp:Date.now()}),s.setTokenUsage(h.tokenUsage),r&&h.queriesUsed.length>0&&await this.contextStore.addEnrichmentRecord({noteId:r.path,timestamp:Date.now(),queriesUsed:h.queriesUsed,urlsCrawled:h.urlsCrawled,summary:h.finalContent.slice(0,200)})}catch(h){let p=`Error: ${h instanceof Error?h.message:String(h)}`;s.appendErrorWithRetry(p,()=>{this.handleChatMessage(e,i)})}finally{this.isRunning=!1,this.progressIndicator.setState("idle")}}async runAgent(e,i,s){if(this.isRunning){new P.Notice("PenNote is already running. Please wait.");return}if(!this.settings.mistralApiKey){new P.Notice("PenNote: No Mistral API key configured. Check Settings.");return}this.isRunning=!0,await this.activatePanel();let r=this.getPanelView();r==null||r.startPlanTracker(),r==null||r.setStatus("Running..."),this.progressIndicator.setState("thinking");let a=o=>{r==null||r.pushPlanStep(o);let l={search:"searching",crawl:"crawling",think:"thinking",write:"writing"};l[o.type]&&this.progressIndicator.setState(l[o.type])};try{let o="";try{o=await this.app.vault.read(e)}catch(u){o=""}if(s==="checklist"){let u=De(o);await this.proposeAndApply(e,o,u,r);return}if(s==="gap-analysis"){let u=this.templateRegistry.detectTemplate(o);if(u){let d=this.templateRegistry.getMissingGaps(o,u);if(d.length===0){new P.Notice("No gaps detected in this note based on the template."),r==null||r.setStatus("No gaps found.");return}let h=`## Identified Gaps
${d.map(p=>`- [ ] Missing section: **${p}**`).join(`
`)}
`;await this.proposeAndApply(e,o,o+`
`+h,r),new P.Notice(`Found ${d.length} gaps. Enriching with web search...`)}}let l=await this.agentLoop.run(i,o,e.path,a);r==null||r.setTokenUsage(l.tokenUsage),await this.contextStore.addEnrichmentRecord({noteId:e.path,timestamp:Date.now(),queriesUsed:l.queriesUsed,urlsCrawled:l.urlsCrawled,summary:l.finalContent.slice(0,200)});let c=await this.app.vault.read(e);if(l.urlsCrawled.length>0){let u=l.urlsCrawled.map(h=>({title:h,url:h,date:new Date().toISOString().split("T")[0]})),d=Gt(u);if(d&&!c.includes("## References")){let h=c.trimEnd()+`
`+d,p=Je(h,"last_enriched",new Date().toISOString().split("T")[0]);await this.proposeAndApply(e,c,p,r)}}else{if(l.finalContent.trim()){let u=Je(c,"last_enriched",new Date().toISOString().split("T")[0]);u!==c&&await this.app.vault.modify(e,u)}new P.Notice("PenNote: Agent completed. Check the note for changes.")}r==null||r.setStatus("Done"),r==null||r.finishPlanTracker(),r==null||r.appendChatMessage({role:"assistant",text:`Enrichment complete. ${l.urlsCrawled.length} URL(s) crawled. Check the note for updates.`,timestamp:Date.now()})}catch(o){let l=o instanceof Error?o.message:String(o);new P.Notice(`PenNote error: ${l}`,8e3),r==null||r.finishPlanTracker(),r==null||r.appendLog({type:"error",message:l,timestamp:Date.now()}),r==null||r.setStatus("Error")}finally{this.isRunning=!1,this.progressIndicator.setState("idle")}}async proposeAndApply(e,i,s,r){if(i===s){new P.Notice("PenNote: No changes to apply.");return}let a=yt(i,s),o=this.settings.autoConfirmThreshold;if(o==="always"||o==="small-changes"&&Hn(a)){await this.app.vault.modify(e,vt(i,a)),new P.Notice("PenNote: Changes applied."),r==null||r.appendLog({type:"write",message:"Changes applied to note.",timestamp:Date.now()});return}new Be(this.app,a,async()=>{await this.app.vault.modify(e,vt(i,a)),new P.Notice("PenNote: Changes accepted and applied."),r==null||r.appendLog({type:"write",message:"Changes accepted by user.",timestamp:Date.now()})},()=>{new P.Notice("PenNote: Changes rejected."),r==null||r.appendLog({type:"think",message:"Changes rejected by user.",timestamp:Date.now()})}).open()}async runScheduledRefresh(){let e=this.noteIndexer.getByTag(this.settings.methodologyTag),i=Date.now()-this.settings.refreshIntervalDays*24*60*60*1e3,s=e.filter(r=>r.lastModified<i);if(s.length===0){new P.Notice("PenNote: All methodology notes are up to date.");return}new P.Notice(`PenNote: Refreshing ${s.length} stale notes...`);for(let r of s){let a=this.app.vault.getAbstractFileByPath(r.path);a instanceof P.TFile&&(await this.runAgent(a,"Update this note with recent techniques and verify all commands are current.","search-update"),await new Promise(o=>setTimeout(o,2e3)))}}scheduleRefresh(){if(this.scheduledRefreshTimer!==null)return;let e=this.settings.refreshIntervalDays*24*60*60*1e3;this.scheduledRefreshTimer=window.setInterval(()=>{this.runScheduledRefresh()},e)}async activatePanel(){let e=this.app.workspace.getLeavesOfType(Z);if(e.length>0){this.app.workspace.revealLeaf(e[0]);return}let i=this.app.workspace.getRightLeaf(!1);i&&(await i.setViewState({type:Z,active:!0}),this.app.workspace.revealLeaf(i))}maybeActivatePanel(){}getPanelView(){let e=this.app.workspace.getLeavesOfType(Z);return e.length>0&&e[0].view instanceof de?e[0].view:null}async loadSettings(){this.settings=Object.assign({},Nt,await this.loadData())}};