@timqi/pier 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +26 -9
  2. package/dist/agent/pi.js +103 -5
  3. package/dist/channels/conversations.js +10 -0
  4. package/dist/core/router.js +27 -11
  5. package/dist/db.js +30 -0
  6. package/dist/extensions/index.js +34 -0
  7. package/dist/extensions/web/anthropic.js +118 -0
  8. package/dist/extensions/web/artifacts.js +57 -0
  9. package/dist/extensions/web/content.js +130 -0
  10. package/dist/extensions/web/http.js +106 -0
  11. package/dist/extensions/web/index.js +9 -0
  12. package/dist/extensions/web/json.js +5 -0
  13. package/dist/extensions/web/language.js +47 -0
  14. package/dist/extensions/web/openai.js +112 -0
  15. package/dist/extensions/web/provider.js +121 -0
  16. package/dist/extensions/web/tools.js +284 -0
  17. package/dist/main.js +44 -6
  18. package/dist/paths.js +15 -0
  19. package/dist/settings.js +68 -13
  20. package/dist/web/instance.js +32 -8
  21. package/dist/web/providers.js +16 -0
  22. package/dist/web/public/assets/{ghostty-web-BhZV0Vvv.js → ghostty-web-C4N9kjtH.js} +1 -1
  23. package/dist/web/public/assets/index-DNCJJRSS.js +91 -0
  24. package/dist/web/public/assets/index-DYl1xk5y.css +2 -0
  25. package/dist/web/public/index.html +27 -4
  26. package/dist/web/public/manifest.webmanifest +11 -1
  27. package/dist/web/public/sw.js +109 -0
  28. package/dist/web/push.js +233 -0
  29. package/dist/web/server.js +51 -4
  30. package/dist/web/session-state.js +48 -9
  31. package/dist/web/terminal.js +34 -4
  32. package/dist/web/webpush.js +131 -0
  33. package/package.json +1 -1
  34. package/skills/pier-help/SKILL.md +12 -0
  35. package/dist/web/public/assets/index-BbwoGR-O.js +0 -90
  36. package/dist/web/public/assets/index-BlHvP59B.css +0 -2
@@ -0,0 +1,91 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=(e,t,n=`POST`)=>fetch(e,{method:n,headers:{"content-type":`application/json`},body:JSON.stringify(t)});async function u(e,t){return(await e.json().catch(()=>({}))).error??`${t} (${e.status})`}async function d(e,t,n,r){let i=window.prompt(e);if(!i?.trim())return{sent:!1};try{let e=await l(t,{message:i,...n});return{sent:!0,...e.ok?{}:{error:await u(e,r)}}}catch(e){return{sent:!0,error:`${r}: ${String(e)}`}}}function f(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function p(e){if(Array.isArray(e))return e}function m(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function h(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function g(e,t){return p(e)||m(e,t)||_(e,t)||h()}function _(e,t){if(e){if(typeof e==`string`)return f(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?f(e,t):void 0}}var v=Object.entries,y=Object.setPrototypeOf,b=Object.isFrozen,x=Object.getPrototypeOf,S=Object.getOwnPropertyDescriptor,C=Object.freeze,w=Object.seal,T=Object.create,E=typeof Reflect<`u`&&Reflect,D=E.apply,O=E.construct;C||=function(e){return e},w||=function(e){return e},D||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},O||=function(e){return new e(...[...arguments].slice(1))};var k=P(Array.prototype.forEach),A=P(Array.prototype.lastIndexOf),ee=P(Array.prototype.pop),j=P(Array.prototype.push),te=P(Array.prototype.splice),M=Array.isArray,ne=P(String.prototype.toLowerCase),N=P(String.prototype.toString),re=P(String.prototype.match),ie=P(String.prototype.replace),ae=P(String.prototype.indexOf),oe=P(String.prototype.trim),se=P(Number.prototype.toString),ce=P(Boolean.prototype.toString),le=typeof BigInt>`u`?null:P(BigInt.prototype.toString),ue=typeof Symbol>`u`?null:P(Symbol.prototype.toString),de=P(Object.prototype.hasOwnProperty),fe=P(Object.prototype.toString),pe=P(RegExp.prototype.test),me=he(TypeError);function P(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return D(e,t,n)}}function he(e){return function(){return O(e,[...arguments])}}function F(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ne;if(y&&y(e,null),!M(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(b(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ge(e){for(let t=0;t<e.length;t++)de(e,t)||(e[t]=null);return e}function _e(e){let t=T(null);for(let r of v(e)){var n=g(r,2);let i=n[0],a=n[1];de(e,i)&&(t[i]=M(a)?ge(a):a&&typeof a==`object`&&a.constructor===Object?_e(a):a)}return t}function ve(e){switch(typeof e){case`string`:return e;case`number`:return se(e);case`boolean`:return ce(e);case`bigint`:return le?le(e):`0`;case`symbol`:return ue?ue(e):`Symbol()`;case`undefined`:return fe(e);case`function`:case`object`:{if(e===null)return fe(e);let t=e,n=ye(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:fe(e)}return fe(e)}default:return fe(e)}}function ye(e,t){for(;e!==null;){let n=S(e,t);if(n){if(n.get)return P(n.get);if(typeof n.value==`function`)return P(n.value)}e=x(e)}function n(){return null}return n}function be(e){try{return pe(e,``),!0}catch{return!1}}var xe=C(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Se=C(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),Ce=C([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),we=C([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Te=C(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Ee=C([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),De=C([`#text`]),Oe=C(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),ke=C(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.pointer-events.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.vector-effect.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Ae=C(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),je=C([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Me=w(/{{[\w\W]*|^[\w\W]*}}/g),Ne=w(/<%[\w\W]*|^[\w\W]*%>/g),Pe=w(/\${[\w\W]*/g),Fe=w(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ie=w(/^aria-[\-\w]+$/),Le=w(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Re=w(/^(?:\w+script|data):/i),ze=w(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Be=w(/^html$/i),Ve=w(/^[a-z][.\w]*(-[.\w]+)+$/i),He=w(/<[/\w!]/g),Ue=w(/<[/\w]/g),We=w(/<\/no(script|embed|frames)/i),Ge=w(/\/>/i),Ke={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},qe=[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`],Je=C(F({},qe)),Ye=function(){let e={};return k(qe,t=>{e[t]=w(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),C(e)}(),Xe=function(){return typeof window>`u`?null:window},Ze=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Qe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},$e=function(e,t,n,r){return de(e,t)&&M(e[t])?F(r.base?_e(r.base):{},e[t],r.transform):n},et=function(e,t,n){let r=de(e,t)?e[t]:void 0;return r&&typeof r==`object`?_e(r):n()};function tt(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xe(),t=e=>tt(e);if(t.version=`3.4.14`,t.removed=[],!e||!e.document||e.document.nodeType!==Ke.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=ye(d,`cloneNode`),p=ye(d,`remove`),m=ye(d,`nextSibling`),h=ye(d,`childNodes`),g=ye(d,`parentNode`),_=ye(d,`shadowRoot`),y=ye(d,`attributes`),b=o&&o.prototype?ye(o.prototype,`nodeType`):null,x=o&&o.prototype?ye(o.prototype,`nodeName`):null,S=o&&o.prototype?ye(o.prototype,`ownerDocument`):null,E=function(e){return b?b(e):e.nodeType},D=function(e){return x?x(e):e.nodeName};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let O,se=``,ce,le=!1,ue=0,fe=function(){if(ue>0)throw me(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},P=function(e){fe(),ue++;try{return O.createHTML(e)}finally{ue--}},he=function(e){fe(),ue++;try{return O.createScriptURL(e)}finally{ue--}},ge=function(){return le||=(ce=Ze(u,i),!0),ce},qe=n,nt=qe.implementation,rt=qe.createNodeIterator,it=qe.createDocumentFragment,at=qe.getElementsByTagName,ot=r.importNode,I=Qe();t.isSupported=typeof v==`function`&&typeof g==`function`&&nt&&nt.createHTMLDocument!==void 0;let L=Me,st=Ne,ct=Pe,lt=Fe,ut=Ie,dt=Re,ft=ze,pt=Ve,mt=Le,R=null,ht=F({},[...xe,...Se,...Ce,...Te,...De]),z=null,gt=F({},[...Oe,...ke,...Ae,...je]),_t=Object.seal(T(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),vt=null,yt=null,bt=Object.seal(T(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),xt=!0,St=!0,Ct=!1,wt=!0,Tt=!1,Et=!0,Dt=!1,Ot=!1,kt=null,At=null,jt=!1,Mt=!1,Nt=!1,Pt=!1,Ft=!0,It=!1,Lt=`user-content-`,Rt=!0,zt=!1,Bt={},Vt=null,Ht=F({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),Ut=null,Wt=F({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Gt=null,Kt=F({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),qt=`http://www.w3.org/1998/Math/MathML`,Jt=`http://www.w3.org/2000/svg`,Yt=`http://www.w3.org/1999/xhtml`,Xt=Yt,Zt=!1,Qt=null,$t=F({},[qt,Jt,Yt],N),en=C([`mi`,`mo`,`mn`,`ms`,`mtext`]),tn=F({},en),nn=C([`annotation-xml`]),rn=F({},nn),an=F({},[`title`,`style`,`font`,`a`,`script`]),on=null,sn=[`application/xhtml+xml`,`text/html`],B=null,cn=null,ln=n.createElement(`form`),un=function(e){return e instanceof RegExp||e instanceof Function},dn=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(cn&&cn===e)return;(!e||typeof e!=`object`)&&(e={}),e=_e(e),on=sn.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,B=on===`application/xhtml+xml`?N:ne,R=$e(e,`ALLOWED_TAGS`,ht,{transform:B}),z=$e(e,`ALLOWED_ATTR`,gt,{transform:B}),Qt=$e(e,`ALLOWED_NAMESPACES`,$t,{transform:N}),Gt=$e(e,`ADD_URI_SAFE_ATTR`,Kt,{transform:B,base:Kt}),Ut=$e(e,`ADD_DATA_URI_TAGS`,Wt,{transform:B,base:Wt}),Vt=$e(e,`FORBID_CONTENTS`,Ht,{transform:B}),vt=$e(e,`FORBID_TAGS`,_e({}),{transform:B}),yt=$e(e,`FORBID_ATTR`,_e({}),{transform:B}),Bt=de(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?_e(e.USE_PROFILES):e.USE_PROFILES:!1,xt=e.ALLOW_ARIA_ATTR!==!1,St=e.ALLOW_DATA_ATTR!==!1,Ct=e.ALLOW_UNKNOWN_PROTOCOLS||!1,wt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Tt=e.SAFE_FOR_TEMPLATES||!1,Et=e.SAFE_FOR_XML!==!1,Dt=e.WHOLE_DOCUMENT||!1,Mt=e.RETURN_DOM||!1,Nt=e.RETURN_DOM_FRAGMENT||!1,Pt=e.RETURN_TRUSTED_TYPE||!1,jt=e.FORCE_BODY||!1,Ft=e.SANITIZE_DOM!==!1,It=e.SANITIZE_NAMED_PROPS||!1,Rt=e.KEEP_CONTENT!==!1,zt=e.IN_PLACE||!1,mt=be(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Le,Xt=typeof e.NAMESPACE==`string`?e.NAMESPACE:Yt,tn=et(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>F({},en)),rn=et(e,`HTML_INTEGRATION_POINTS`,()=>F({},nn));let t=et(e,`CUSTOM_ELEMENT_HANDLING`,()=>T(null));if(_t=T(null),de(t,`tagNameCheck`)&&un(t.tagNameCheck)&&(_t.tagNameCheck=t.tagNameCheck),de(t,`attributeNameCheck`)&&un(t.attributeNameCheck)&&(_t.attributeNameCheck=t.attributeNameCheck),de(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(_t.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),w(_t),Tt&&(St=!1),Nt&&(Mt=!0),Bt&&(R=F({},De),z=T(null),Bt.html===!0&&(F(R,xe),F(z,Oe)),Bt.svg===!0&&(F(R,Se),F(z,ke),F(z,je)),Bt.svgFilters===!0&&(F(R,Ce),F(z,ke),F(z,je)),Bt.mathMl===!0&&(F(R,Te),F(z,Ae),F(z,je))),bt.tagCheck=null,bt.attributeCheck=null,de(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?bt.tagCheck=e.ADD_TAGS:M(e.ADD_TAGS)&&(R===ht&&(R=_e(R)),F(R,e.ADD_TAGS,B))),de(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?bt.attributeCheck=e.ADD_ATTR:M(e.ADD_ATTR)&&(z===gt&&(z=_e(z)),F(z,e.ADD_ATTR,B))),de(e,`ADD_FORBID_CONTENTS`)&&M(e.ADD_FORBID_CONTENTS)&&(Vt===Ht&&(Vt=_e(Vt)),F(Vt,e.ADD_FORBID_CONTENTS,B)),Rt&&(R[`#text`]=!0),Dt&&F(R,[`html`,`head`,`body`]),R.table&&(F(R,[`tbody`]),delete vt.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw me(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw me(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=O;O=e.TRUSTED_TYPES_POLICY;try{se=P(``)}catch(e){throw O=t,e}}else e.TRUSTED_TYPES_POLICY===null?(O=void 0,se=``):(O===void 0&&(O=ge()),O&&typeof se==`string`&&(se=P(``)));C&&C(e),cn=e},fn=F({},[...Se,...Ce,...we]),pn=F({},[...Te,...Ee]),mn=function(e,t,n){return t.namespaceURI===Yt?e===`svg`:t.namespaceURI===qt?e===`svg`&&(n===`annotation-xml`||tn[n]):!!fn[e]},hn=function(e,t,n){return t.namespaceURI===Yt?e===`math`:t.namespaceURI===Jt?e===`math`&&rn[n]:!!pn[e]},gn=function(e,t,n){return t.namespaceURI===Jt&&!rn[n]||t.namespaceURI===qt&&!tn[n]?!1:!pn[e]&&(an[e]||!fn[e])},_n=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:Xt,tagName:`template`});let n=ne(e.tagName),r=ne(t.tagName);return Qt[e.namespaceURI]?e.namespaceURI===Jt?mn(n,t,r):e.namespaceURI===qt?hn(n,t,r):e.namespaceURI===Yt?gn(n,t,r):!!(on===`application/xhtml+xml`&&Qt[e.namespaceURI]):!1},vn=function(e){j(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw me(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},yn=function(e,t,n){try{e.removeAttributeNode(t)}catch{try{e.removeAttribute(n)}catch{}}},bn=function(e){Cn(e);let t=h(e);if(t){let e=[];k(t,t=>{j(e,t)}),k(e,e=>{try{p(e)}catch{}})}let n=y(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&yn(e,r,i)}},xn=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}j(t.removed,{attribute:r||null,from:n});try{r?n.removeAttributeNode(r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(Mt||Nt)try{vn(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},Sn=function(e){let t=y(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||z[B(i)]||yn(e,r,i)}},Cn=function(e){let t=[e];for(;t.length>0;){let e=t.pop();E(e)===Ke.element&&Sn(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},wn=function(e,t){return Et?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},Tn=function(e){if(!Et)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=E(e);if(n===Ke.processingInstruction||n===Ke.comment&&pe(Ue,e.data)){try{p(e)}catch{}continue}if(n===Ke.element){let t=e,n=B(D(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&wn(`for`,n)&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},En=function(e){let t=null,r=null;if(jt)e=`<remove></remove>`+e;else{let t=re(e,/^[\r\n\t ]+/);r=t&&t[0]}on===`application/xhtml+xml`&&Xt===Yt&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=O?P(e):e;if(Xt===Yt)try{t=new l().parseFromString(i,on)}catch{}if(!t||!t.documentElement){t=nt.createDocument(Xt,`template`,null);try{t.documentElement.innerHTML=Zt?se:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Xt===Yt?at.call(t,Dt?`html`:`body`)[0]:Dt?t.documentElement:a},Dn=function(e){let t=S?S(e):e.ownerDocument;return rt.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},On=function(e){return e=ie(e,L,` `),e=ie(e,st,` `),e=ie(e,ct,` `),e},kn=function(e){e.normalize();let t=S?S(e):e.ownerDocument,n=rt.call(t||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=On(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&k(i,e=>{jn(e.content)&&kn(e.content)})},An=function(e){let t=x?x(e):null;return typeof t!=`string`||B(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==y(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==b(e)||e.childNodes!==h(e)},jn=function(e){if(!b||typeof e!=`object`||!e)return!1;try{return b(e)===Ke.documentFragment}catch{return!1}},Mn=function(e){if(!b||typeof e!=`object`||!e)return!1;try{return typeof b(e)==`number`}catch{return!1}};function V(e,n,r){e.length!==0&&k(e,e=>{e.call(t,n,r,cn)})}let Nn=function(e,t){return!!(Et&&e.hasChildNodes()&&!Mn(e.firstElementChild)&&pe(He,e.textContent)&&pe(He,e.innerHTML)||Et&&e.namespaceURI===Yt&&Je[t]&&(Mn(e.firstElementChild)||typeof e.textContent==`string`&&pe(Ye[t],e.textContent))||e.nodeType===Ke.processingInstruction||Et&&e.nodeType===Ke.comment&&pe(Ue,e.data))},Pn=function(e,t){return e instanceof RegExp?pe(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},H=function(e,t,n){if(!vt[t]&&W(t)&&Pn(_t.tagNameCheck,t))return!1;if(Rt&&!Vt[t]){let t=g(e),r=h(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?f(r[a],!0):r[a];t.insertBefore(i,m(e))}}}return vn(e),!0},Fn=function(e,t,n,r){return e.length===0?t:t===n||t===r?_e(t):t},In=function(e,t){return e===t||g(e)!==null?!1:(zt&&Cn(e),!0)},Ln=function(e,n){if(V(I.beforeSanitizeElements,e,null),In(e,n))return!0;if(An(e))return vn(e),!0;let r=B(D(e));if(R=Fn(I.uponSanitizeElement,R,ht,kt),V(I.uponSanitizeElement,e,{tagName:r,allowedTags:R}),In(e,n))return!0;if(Nn(e,r))return vn(e),!0;if(vt[r]||!(bt.tagCheck instanceof Function&&bt.tagCheck(r))&&!R[r]){let t=H(e,r,n);return t===!1&&V(I.afterSanitizeElements,e,null),t}if(E(e)===Ke.element&&!_n(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&pe(We,e.innerHTML))return vn(e),!0;if(Tt&&e.nodeType===Ke.text){let n=On(e.textContent);e.textContent!==n&&(j(t.removed,{element:e.cloneNode()}),e.textContent=n)}return V(I.afterSanitizeElements,e,null),!1},U=function(e,t,r){if(yt[t]||wn(t,e)||Ft&&(t===`id`||t===`name`)&&(r in n||r in ln))return!1;let i=z[t]||bt.attributeCheck instanceof Function&&bt.attributeCheck(t,e);return St&&pe(lt,t)||xt&&pe(ut,t)?!0:i?Gt[t]||pe(mt,ie(r,ft,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&ae(r,`data:`)===0&&Ut[e]||Ct&&!pe(dt,ie(r,ft,``))?!0:!r:W(e)&&Pn(_t.tagNameCheck,e)&&Pn(_t.attributeNameCheck,t,e)||t===`is`&&_t.allowCustomizedBuiltInElements&&Pn(_t.tagNameCheck,r)},Rn=F({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),W=function(e){return!Rn[ne(e)]&&pe(pt,e)},zn=function(e,t,n,r){if(O&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return P(r);case`TrustedScriptURL`:return he(r)}return r},Bn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),An(e)?vn(e):ee(t.removed)}catch{xn(n,e)}},Vn=function(e){V(I.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||An(e))return;z=Fn(I.uponSanitizeAttribute,z,gt,At);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0},r=t.length,i=B(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=B(o),u=c,d=o===`value`?u:oe(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,V(I.uponSanitizeAttribute,e,n),d=n.attrValue,It&&(l===`id`||l===`name`)&&ae(d,Lt)!==0&&(xn(o,e,a),d=Lt+d),Et&&pe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){xn(o,e,a);continue}if(l===`attributename`&&re(d,`href`)){xn(o,e,a);continue}if(!n.forceKeepAttr){if(!n.keepAttr){xn(o,e,a);continue}if(!wt&&pe(Ge,d)){xn(o,e,a);continue}if(Tt&&(d=On(d)),!U(i,l,d)){xn(o,e,a);continue}d=zn(i,l,s,d),d!==u&&Bn(e,o,s,d)}}V(I.afterSanitizeAttributes,e,null)},Hn=function(e){let t=null,n=Dn(e);for(V(I.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(V(I.uponSanitizeShadowNode,t,null),Ln(t,e),Vn(t),jn(t.content)&&Hn(t.content),E(t)===Ke.element){let e=_(t);jn(e)&&(Un(e),Hn(e))}V(I.afterSanitizeShadowDOM,e,null)},Un=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Hn(e.shadow);continue}let n=e.node,r=E(n)===Ke.element,i=h(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=x?x(n):null;if(typeof e==`string`&&B(e)===`template`){let e=n.content;jn(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);jn(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Zt=!e,Zt&&(e=`<!-->`),typeof e!=`string`&&!Mn(e)&&(e=ve(e),typeof e!=`string`))throw me(`dirty is not a string, aborting`);if(!t.isSupported)return e;Ot?(R=kt,z=At):dn(n),(I.uponSanitizeElement.length>0||I.uponSanitizeAttribute.length>0)&&(R=_e(R)),I.uponSanitizeAttribute.length>0&&(z=_e(z)),t.removed=[];let c=zt&&typeof e!=`string`&&Mn(e);if(c){Tn(e);let t=D(e);if(typeof t==`string`){let n=B(t);if(!R[n]||vt[n])throw bn(e),me(`root node is forbidden and cannot be sanitized in-place`)}if(An(e))throw bn(e),me(`root node is clobbered and cannot be sanitized in-place`);try{Un(e)}catch(t){throw bn(e),t}}else if(Mn(e))i=En(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===Ke.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Un(a);else{if(!Mt&&!Tt&&!Dt&&e.indexOf(`<`)===-1)return O&&Pt?P(e):e;if(i=En(e),!i)return Mt?null:Pt?se:``}i&&jt&&vn(i.firstChild);let l=c?e:i;try{let e=Dn(l);for(;o=e.nextNode();)Ln(o,l),Vn(o),jn(o.content)&&Hn(o.content)}catch(n){throw c&&(bn(e),k(t.removed,e=>{e.element&&Cn(e.element)})),n}if(c)return k(t.removed,e=>{e.element&&Cn(e.element)}),Tt&&kn(e),e;if(Mt){if(Tt&&kn(i),Nt)for(s=it.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(z.shadowroot||z.shadowrootmode)&&(s=ot.call(r,s,!0)),s}let u=Dt?i.outerHTML:i.innerHTML;return Dt&&R[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&pe(Be,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
3
+ `+u),Tt&&(u=On(u)),O&&Pt?P(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};dn(e),Ot=!0,kt=R,At=z},t.clearConfig=function(){cn=null,Ot=!1,kt=null,At=null,O=ce,se=``},t.isValidAttribute=function(e,t,n){cn||dn({});let r=B(e),i=B(t);return U(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&de(I,e)&&j(I[e],t)},t.removeHook=function(e,t){if(de(I,e)){if(t!==void 0){let n=A(I[e],t);return n===-1?void 0:te(I[e],n,1)[0]}return ee(I[e])}},t.removeHooks=function(e){de(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=Qe()},t}var nt=tt();function rt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var it=rt();function at(e){it=e}var ot={exec:()=>null};function I(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function L(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(ct.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var st=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),ct={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:I(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:I(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:I(e=>RegExp(`^ {0,${e}}>`))},lt=/^(?:[ \t]*(?:\n|$))+/,ut=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,dt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ft=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,pt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,mt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,R=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ht=L(R).replace(/bull/g,mt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),z=L(R).replace(/bull/g,mt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),gt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,_t=/^[^\n]+/,vt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,yt=L(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,vt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),bt=L(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,mt).getRegex(),xt=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,St=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ct=L(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,St).replace(`tag`,xt).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),wt=e=>L(gt).replace(`hr`,ft).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,xt).getRegex(),Tt=wt(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Et=wt(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Dt={blockquote:L(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Et).getRegex(),code:ut,def:yt,fences:dt,heading:pt,hr:ft,html:Ct,lheading:ht,list:bt,newline:lt,paragraph:Tt,table:ot,text:_t},Ot=L(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,ft).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,xt).getRegex(),kt={...Dt,lheading:z,table:Ot,paragraph:L(gt).replace(`hr`,ft).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ot).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,xt).getRegex()},At={...Dt,html:L(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,St).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ot,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:L(gt).replace(`hr`,ft).replace(`heading`,` *#{1,6} *[^
4
+ ]`).replace(`lheading`,ht).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},jt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Mt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Nt=/^( {2,}|\\)\n(?!\s*$)/,Pt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ft=/[\p{P}\p{S}]/u,It=/[\s\p{P}\p{S}]/u,Lt=/[^\s\p{P}\p{S}]/u,Rt=L(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,It).getRegex(),zt=/[\p{Pi}\p{Ps}"']/u,Bt=/(?!~)[\p{P}\p{S}]/u,Vt=/(?!~)[\s\p{P}\p{S}]/u,Ht=/(?:[^\s\p{P}\p{S}]|~)/u,Ut=L(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,st?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Wt=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Gt=L(Wt,`u`).replace(/punct/g,Ft).getRegex(),Kt=L(Wt,`u`).replace(/punct/g,Bt).getRegex(),qt=L(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,zt).replace(/punct/g,Ft).getRegex(),Jt=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Yt=L(Jt,`gu`).replace(/notPunctSpace/g,Lt).replace(/punctSpace/g,It).replace(/punct/g,Ft).getRegex(),Xt=L(Jt,`gu`).replace(/notPunctSpace/g,Ht).replace(/punctSpace/g,Vt).replace(/punct/g,Bt).getRegex(),Zt=L(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Lt).replace(/punctSpace/g,It).replace(/punct/g,Ft).getRegex(),Qt=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Lt).replace(/punctSpace/g,It).replace(/punct/g,Ft).getRegex(),$t=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Lt).replace(/punctSpace/g,It).replace(/punct/g,Ft).getRegex(),en=L(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Ft).getRegex(),tn=L(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Lt).replace(/punctSpace/g,It).replace(/punct/g,Ft).getRegex(),nn=L(/\\(punct)/,`gu`).replace(/punct/g,Ft).getRegex(),rn=L(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),an=L(St).replace(`(?:-->|$)`,`-->`).getRegex(),on=L(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,an).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),sn=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,B=L(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,sn).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),cn=L(/^!?\[(label)\]\[(ref)\]/).replace(`label`,sn).replace(`ref`,vt).getRegex(),ln=L(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,vt).getRegex(),un=L(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,cn).replace(`nolink`,ln).getRegex(),dn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,fn={_backpedal:ot,anyPunctuation:nn,autolink:rn,blockSkip:Ut,br:Nt,code:Mt,del:ot,delLDelim:ot,delRDelim:ot,emStrongLDelim:Gt,emStrongRDelimAst:Yt,emStrongRDelimUnd:Qt,escape:jt,link:B,nolink:ln,punctuation:Rt,reflink:cn,reflinkSearch:un,tag:on,text:Pt,url:ot},pn={...fn,emStrongLDelim:qt,emStrongRDelimAst:Zt,emStrongRDelimUnd:$t,link:L(/^!?\[(label)\]\((.*?)\)/).replace(`label`,sn).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,sn).getRegex()},mn={...fn,emStrongRDelimAst:Xt,emStrongLDelim:Kt,delLDelim:en,delRDelim:tn,url:L(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,dn).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:L(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,dn).getRegex()},hn={...mn,br:L(Nt).replace(`{2,}`,`*`).getRegex(),text:L(mn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},gn={normal:Dt,gfm:kt,pedantic:At},_n={normal:fn,gfm:mn,breaks:hn,pedantic:pn},vn={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},yn=e=>vn[e];function bn(e,t){if(t){if(ct.escapeTest.test(e))return e.replace(ct.escapeReplace,yn)}else if(ct.escapeTestNoEncode.test(e))return e.replace(ct.escapeReplaceNoEncode,yn);return e}function xn(e){try{e=encodeURI(e).replace(ct.percentDecode,`%`)}catch{return null}return e}function Sn(e,t){let n=e.replace(ct.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(ct.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(ct.slashPipe,`|`);return n}function Cn(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function wn(e){let t=e.split(`
5
+ `),n=t.length-1;for(;n>=0&&ct.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
6
+ `)}function Tn(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function En(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Dn(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function On(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
7
+ `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
8
+ `)}var kn=class{options;rules;lexer;constructor(e){this.options=e||it}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:wn(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=On(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Cn(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Cn(t[0],`
9
+ `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Cn(t[0],`
10
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Cn(t[0],`
11
+ `).split(`
12
+ `),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
13
+ `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
14
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
15
+ ${s}`:s,r=r?`${r}
16
+ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`)break;if(u?.type===`blockquote`){let t=u,a=e.join(`
17
+ `),o=t.raw+`
18
+ `+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s,n=`${n}
19
+ ${a}`,r=r.substring(0,r.length-t.text.length)+s.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
20
+ `+e.join(`
21
+ `),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
22
+ `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=En(t[2].split(`
23
+ `,1)[0],t[1].length),l=e.split(`
24
+ `,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
25
+ `,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
26
+ `,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
27
+ `+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
28
+ `+l}u=!l.trim(),r+=p+`
29
+ `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items)if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}for(let e of i.items){let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=wn(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:Cn(t[0],`
30
+ `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Sn(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
31
+ `):[],a={type:`table`,raw:Cn(t[0],`
32
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Sn(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Cn(t[0],`
33
+ `),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
34
+ `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Cn(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Tn(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Dn(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Dn(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,o,s=i,c=0,l=r[0][0],u=n===l,d=l===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){s+=o;continue}if(r[5]||r[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let t=[...r[0]][0].length,n=e.slice(0,i+r.index+t+o);if(Math.min(i,o)%2){let e=n.slice(1,-1);return{type:`em`,raw:n,text:e,tokens:this.lexer.inlineTokens(e)}}let l=n.slice(2,-2);return{type:`strong`,raw:n,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},An=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||it,this.options.tokenizer=this.options.tokenizer||new kn,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:ct,block:gn.normal,inline:_n.normal};this.options.pedantic?(t.block=gn.pedantic,t.inline=_n.pedantic):this.options.gfm&&(t.block=gn.gfm,t.inline=this.options.breaks?_n.breaks:_n.gfm),this.tokenizer.rules=t}static get rules(){return{block:gn,inline:_n}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(ct.carriageReturn,`
35
+ `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(ct.tabCharGlobal,` `).replace(ct.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
36
+ `:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
37
+ `)?``:`
38
+ `)+i.raw,n.text+=`
39
+ `+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
40
+ `)?``:`
41
+ `)+i.raw,n.text+=`
42
+ `+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
43
+ `)?``:`
44
+ `)+i.raw,r.text+=`
45
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
46
+ `)?``:`
47
+ `)+i.raw,n.text+=`
48
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links){let e=Object.keys(this.tokens.links);e.length>0&&(n=n.replace(this.tokenizer.rules.inline.reflinkSearch,t=>e.includes(t.slice(t.lastIndexOf(`[`)+1,-1))?`[`+`a`.repeat(t.length-2)+`]`:t))}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,e=>`+`.repeat(e.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(e,t,n)=>{let r=n?n.length:0;return e.slice(0,r)+`[`+`a`.repeat(e.length-r-2)+`]`}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,i=``,a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(i=``),r=!1;let o;if(this.options.extensions?.inline?.some(n=>(o=n.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let n=t.at(-1);o.type===`text`&&n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(s)){e=e.substring(o.raw.length),o.raw.slice(-1)!==`_`&&(i=o.raw.slice(-1)),r=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},jn=class{options;parser;constructor(e){this.options=e||it}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(ct.notSpaceStart)?.[0],i=e.replace(ct.endingNewline,``)+`
49
+ `;return r?`<pre><code class="language-`+bn(r)+`">`+(n?i:bn(i,!0))+`</code></pre>
50
+ `:`<pre><code>`+(n?i:bn(i,!0))+`</code></pre>
51
+ `}blockquote({tokens:e}){return`<blockquote>
52
+ ${this.parser.parse(e)}</blockquote>
53
+ `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
54
+ `}hr(e){return`<hr>
55
+ `}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t<e.items.length;t++){let n=e.items[t];r+=this.listitem(n)}let i=t?`ol`:`ul`,a=t&&n!==1?` start="`+n+`"`:``;return`<`+i+a+`>
56
+ `+r+`</`+i+`>
57
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
58
+ `}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox"> `}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
59
+ `}table(e){let t=``,n=``;for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r=``;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n=``;for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&=`<tbody>${r}</tbody>`,`<table>
60
+ <thead>
61
+ `+t+`</thead>
62
+ `+r+`</table>
63
+ `}tablerow({text:e}){return`<tr>
64
+ ${e}</tr>
65
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
66
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${bn(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=xn(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+bn(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=xn(e);if(i===null)return bn(n);e=i;let a=`<img src="${e}" alt="${bn(n)}"`;return t&&(a+=` title="${bn(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:bn(e.text)}},Mn=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},V=class e{options;renderer;textRenderer;constructor(e){this.options=e||it,this.options.renderer=this.options.renderer||new jn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Mn}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},Nn=class{options;block;constructor(e){this.options=e||it}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?An.lex:An.lexInline}provideParser(e=this.block){return e?V.parse:V.parseInline}},Pn=new class{defaults=rt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=V;Renderer=jn;TextRenderer=Mn;Lexer=An;Tokenizer=kn;Hooks=Nn;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new jn(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new kn(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Nn;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=Nn.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Nn.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return An.lex(e,t??this.defaults)}parser(e,t){return V.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?An.lex:An.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?V.parse:V.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?An.lex:An.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?V.parse:V.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
67
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+bn(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function H(e,t){return Pn.parse(e,t)}H.options=H.setOptions=function(e){return Pn.setOptions(e),H.defaults=Pn.defaults,at(H.defaults),H},H.getDefaults=rt,H.defaults=it;function Fn(...e){return Pn.use(...e),H.defaults=Pn.defaults,at(H.defaults),H}H.use=Fn,H.walkTokens=function(e,t){return Pn.walkTokens(e,t)},H.parseInline=Pn.parseInline,H.Parser=V,H.parser=V.parse,H.Renderer=jn,H.TextRenderer=Mn,H.Lexer=An,H.lexer=An.lex,H.Tokenizer=kn,H.Hooks=Nn,H.parse=H,H.options,H.setOptions,H.walkTokens,H.parseInline,V.parse,An.lex;var In=/^\[(?:([^\n[\]<>]*)<([^\n[\]<>]+)>)? ?((?:\d{4}-\d{2}-\d{2} )?\d{1,2}:\d{2})?\]\n/;function Ln(e){let t=In.exec(e);return!t?.[2]&&!t?.[3]?{text:e}:{...t[1]?{name:t[1]}:{},...t[2]?{id:t[2]}:{},...t[3]?{when:t[3]}:{},text:e.slice(t[0].length)}}var U=e=>{let t=document.querySelector(e);if(!t)throw Error(`missing element: ${e}`);return t};function Rn(e){let t=Math.round((Date.now()-e)/6e4);return t<1?`now`:t<60?`${t}m`:t<1440?`${Math.round(t/60)}h`:`${Math.round(t/1440)}d`}function W(e,t,...n){let r=document.createElement(e);return t&&(r.className=t),r.append(...n),r}function zn(e){if(!e)return e;let{name:t,id:n,text:r}=Ln(e),i=t??n;if(!i&&r===e)return e;let a=r.replace(/\s+/g,` `).trim();return i?`${i}: ${a}`:a||e}var Bn=e=>e.split(`/`).filter(Boolean).pop()??e;function Vn(e){let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Hn(e,t,n){return{visible:!1,show(n){this.visible=!0,e.classList.remove(`hidden`),e.classList.add(`flex`),t(n)},hide(){n?.(),this.visible=!1,e.classList.add(`hidden`),e.classList.remove(`flex`)}}}function Un(e){let t=W(`span`,`help`);return t.innerHTML=nt.sanitize(H.parseInline(e,{async:!1})),Wn(t),t}function Wn(e){for(let t of e.querySelectorAll(`a`))(t.getAttribute(`href`)??``).startsWith(`#`)||(t.target=`_blank`,t.rel=`noreferrer`)}async function Gn(e){if(navigator.clipboard)return navigator.clipboard.writeText(e);let t=document.createElement(`textarea`);t.value=e,t.className=`fixed opacity-0`,document.body.append(t),t.select();let n=document.execCommand(`copy`);if(t.remove(),!n)throw Error(`clipboard unavailable`)}function Kn(e,t){let n=W(`button`,e,`Copy`);n.title=`Copy to clipboard`;let r;return n.onclick=async e=>{e.stopPropagation(),n.textContent=await Gn(t()).then(()=>`Copied`,()=>`Failed`),clearTimeout(r),r=setTimeout(()=>n.textContent=`Copy`,1200)},n}function qn(e,t){let n=document.createElement(`details`);n.className=e;let r=W(`summary`,`flex cursor-pointer select-none items-center gap-1.5`);return r.append(W(`span`,`chev`,`▶`),...t),n.append(r),{el:n,summary:r}}var Jn=`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,G=(e,t=!1)=>Yn(e,`${t?`btn btn-primary`:`btn`} text-[12.5px]`),Yn=(e,t=``)=>{let n=W(`button`,t,e);return n.type=`button`,n};function Xn(e,t,n){let r=G(e);return t&&r.classList.add(`bg-neutral-200`),r.onclick=n,r}function Zn(e,t,n){let r=Yn(e,`flex cursor-pointer items-center gap-1.5 rounded-full px-3 py-1 text-[13px] transition-colors ${t?`bg-indigo-50 font-medium text-indigo-700 ring-1 ring-indigo-200/70`:`text-neutral-600 hover:bg-neutral-100`}`);return r.onclick=n,r}function Qn(e,t,...n){let r=W(`section`,`rounded-xl border border-neutral-200 bg-white shadow-xs`),i=W(`div`,`rounded-t-xl border-b border-neutral-200/70 bg-neutral-50/70 px-4 py-2.5`);return i.append(W(`h2`,`text-[13px] font-semibold text-neutral-700`,e)),t&&i.append(W(`p`,`mt-0.5 text-[11.5px] leading-snug text-neutral-500`,t)),r.append(i,W(`div`,`flex flex-col gap-4 px-4 py-3.5`,...n)),r}function K(e,t,n={}){let r=W(`div`,`flex flex-col gap-1.5`),i=W(`div`,`flex items-center gap-1.5`,W(`span`,Jn,e));return n.help&&i.append(n.help),r.append(i,t),n.hint&&r.append(W(`span`,`text-[11.5px] leading-snug text-neutral-400`,n.hint)),r}var $n=`w-full rounded-lg border border-neutral-300 bg-white px-2.5 py-1.5 text-[12.5px] transition-colors placeholder:text-neutral-400 focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100 focus:outline-none`,er=(e,t,n,r=!1)=>{let i=document.createElement(`input`);return i.className=r?`${$n} font-mono`:$n,i.value=e,i.placeholder=t,i.oninput=()=>n(i.value),i},q=(e=``,t=`text`)=>{let n=document.createElement(`input`);return n.type=t,n.className=$n,n.value=e,n},tr=(e,t)=>{let n=document.createElement(`select`);return n.className=`${$n} select`,n.append(...e.map(([e,t])=>new Option(e,t))),n.value=t,n},nr=(e=``,t=4)=>{let n=document.createElement(`textarea`);return n.className=`${$n} resize-y font-mono`,n.value=e,n.rows=t,n.spellcheck=!1,n};function rr(e,t,n,r,i){let a=document.createElement(`input`);a.type=`checkbox`,a.className=`peer sr-only`,a.checked=n,a.onchange=()=>r(a.checked);let o=W(`span`,`relative h-4 w-7 flex-none rounded-full bg-neutral-300 transition-colors after:absolute after:left-0.5 after:top-0.5 after:h-3 after:w-3 after:rounded-full after:bg-white after:shadow-sm after:transition-transform peer-checked:bg-indigo-600 peer-checked:after:translate-x-3 peer-focus-visible:ring-2 peer-focus-visible:ring-indigo-200`),s=W(`label`,`flex cursor-pointer gap-2.5 ${e?`items-start`:`items-center`}`);if(s.append(a,o),e){let n=W(`span`,`flex items-center gap-1.5`,W(`span`,`text-[13px] text-neutral-700`,e));i&&n.append(i);let r=W(`span`,`flex min-w-0 flex-col`,n);t&&r.append(W(`span`,`text-[11.5px] leading-snug text-neutral-400`,t)),s.append(r)}return s}var ir={idle:`text-neutral-400`,saving:`text-neutral-400`,saved:`text-green-700`,failed:`text-red-600`};function J(e,t,n){e.className=`text-[11.5px] ${ir[t]}`,e.textContent=n}var ar=(e,t)=>W(`span`,`flex-none rounded-full px-1.5 py-px text-[10px] font-medium uppercase tracking-wide ring-1 ${t}`,e),or=e=>W(`p`,`rounded-lg border border-dashed border-neutral-200 px-3 py-4 text-center text-[12.5px] text-neutral-400`,e);function sr(e,t,n=`left`){let r=W(`span`,`group relative inline-flex`),i=Yn(`?`,`flex h-4 w-4 cursor-help items-center justify-center rounded-full border border-neutral-300 text-[9px] font-bold text-neutral-400 transition-colors group-hover:border-indigo-400 group-hover:text-indigo-500`),a=W(`span`,`absolute ${n===`right`?`right-0`:`left-0`} top-full z-20 hidden w-[min(27rem,calc(100vw-3rem))] pt-1.5 group-hover:block`),o=W(`span`,`flex flex-col gap-2 rounded-xl border border-neutral-200 bg-white p-3.5 text-[12px] font-normal normal-case leading-[1.55] tracking-normal text-neutral-600 shadow-xl`);o.append(W(`span`,`text-[12.5px] font-semibold text-neutral-800`,e));let s=W(`ol`,`flex list-decimal flex-col gap-1.5 pl-4`);for(let e of t){let t=W(`li`,`marker:text-neutral-400`);t.append(typeof e==`string`?Un(e):e),s.append(t)}return o.append(s),a.append(o),i.onclick=()=>{let e=a.classList.contains(`hidden`);a.classList.toggle(`hidden`,!e),a.classList.toggle(`block`,e),i.classList.toggle(`border-indigo-400`,e),i.classList.toggle(`text-indigo-500`,e)},r.append(i,a),r}var cr=(e,t)=>W(`span`,`flex flex-col gap-1`,Un(e),t),lr=/[\u201c\u201d"\u2018\u2019'()\uff08\uff09\u300c\u300d\u300e\u300f\u3010\u3011\u300a\u300b\u3008\u3009[\]]/;function ur(e){let t=[],n=e=>`\uE010${t.push(e)-1}\uE011`,r=e.replace(/```[\s\S]*?```/g,e=>n(e)).replace(/`[^`\n]+`/g,e=>n(e));return r=r.replace(/\*\*(\S|\S[\s\S]*?\S)\*\*/g,(e,t)=>{let n=``,r=``,i=t;for(;i.length>1&&lr.test(i[0]);)n+=i[0],i=i.slice(1);for(;i.length>1&&lr.test(i.at(-1));)r=i.at(-1)+r,i=i.slice(0,-1);return n||r?`${n}**${i}**${r}`:e}),r.replace(/\uE010(\d+)\uE011/g,(e,n)=>t[Number(n)]??``)}var dr=e=>!e.text.trim()&&e.suggestions.length===0,fr=e=>e===`xhigh`?`Extra high`:e[0].toUpperCase()+e.slice(1),pr=e=>{if(e<1e3)return String(e);let t=e/1e3;return t>=9.95?`${Math.round(t)}K`:`${t.toFixed(1)}K`};function mr(e){let t=Math.max(1,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`}var hr=e=>`${mr(e.durationMs)} · ${pr(e.tokens)} tok`,gr=/(?:^|\n)[ \t]*-{3,}[ \t]*\r?\n((?:[ \t]*\[[^\]\r\n]+\][ \t]*(?:[||][ \t]*)?)+)\s*$/,_r=/\[([^\]\r\n]+)\]/g,vr=5,yr=/<silent>([\s\S]*?)<\/silent>/gi;function br(e){let t=[...e.matchAll(yr)].map(e=>(e[1]??``).trim()).filter(Boolean);return t.length?t.join(` · `):void 0}function xr(e,t){let n=ur(e.replace(yr,``).trim()),r=br(e),i=gr.exec(n);if(!i?.[1])return{text:n,suggestions:[],meta:t,silence:r};let a=[...i[1].matchAll(_r)].map(e=>(e[1]??``).trim()).filter(Boolean).slice(0,vr);return a.length?{text:n.slice(0,i.index).trimEnd(),suggestions:a,meta:t,silence:r}:{text:n,suggestions:[],meta:t,silence:r}}var Sr=U(`#image-dialog`),Cr=U(`#image-full`),wr=U(`#image-prev`),Tr=U(`#image-next`),Er=[],Dr=0;function Or(e){Er.length<2||(Dr=(Dr+e+Er.length)%Er.length,Cr.src=Er[Dr])}function kr(e){let t=e.closest(`[data-gallery]`);Er=t?[...t.querySelectorAll(`img.thumb`)].map(e=>e.src):[e.src],Dr=Math.max(0,Er.indexOf(e.src)),Cr.src=e.src;let n=Er.length<2?`none`:`flex`;wr.style.display=n,Tr.style.display=n,Sr.showModal()}Sr.onclick=()=>Sr.close();var Ar=(e,t)=>{e.onclick=e=>{e.stopPropagation(),Or(t)}};Ar(wr,-1),Ar(Tr,1),Sr.onkeydown=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),Or(e.key===`ArrowLeft`?-1:1))};function jr(e){let t=e.querySelector(`:scope > .thumbs`);if(t)return t;let n=W(`div`,`thumbs`);return e.append(n),n}function Mr(e){let t=document.createElement(`img`);return t.src=e,t.loading=`lazy`,t.className=`thumb`,t.onclick=()=>kr(t),t}var Nr=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`]),Pr=new Set([`txt`,`md`,`log`,`json`,`csv`,`yaml`,`yml`]),Fr=524288,Ir=U(`#file-dialog`),Lr=U(`#file-name`),Rr=U(`#file-text`),zr=U(`#file-download`);U(`#file-close`).onclick=()=>Ir.close();var Br=e=>e.split(`.`).pop()?.toLowerCase()??``,Vr=(e,t,n=!1)=>`/api/sessions/${encodeURIComponent(e)}/files?path=${encodeURIComponent(t)}${n?`&download=1`:``}`;function Hr(e,t){return e.replace(/\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)/g,(e,n)=>{let r=n;try{r=decodeURIComponent(n)}catch{}return`](${Vr(t,r)})`})}var Ur=e=>/^\/api\/sessions\/[^/]+\/files\?/.test(e);function Wr(e,t){let n=Bn(t)||`file`,r=Vr(e,t);return Nr.has(Br(n))?qr(r,n):Jr(r,n)}function Gr(e){return new URLSearchParams(e.slice(e.indexOf(`?`)+1)).get(`path`)??``}async function Kr(e,t){Lr.textContent=t,zr.href=`${e}&download=1`,Rr.textContent=`loading…`,Ir.showModal();let n=await fetch(e),r=n.ok?await n.text():`failed to load: ${n.status}`;Rr.textContent=r.length>Fr?`${r.slice(0,Fr)}\n…`:r}function qr(e,t){let n=Mr(e);return n.alt=t,n}function Jr(e,t){let n=Br(t),r=W(`span`,`inline-flex max-w-full items-center gap-2.5 rounded-lg border border-neutral-200 bg-neutral-50 px-2.5 py-1.5 no-underline`),i=W(`span`,`flex h-7 w-7 flex-none items-center justify-center rounded-md bg-indigo-50 text-[10px] font-semibold uppercase text-indigo-600`,n.slice(0,4)||`file`),a=W(`span`,`min-w-0 truncate text-[13px] font-medium text-neutral-800`,t),o=W(`span`,`ml-1 flex flex-none items-center gap-0.5`);if(Pr.has(n)||n===`pdf`){let r=W(`button`,`icon-btn h-6 w-6 text-[13px]`,`◉`);r.title=`Preview`,r.onclick=r=>{r.preventDefault(),n===`pdf`?window.open(e,`_blank`,`noopener`):Kr(e,t)},o.append(r)}let s=document.createElement(`a`);return s.className=`icon-btn h-6 w-6 text-[13px] no-underline`,s.href=`${e}&download=1`,s.download=t,s.title=`Download`,s.textContent=`↓`,o.append(s),r.append(i,a,o),r}function Yr(e){let t=new Set;for(let n of e)n.parentElement&&t.add(n.parentElement);for(let n of t){let t=[...n.children].filter(t=>e.includes(t));if([...n.childNodes].every(e=>e.nodeType===Node.TEXT_NODE?!e.textContent?.trim():t.includes(e))){n.classList.add(`thumbs`);continue}let r=W(`div`,`thumbs`);r.append(...t),n.after(r)}}function Xr(e){let t=[];for(let n of e.querySelectorAll(`img`)){let e=n.getAttribute(`src`)??``;if(!Ur(e))continue;let r=qr(e,Bn(Gr(e)));n.replaceWith(r),t.push(r)}for(let n of e.querySelectorAll(`a`)){let e=n.getAttribute(`href`)??``;if(!Ur(e))continue;let r=Bn(Gr(e))||n.textContent?.trim()||`file`,i=Nr.has(Br(r))?qr(e,r):Jr(e,r);n.replaceWith(i),t.push(i)}t.length&&Yr(t)}var Zr=e=>`[${e.split(`/`).pop()??`file`}](file://${encodeURI(e).replace(/\(/g,`%28`).replace(/\)/g,`%29`)})`,Qr=/^\[[^\]\n]*\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)$/;function $r(e){let t=e.split(`
68
+ `),n=t.length;for(;n>0&&Qr.test(t[n-1].trim());)n--;let r=t.slice(n).map(e=>{let t=Qr.exec(e.trim())[1];try{return decodeURIComponent(t)}catch{return t}});return{text:t.slice(0,n).join(`
69
+ `).trimEnd(),paths:r}}var ei=c(o(((e,t)=>{function n(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw Error(`map is read-only`)}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw Error(`set is read-only`)}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{let r=e[t],i=typeof r;(i===`object`||i===`function`)&&!Object.isFrozen(r)&&n(r)}),e}var r=class{constructor(e){e.data===void 0&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function i(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#x27;`)}function a(e,...t){let n=Object.create(null);for(let t in e)n[t]=e[t];return t.forEach(function(e){for(let t in e)n[t]=e[t]}),n}var o=`</span>`,s=e=>!!e.scope,c=(e,{prefix:t})=>{if(e.startsWith(`language:`))return e.replace(`language:`,`language-`);if(e.includes(`.`)){let n=e.split(`.`);return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${`_`.repeat(t+1)}`)].join(` `)}return`${t}${e}`},l=class{constructor(e,t){this.buffer=``,this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=i(e)}openNode(e){if(!s(e))return;let t=c(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){s(e)&&(this.buffer+=o)}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}},u=(e={})=>{let t={children:[]};return Object.assign(t,e),t},d=class e{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){let t=u({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return typeof t==`string`?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(t){typeof t!=`string`&&t.children&&(t.children.every(e=>typeof e==`string`)?t.children=[t.children.join(``)]:t.children.forEach(t=>{e._collapse(t)}))}},f=class extends d{constructor(e){super(),this.options=e}addText(e){e!==``&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){let n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function p(e){return e?typeof e==`string`?e:e.source:null}function m(e){return _(`(?=`,e,`)`)}function h(e){return _(`(?:`,e,`)*`)}function g(e){return _(`(?:`,e,`)?`)}function _(...e){return e.map(e=>p(e)).join(``)}function v(e){let t=e[e.length-1];return typeof t==`object`&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function y(...e){return`(`+(v(e).capture?``:`?:`)+e.map(e=>p(e)).join(`|`)+`)`}function b(e){return RegExp(e.toString()+`|`).exec(``).length-1}function x(e,t){let n=e&&e.exec(t);return n&&n.index===0}var S=new RegExp(y(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function C(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;let t=n,r=p(e),i=``;for(;r.length>0;){let e=S.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),e[0][0]===`\\`&&e[1]?i+=`\\`+String(Number(e[1])+t):(i+=e[0],(e[0]===`(`||/^\(\?[<']/.test(e[0]))&&n++)}return i}).map(e=>`(${e})`).join(t)}var w=/\b\B/,T=`[a-zA-Z]\\w*`,E=`[a-zA-Z_]\\w*`,D=`\\b\\d+(\\.\\d+)?`,O=`(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)`,k=`\\b(0b[01]+)`,A=`!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~`,ee=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=_(t,/.*\b/,e.binary,/\b.*/)),a({scope:`meta`,begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{e.index!==0&&t.ignoreMatch()}},e)},j={begin:`\\\\[\\s\\S]`,relevance:0},te={scope:`string`,begin:`'`,end:`'`,illegal:`\\n`,contains:[j]},M={scope:`string`,begin:`"`,end:`"`,illegal:`\\n`,contains:[j]},ne={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},N=function(e,t,n={}){let r=a({scope:`comment`,begin:e,end:t,contains:[]},n);r.contains.push({scope:`doctag`,begin:`[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)`,end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});let i=y(`I`,`a`,`is`,`so`,`us`,`to`,`at`,`if`,`in`,`it`,`on`,/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return r.contains.push({begin:_(/[ ]+/,`(`,i,/[.]?[:]?([.][ ]|[ ])/,`){3}`)}),r},re=N(`//`,`$`),ie=N(`/\\*`,`\\*/`),ae=N(`#`,`$`),oe=Object.freeze({__proto__:null,APOS_STRING_MODE:te,BACKSLASH_ESCAPE:j,BINARY_NUMBER_MODE:{scope:`number`,begin:k,relevance:0},BINARY_NUMBER_RE:k,COMMENT:N,C_BLOCK_COMMENT_MODE:ie,C_LINE_COMMENT_MODE:re,C_NUMBER_MODE:{scope:`number`,begin:O,relevance:0},C_NUMBER_RE:O,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:ae,IDENT_RE:T,MATCH_NOTHING_RE:w,METHOD_GUARD:{begin:`\\.\\s*[a-zA-Z_]\\w*`,relevance:0},NUMBER_MODE:{scope:`number`,begin:D,relevance:0},NUMBER_RE:D,PHRASAL_WORDS_MODE:ne,QUOTE_STRING_MODE:M,REGEXP_MODE:{scope:`regexp`,begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[j,{begin:/\[/,end:/\]/,relevance:0,contains:[j]}]},RE_STARTERS_RE:A,SHEBANG:ee,TITLE_MODE:{scope:`title`,begin:T,relevance:0},UNDERSCORE_IDENT_RE:E,UNDERSCORE_TITLE_MODE:{scope:`title`,begin:E,relevance:0}});function se(e,t){e.input[e.index-1]===`.`&&t.ignoreMatch()}function ce(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function le(e,t){t&&e.beginKeywords&&(e.begin=`\\b(`+e.beginKeywords.split(` `).join(`|`)+`)(?!\\.)(?=\\b|\\s)`,e.__beforeBegin=se,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function ue(e,t){Array.isArray(e.illegal)&&(e.illegal=y(...e.illegal))}function de(e,t){if(e.match){if(e.begin||e.end)throw Error(`begin & end are not supported with match`);e.begin=e.match,delete e.match}}function fe(e,t){e.relevance===void 0&&(e.relevance=1)}var pe=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw Error(`beforeMatch cannot be used with starts`);let n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=_(n.beforeMatch,m(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},me=[`of`,`and`,`for`,`in`,`not`,`or`,`if`,`then`,`parent`,`list`,`value`],P=`keyword`;function he(e,t,n=P){let r=Object.create(null);return typeof e==`string`?i(n,e.split(` `)):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,he(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){let n=t.split(`|`);r[n[0]]=[e,F(n[0],n[1])]})}}function F(e,t){return t?Number(t):+!ge(e)}function ge(e){return me.includes(e.toLowerCase())}var _e={},ve=e=>{console.error(e)},ye=(e,...t)=>{console.log(`WARN: ${e}`,...t)},be=(e,t)=>{_e[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),_e[`${e}/${t}`]=!0)},xe=Error();function Se(e,t,{key:n}){let r=0,i=e[n],a={},o={};for(let e=1;e<=t.length;e++)o[e+r]=i[e],a[e+r]=!0,r+=b(t[e-1]);e[n]=o,e[n]._emit=a,e[n]._multi=!0}function Ce(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw ve(`skip, excludeBegin, returnBegin not compatible with beginScope: {}`),xe;if(typeof e.beginScope!=`object`||e.beginScope===null)throw ve(`beginScope must be object`),xe;Se(e,e.begin,{key:`beginScope`}),e.begin=C(e.begin,{joinWith:``})}}function we(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw ve(`skip, excludeEnd, returnEnd not compatible with endScope: {}`),xe;if(typeof e.endScope!=`object`||e.endScope===null)throw ve(`endScope must be object`),xe;Se(e,e.end,{key:`endScope`}),e.end=C(e.end,{joinWith:``})}}function Te(e){e.scope&&typeof e.scope==`object`&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function Ee(e){Te(e),typeof e.beginScope==`string`&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope==`string`&&(e.endScope={_wrap:e.endScope}),Ce(e),we(e)}function De(e){function t(t,n){return new RegExp(p(t),`m`+(e.case_insensitive?`i`:``)+(e.unicodeRegex?`u`:``)+(n?`g`:``))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=b(e)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let e=this.regexes.map(e=>e[1]);this.matcherRe=t(C(e,{joinWith:`|`}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;let t=this.matcherRe.exec(e);if(!t)return null;let n=t.findIndex((e,t)=>t>0&&e!==void 0),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class r{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];let t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),t.type===`begin`&&this.count++}exec(e){let t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition()&&!(n&&n.index===this.lastIndex)){let t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}function i(e){let t=new r;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:`begin`})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:`end`}),e.illegal&&t.addRule(e.illegal,{type:`illegal`}),t}function o(n,r){let a=n;if(n.isCompiled)return a;[ce,de,Ee,pe].forEach(e=>e(n,r)),e.compilerExtensions.forEach(e=>e(n,r)),n.__beforeBegin=null,[le,ue,fe].forEach(e=>e(n,r)),n.isCompiled=!0;let s=null;return typeof n.keywords==`object`&&n.keywords.$pattern&&(n.keywords=Object.assign({},n.keywords),s=n.keywords.$pattern,delete n.keywords.$pattern),s||=/\w+/,n.keywords&&=he(n.keywords,e.case_insensitive),a.keywordPatternRe=t(s,!0),r&&(n.begin||=/\B|\b/,a.beginRe=t(a.begin),!n.end&&!n.endsWithParent&&(n.end=/\B|\b/),n.end&&(a.endRe=t(a.end)),a.terminatorEnd=p(a.end)||``,n.endsWithParent&&r.terminatorEnd&&(a.terminatorEnd+=(n.end?`|`:``)+r.terminatorEnd)),n.illegal&&(a.illegalRe=t(n.illegal)),n.contains||=[],n.contains=[].concat(...n.contains.map(function(e){return ke(e===`self`?n:e)})),n.contains.forEach(function(e){o(e,a)}),n.starts&&o(n.starts,r),a.matcher=i(a),a}if(e.compilerExtensions||=[],e.contains&&e.contains.includes(`self`))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=a(e.classNameAliases||{}),o(e)}function Oe(e){return e?e.endsWithParent||Oe(e.starts):!1}function ke(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return a(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:Oe(e)?a(e,{starts:e.starts?a(e.starts):null}):Object.isFrozen(e)?a(e):e}var Ae=`11.12.0`,je=class extends Error{constructor(e,t){super(e),this.name=`HTMLInjectionError`,this.html=t}},Me=i,Ne=a,Pe=Symbol(`nomatch`),Fe=7,Ie=function(e){let t=Object.create(null),i=Object.create(null),a=[],o=!0,s=`Could not find the language '{}', did you forget to load/include a language module?`,c={disableAutodetect:!0,name:`Plain text`,contains:[]},l={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:`hljs-`,cssSelector:`pre code`,languages:null,__emitter:f};function u(e){return l.noHighlightRe.test(e)}function d(e){let t=e.className+` `;t+=e.parentNode?e.parentNode.className:``;let n=l.languageDetectRe.exec(t);if(n){let t=te(n[1]);return t||(ye(s.replace(`{}`,n[1])),ye(`Falling back to no-highlight mode for this block.`,e)),t?n[1]:`no-highlight`}return t.split(/\s+/).find(e=>u(e)||te(e))}function p(e,t,n){let r=``,i=``;typeof t==`object`?(r=e,n=t.ignoreIllegals,i=t.language):(be(`10.7.0`,`highlight(lang, code, ...args) has been deprecated.`),be(`10.7.0`,`Please use highlight(code, options) instead.
70
+ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(n=!0);let a={code:r,language:i};ae(`before:highlight`,a);let o=a.result?a.result:v(a.language,a.code,n);return o.code=a.code,ae(`after:highlight`,o),o}function v(e,n,i,a){let c=Object.create(null);function u(e,t){return e.keywords[t]}function d(){if(!A.keywords){j.addText(M);return}let e=0;A.keywordPatternRe.lastIndex=0;let t=A.keywordPatternRe.exec(M),n=``;for(;t;){n+=M.substring(e,t.index);let r=D.case_insensitive?t[0].toLowerCase():t[0],i=u(A,r);if(i){let[e,a]=i;if(j.addText(n),n=``,c[r]=(c[r]||0)+1,c[r]<=Fe&&(ne+=a),e.startsWith(`_`))n+=t[0];else{let n=D.classNameAliases[e]||e;m(t[0],n)}}else n+=t[0];e=A.keywordPatternRe.lastIndex,t=A.keywordPatternRe.exec(M)}n+=M.substring(e),j.addText(n)}function f(){if(M===``)return;let e=null;if(typeof A.subLanguage==`string`){if(!t[A.subLanguage]){j.addText(M);return}e=v(A.subLanguage,M,!0,ee[A.subLanguage]),ee[A.subLanguage]=e._top}else e=S(M,A.subLanguage.length?A.subLanguage:null);A.relevance>0&&(ne+=e.relevance),j.__addSublanguage(e._emitter,e.language)}function p(){A.subLanguage==null?d():f(),M=``}function m(e,t){e!==``&&(j.startScope(t),j.addText(e),j.endScope())}function h(e,t){let n=1,r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}let r=D.classNameAliases[e[n]]||e[n],i=t[n];r?m(i,r):(M=i,d(),M=``),n++}}function g(e,t){return e.scope&&typeof e.scope==`string`&&j.openNode(D.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(M,D.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),M=``):e.beginScope._multi&&(h(e.beginScope,t),M=``)),A=Object.create(e,{parent:{value:A}}),A}function _(e,t,n){let i=x(e.endRe,n);if(i){if(e[`on:end`]){let n=new r(e);e[`on:end`](t,n),n.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return _(e.parent,t,n)}function y(e){return A.matcher.regexIndex===0?(M+=e[0],1):(ie=!0,0)}function b(e){let t=e[0],n=e.rule,i=new r(n),a=[n.__beforeBegin,n[`on:begin`]];for(let n of a)if(n&&(n(e,i),i.isMatchIgnored))return y(t);return n.skip?M+=t:(n.excludeBegin&&(M+=t),p(),!n.returnBegin&&!n.excludeBegin&&(M=t)),g(n,e),n.returnBegin?0:t.length}function C(e){let t=e[0],r=n.substring(e.index),i=_(A,e,r);if(!i)return Pe;let a=A;A.endScope&&A.endScope._wrap?(p(),m(t,A.endScope._wrap)):A.endScope&&A.endScope._multi?(p(),h(A.endScope,e)):a.skip?M+=t:(a.returnEnd||a.excludeEnd||(M+=t),p(),a.excludeEnd&&(M=t));do A.scope&&j.closeNode(),!A.skip&&!A.subLanguage&&(ne+=A.relevance),A=A.parent;while(A!==i.parent);return i.starts&&g(i.starts,e),a.returnEnd?0:t.length}function w(){let e=[];for(let t=A;t!==D;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>j.openNode(e))}let T={};function E(t,r){let a=r&&r[0];if(M+=t,a==null)return p(),0;if(T.type===`begin`&&r.type===`end`&&T.index===r.index&&a===``){if(M+=n.slice(r.index,r.index+1),!o){let t=Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=T.rule,t}return 1}if(T=r,r.type===`begin`)return b(r);if(r.type===`illegal`&&!i){let e=Error(`Illegal lexeme "`+a+`" for mode "`+(A.scope||`<unnamed>`)+`"`);throw e.mode=A,e}if(r.type===`end`){let e=C(r);if(e!==Pe)return e}if(r.type===`illegal`&&a===``)return r.index===n.length||(M+=`
71
+ `),1;if(re>1e5&&re>r.index*3)throw Error(`potential infinite loop, way more iterations than matches`);return M+=a,a.length}let D=te(e);if(!D)throw ve(s.replace(`{}`,e)),Error(`Unknown language: "`+e+`"`);let O=De(D),k=``,A=a||O,ee={},j=new l.__emitter(l);w();let M=``,ne=0,N=0,re=0,ie=!1;try{if(D.__emitTokens)D.__emitTokens(n,j);else{for(A.matcher.considerAll();;){re++,ie?ie=!1:A.matcher.considerAll(),A.matcher.lastIndex=N;let e=A.matcher.exec(n);if(!e)break;let t=E(n.substring(N,e.index),e);N=e.index+t}E(n.substring(N))}return j.finalize(),k=j.toHTML(),{language:e,value:k,relevance:ne,illegal:!1,_emitter:j,_top:A}}catch(t){if(t.message&&t.message.includes(`Illegal`))return{language:e,value:Me(n),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:N,context:n.slice(N-100,N+100),mode:t.mode,resultSoFar:k},_emitter:j};if(o)return{language:e,value:Me(n),illegal:!1,relevance:0,errorRaised:t,_emitter:j,_top:A};throw t}}function b(e){let t={value:Me(e),illegal:!1,relevance:0,_top:c,_emitter:new l.__emitter(l)};return t._emitter.addText(e),t}function S(e,n){n=n||l.languages||Object.keys(t);let r=b(e),i=n.filter(te).filter(ne).map(t=>v(t,e,!1));i.unshift(r);let[a,o]=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(te(e.language).supersetOf===t.language)return 1;if(te(t.language).supersetOf===e.language)return-1}return 0}),s=a;return s.secondBest=o,s}function C(e,t,n){let r=t&&i[t]||n;e.classList.add(`hljs`),e.classList.add(`language-${r}`)}function w(e){let t=null,n=d(e);if(u(n))return;if(ae(`before:highlightElement`,{el:e,language:n}),e.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);return}if(e.children.length>0&&(l.ignoreUnescapedHTML||(console.warn(`One of your code blocks includes unescaped HTML. This is a potentially serious security risk.`),console.warn(`https://github.com/highlightjs/highlight.js/wiki/security`),console.warn(`The element with unescaped HTML:`),console.warn(e)),l.throwUnescapedHTML))throw new je(`One of your code blocks includes unescaped HTML.`,e.innerHTML);t=e;let r=t.textContent,i=n?p(r,{language:n,ignoreIllegals:!0}):S(r);e.innerHTML=i.value,e.dataset.highlighted=`yes`,C(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),ae(`after:highlightElement`,{el:e,result:i,text:r})}function T(e){l=Ne(l,e)}let E=()=>{k(),be(`10.6.0`,`initHighlighting() deprecated. Use highlightAll() now.`)};function D(){k(),be(`10.6.0`,`initHighlightingOnLoad() deprecated. Use highlightAll() now.`)}let O=!1;function k(){function e(){k()}if(document.readyState===`loading`){O||window.addEventListener(`DOMContentLoaded`,e,!1),O=!0;return}document.querySelectorAll(l.cssSelector).forEach(w)}function A(n,r){let i=null;try{i=r(e)}catch(e){if(ve(`Language definition for '{}' could not be registered.`.replace(`{}`,n)),o)ve(e);else throw e;i=c}i.name||(i.name=n),t[n]=i,i.rawDefinition=r.bind(null,e),i.aliases&&M(i.aliases,{languageName:n})}function ee(e){delete t[e];for(let t of Object.keys(i))i[t]===e&&delete i[t]}function j(){return Object.keys(t)}function te(e){return e=(e||``).toLowerCase(),t[e]||t[i[e]]}function M(e,{languageName:t}){typeof e==`string`&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function ne(e){let t=te(e);return t&&!t.disableAutodetect}function N(e){e[`before:highlightBlock`]&&!e[`before:highlightElement`]&&(e[`before:highlightElement`]=t=>{e[`before:highlightBlock`](Object.assign({block:t.el},t))}),e[`after:highlightBlock`]&&!e[`after:highlightElement`]&&(e[`after:highlightElement`]=t=>{e[`after:highlightBlock`](Object.assign({block:t.el},t))})}function re(e){N(e),a.push(e)}function ie(e){let t=a.indexOf(e);t!==-1&&a.splice(t,1)}function ae(e,t){let n=e;a.forEach(function(e){e[n]&&e[n](t)})}function se(e){return be(`10.7.0`,`highlightBlock will be removed entirely in v12.0`),be(`10.7.0`,`Please use highlightElement now.`),w(e)}Object.assign(e,{highlight:p,highlightAuto:S,highlightAll:k,highlightElement:w,highlightBlock:se,configure:T,initHighlighting:E,initHighlightingOnLoad:D,registerLanguage:A,unregisterLanguage:ee,listLanguages:j,getLanguage:te,registerAliases:M,autoDetection:ne,inherit:Ne,addPlugin:re,removePlugin:ie}),e.debugMode=function(){o=!1},e.safeMode=function(){o=!0},e.versionString=Ae,e.regex={concat:_,lookahead:m,either:y,optional:g,anyNumberOfTimes:h};for(let e in oe)typeof oe[e]==`object`&&n(oe[e]);return Object.assign(e,oe),e},Le=Ie({});Le.newInstance=()=>Ie({}),t.exports=Le,Le.HighlightJS=Le,Le.default=Le}))()).default;function ti(e){let t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:[`self`,{begin:/:-/,contains:[n]}]};Object.assign(n,{className:`variable`,variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,`(?![\\w\\d])(?![$])`)},r]});let i={className:`subst`,begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},a=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:`comment`}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:`string`})]}},s={className:`string`,begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(s);let c={match:/\\"/},l={className:`string`,begin:/'/,end:/'/},u={match:/\\'/},d={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:`number`},e.NUMBER_MODE,n]},f=e.SHEBANG({binary:`(${[`fish`,`bash`,`zsh`,`sh`,`csh`,`ksh`,`tcsh`,`dash`,`scsh`].join(`|`)})`,relevance:10}),p={className:`function`,begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},m=[`if`,`then`,`else`,`elif`,`fi`,`time`,`for`,`while`,`until`,`in`,`do`,`done`,`case`,`esac`,`coproc`,`function`,`select`],h=[`true`,`false`],g={match:/(\/[a-z._-]+)+/},_=[`break`,`cd`,`continue`,`eval`,`exec`,`exit`,`export`,`getopts`,`hash`,`pwd`,`readonly`,`return`,`shift`,`test`,`times`,`trap`,`umask`,`unset`],v=[`alias`,`bind`,`builtin`,`caller`,`command`,`declare`,`echo`,`enable`,`help`,`let`,`local`,`logout`,`mapfile`,`printf`,`read`,`readarray`,`source`,`sudo`,`type`,`typeset`,`ulimit`,`unalias`],y=`autoload.bg.bindkey.bye.cap.chdir.clone.comparguments.compcall.compctl.compdescribe.compfiles.compgroups.compquote.comptags.comptry.compvalues.dirs.disable.disown.echotc.echoti.emulate.fc.fg.float.functions.getcap.getln.history.integer.jobs.kill.limit.log.noglob.popd.print.pushd.pushln.rehash.sched.setcap.setopt.stat.suspend.ttyctl.unfunction.unhash.unlimit.unsetopt.vared.wait.whence.where.which.zcompile.zformat.zftp.zle.zmodload.zparseopts.zprof.zpty.zregexparse.zsocket.zstyle.ztcp`.split(`.`),b=`chcon.chgrp.chown.chmod.cp.dd.df.dir.dircolors.ln.ls.mkdir.mkfifo.mknod.mktemp.mv.realpath.rm.rmdir.shred.sync.touch.truncate.vdir.b2sum.base32.base64.cat.cksum.comm.csplit.cut.expand.fmt.fold.head.join.md5sum.nl.numfmt.od.paste.ptx.pr.sha1sum.sha224sum.sha256sum.sha384sum.sha512sum.shuf.sort.split.sum.tac.tail.tr.tsort.unexpand.uniq.wc.arch.basename.chroot.date.dirname.du.echo.env.expr.factor.groups.hostid.id.link.logname.nice.nohup.nproc.pathchk.pinky.printenv.printf.pwd.readlink.runcon.seq.sleep.stat.stdbuf.stty.tee.test.timeout.tty.uname.unlink.uptime.users.who.whoami.yes`.split(`.`);return{name:`Bash`,aliases:[`sh`,`zsh`],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:m,literal:h,built_in:[..._,...v,`set`,`shopt`,...y,...b]},contains:[f,e.SHEBANG(),p,d,a,o,g,s,c,l,u,n]}}var ni=e=>({IMPORTANT:{scope:`meta`,begin:`!important`},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:`number`,begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:`number`,begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:`built_in`,begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:`selector-attr`,begin:/\[/,end:/\]/,illegal:`$`,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:`number`,begin:e.NUMBER_RE+`(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?`,relevance:0},CSS_VARIABLE:{className:`attr`,begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),ri=`a.abbr.address.article.aside.audio.b.blockquote.body.button.canvas.caption.cite.code.dd.del.details.dfn.div.dl.dt.em.fieldset.figcaption.figure.footer.form.h1.h2.h3.h4.h5.h6.header.hgroup.html.i.iframe.img.input.ins.kbd.label.legend.li.main.mark.menu.nav.object.ol.optgroup.option.p.picture.q.quote.samp.section.select.source.span.strong.summary.sup.table.tbody.td.textarea.tfoot.th.thead.time.tr.ul.var.video`.split(`.`),ii=`defs.g.marker.mask.pattern.svg.switch.symbol.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feFlood.feGaussianBlur.feImage.feMerge.feMorphology.feOffset.feSpecularLighting.feTile.feTurbulence.linearGradient.radialGradient.stop.circle.ellipse.image.line.path.polygon.polyline.rect.text.use.textPath.tspan.foreignObject.clipPath`.split(`.`),ai=[...ri,...ii],oi=`any-hover.any-pointer.aspect-ratio.color.color-gamut.color-index.device-aspect-ratio.device-height.device-width.display-mode.forced-colors.grid.height.hover.inverted-colors.monochrome.orientation.overflow-block.overflow-inline.pointer.prefers-color-scheme.prefers-contrast.prefers-reduced-motion.prefers-reduced-transparency.resolution.scan.scripting.update.width.min-width.max-width.min-height.max-height`.split(`.`).sort().reverse(),si=`active.any-link.blank.checked.current.default.defined.dir.disabled.drop.empty.enabled.first.first-child.first-of-type.fullscreen.future.focus.focus-visible.focus-within.has.host.host-context.hover.indeterminate.in-range.invalid.is.lang.last-child.last-of-type.left.link.local-link.not.nth-child.nth-col.nth-last-child.nth-last-col.nth-last-of-type.nth-of-type.only-child.only-of-type.optional.out-of-range.past.placeholder-shown.read-only.read-write.required.right.root.scope.target.target-within.user-invalid.valid.visited.where`.split(`.`).sort().reverse(),ci=[`after`,`backdrop`,`before`,`cue`,`cue-region`,`first-letter`,`first-line`,`grammar-error`,`marker`,`part`,`placeholder`,`selection`,`slotted`,`spelling-error`].sort().reverse(),li=`accent-color.align-content.align-items.align-self.alignment-baseline.all.anchor-name.animation.animation-composition.animation-delay.animation-direction.animation-duration.animation-fill-mode.animation-iteration-count.animation-name.animation-play-state.animation-range.animation-range-end.animation-range-start.animation-timeline.animation-timing-function.appearance.aspect-ratio.backdrop-filter.backface-visibility.background.background-attachment.background-blend-mode.background-clip.background-color.background-image.background-origin.background-position.background-position-x.background-position-y.background-repeat.background-size.baseline-shift.block-size.border.border-block.border-block-color.border-block-end.border-block-end-color.border-block-end-style.border-block-end-width.border-block-start.border-block-start-color.border-block-start-style.border-block-start-width.border-block-style.border-block-width.border-bottom.border-bottom-color.border-bottom-left-radius.border-bottom-right-radius.border-bottom-style.border-bottom-width.border-collapse.border-color.border-end-end-radius.border-end-start-radius.border-image.border-image-outset.border-image-repeat.border-image-slice.border-image-source.border-image-width.border-inline.border-inline-color.border-inline-end.border-inline-end-color.border-inline-end-style.border-inline-end-width.border-inline-start.border-inline-start-color.border-inline-start-style.border-inline-start-width.border-inline-style.border-inline-width.border-left.border-left-color.border-left-style.border-left-width.border-radius.border-right.border-right-color.border-right-style.border-right-width.border-spacing.border-start-end-radius.border-start-start-radius.border-style.border-top.border-top-color.border-top-left-radius.border-top-right-radius.border-top-style.border-top-width.border-width.bottom.box-align.box-decoration-break.box-direction.box-flex.box-flex-group.box-lines.box-ordinal-group.box-orient.box-pack.box-shadow.box-sizing.break-after.break-before.break-inside.caption-side.caret-color.clear.clip.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.color-scheme.column-count.column-fill.column-gap.column-rule.column-rule-color.column-rule-style.column-rule-width.column-span.column-width.columns.contain.contain-intrinsic-block-size.contain-intrinsic-height.contain-intrinsic-inline-size.contain-intrinsic-size.contain-intrinsic-width.container.container-name.container-type.content.content-visibility.corner-bottom-left-shape.corner-bottom-right-shape.corner-shape.corner-top-left-shape.corner-top-right-shape.counter-increment.counter-reset.counter-set.cue.cue-after.cue-before.cursor.cx.cy.direction.display.dominant-baseline.empty-cells.enable-background.field-sizing.fill.fill-opacity.fill-rule.filter.flex.flex-basis.flex-direction.flex-flow.flex-grow.flex-shrink.flex-wrap.float.flood-color.flood-opacity.flow.font.font-display.font-family.font-feature-settings.font-kerning.font-language-override.font-optical-sizing.font-palette.font-size.font-size-adjust.font-smooth.font-smoothing.font-stretch.font-style.font-synthesis.font-synthesis-position.font-synthesis-small-caps.font-synthesis-style.font-synthesis-weight.font-variant.font-variant-alternates.font-variant-caps.font-variant-east-asian.font-variant-emoji.font-variant-ligatures.font-variant-numeric.font-variant-position.font-variation-settings.font-weight.forced-color-adjust.gap.glyph-orientation-horizontal.glyph-orientation-vertical.grid.grid-area.grid-auto-columns.grid-auto-flow.grid-auto-rows.grid-column.grid-column-end.grid-column-start.grid-gap.grid-row.grid-row-end.grid-row-start.grid-template.grid-template-areas.grid-template-columns.grid-template-rows.hanging-punctuation.height.hyphenate-character.hyphenate-limit-chars.hyphens.icon.image-orientation.image-rendering.image-resolution.ime-mode.initial-letter.initial-letter-align.inline-size.inset.inset-area.inset-block.inset-block-end.inset-block-start.inset-inline.inset-inline-end.inset-inline-start.isolation.justify-content.justify-items.justify-self.kerning.left.letter-spacing.lighting-color.line-break.line-height.line-height-step.list-style.list-style-image.list-style-position.list-style-type.margin.margin-block.margin-block-end.margin-block-start.margin-bottom.margin-inline.margin-inline-end.margin-inline-start.margin-left.margin-right.margin-top.margin-trim.marker.marker-end.marker-mid.marker-start.marks.mask.mask-border.mask-border-mode.mask-border-outset.mask-border-repeat.mask-border-slice.mask-border-source.mask-border-width.mask-clip.mask-composite.mask-image.mask-mode.mask-origin.mask-position.mask-repeat.mask-size.mask-type.masonry-auto-flow.math-depth.math-shift.math-style.max-block-size.max-height.max-inline-size.max-width.min-block-size.min-height.min-inline-size.min-width.mix-blend-mode.nav-down.nav-index.nav-left.nav-right.nav-up.none.normal.object-fit.object-position.offset.offset-anchor.offset-distance.offset-path.offset-position.offset-rotate.opacity.order.orphans.outline.outline-color.outline-offset.outline-style.outline-width.overflow.overflow-anchor.overflow-block.overflow-clip-margin.overflow-inline.overflow-wrap.overflow-x.overflow-y.overlay.overscroll-behavior.overscroll-behavior-block.overscroll-behavior-inline.overscroll-behavior-x.overscroll-behavior-y.padding.padding-block.padding-block-end.padding-block-start.padding-bottom.padding-inline.padding-inline-end.padding-inline-start.padding-left.padding-right.padding-top.page.page-break-after.page-break-before.page-break-inside.paint-order.pause.pause-after.pause-before.perspective.perspective-origin.place-content.place-items.place-self.pointer-events.position.position-anchor.position-visibility.print-color-adjust.quotes.r.resize.rest.rest-after.rest-before.right.rotate.row-gap.ruby-align.ruby-position.scale.scroll-behavior.scroll-margin.scroll-margin-block.scroll-margin-block-end.scroll-margin-block-start.scroll-margin-bottom.scroll-margin-inline.scroll-margin-inline-end.scroll-margin-inline-start.scroll-margin-left.scroll-margin-right.scroll-margin-top.scroll-padding.scroll-padding-block.scroll-padding-block-end.scroll-padding-block-start.scroll-padding-bottom.scroll-padding-inline.scroll-padding-inline-end.scroll-padding-inline-start.scroll-padding-left.scroll-padding-right.scroll-padding-top.scroll-snap-align.scroll-snap-stop.scroll-snap-type.scroll-timeline.scroll-timeline-axis.scroll-timeline-name.scrollbar-color.scrollbar-gutter.scrollbar-width.shape-image-threshold.shape-margin.shape-outside.shape-rendering.speak.speak-as.src.stop-color.stop-opacity.stroke.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke-width.tab-size.table-layout.text-align.text-align-all.text-align-last.text-anchor.text-combine-upright.text-decoration.text-decoration-color.text-decoration-line.text-decoration-skip.text-decoration-skip-ink.text-decoration-style.text-decoration-thickness.text-emphasis.text-emphasis-color.text-emphasis-position.text-emphasis-style.text-indent.text-justify.text-orientation.text-overflow.text-rendering.text-shadow.text-size-adjust.text-transform.text-underline-offset.text-underline-position.text-wrap.text-wrap-mode.text-wrap-style.timeline-scope.top.touch-action.transform.transform-box.transform-origin.transform-style.transition.transition-behavior.transition-delay.transition-duration.transition-property.transition-timing-function.translate.unicode-bidi.unicode-range.user-modify.user-select.vector-effect.vertical-align.view-timeline.view-timeline-axis.view-timeline-inset.view-timeline-name.view-transition-name.visibility.voice-balance.voice-duration.voice-family.voice-pitch.voice-range.voice-rate.voice-stress.voice-volume.white-space.white-space-collapse.widows.width.will-change.word-break.word-spacing.word-wrap.writing-mode.x.y.z-index.zoom`.split(`.`).sort().reverse();function ui(e){let t=e.regex,n=ni(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i=/@-?\w[\w]*(-\w+)*/,a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:`CSS`,case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:`from to`},classNameAliases:{keyframePosition:`selector-tag`},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:`selector-id`,begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:`selector-class`,begin:`\\.[a-zA-Z-][a-zA-Z0-9_-]*`,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:`selector-pseudo`,variants:[{begin:`:(`+si.join(`|`)+`)`},{begin:`:(:)?(`+ci.join(`|`)+`)`}]},n.CSS_VARIABLE,{className:`attribute`,begin:`\\b(`+li.join(`|`)+`)\\b`},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,n.UNICODE_RANGE,...a,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:`url data-uri`},contains:[...a,{className:`string`,begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:`[{;]`,relevance:0,illegal:/:/,contains:[{className:`keyword`,begin:i},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:`and or not only`,attribute:oi.join(` `)},contains:[{begin:/[a-z-]+(?=:)/,className:`attribute`},...a,n.CSS_NUMBER_MODE]}]},{className:`selector-tag`,begin:`\\b(`+ai.join(`|`)+`)\\b`}]}}function di(e){let t=e.regex;return{name:`Diff`,aliases:[`patch`],contains:[{className:`meta`,relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:`comment`,variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:`addition`,begin:/^\+/,end:/$/},{className:`deletion`,begin:/^-/,end:/$/},{className:`addition`,begin:/^!/,end:/$/}]}}function fi(e){let t={keyword:[`break`,`case`,`chan`,`const`,`continue`,`default`,`defer`,`else`,`fallthrough`,`for`,`func`,`go`,`goto`,`if`,`import`,`interface`,`map`,`package`,`range`,`return`,`select`,`struct`,`switch`,`type`,`var`],type:[`bool`,`byte`,`complex64`,`complex128`,`error`,`float32`,`float64`,`int8`,`int16`,`int32`,`int64`,`string`,`uint8`,`uint16`,`uint32`,`uint64`,`int`,`uint`,`uintptr`,`rune`],literal:[`true`,`false`,`iota`,`nil`],built_in:[`append`,`cap`,`close`,`complex`,`copy`,`imag`,`len`,`make`,`new`,`panic`,`print`,`println`,`real`,`recover`,`delete`]};return{name:`Go`,aliases:[`golang`],keywords:t,illegal:`</`,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:`string`,variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:`number`,variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\b0[bB](_?[01])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:`function`,beginKeywords:`func`,end:`\\s*(\\{|$)`,excludeEnd:!0,contains:[e.TITLE_MODE,{className:`params`,begin:/\(/,end:/\)/,endsParent:!0,keywords:t,illegal:/["']/}]}]}}var pi=`[A-Za-z$_][0-9A-Za-z$_]*`,mi=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),hi=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],gi=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),_i=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],vi=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],yi=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],bi=[].concat(vi,gi,_i);function xi(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=pi,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:pi,keyword:mi,literal:hi,built_in:bi,"variable.language":yi},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:r+`(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...gi,..._i]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let O={match:t.concat(/\b/,D([...vi,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},k={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},A={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ee=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,j={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ee)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},j,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ee,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},k,{match:`\\$`+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},O,E,S,A,{match:/\$[(.]/}]}}var Si={scope:`number`,match:`([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity`,relevance:0};function Ci(e){let t={className:`attr`,begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:`punctuation`,relevance:0},r=[`true`,`false`,`null`],i={scope:`literal`,beginKeywords:r.join(` `)};return{name:`JSON`,aliases:[`jsonc`,`json5`],keywords:{literal:r},contains:[t,n,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,i,Si,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:`\\S`}}function wi(e){let t=e.regex,n={begin:/<\/?[A-Za-z_]/,end:`>`,subLanguage:`xml`,relevance:0},r={match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},i={className:`code`,variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:`(~{3,})[^~](.|\\n)*?\\1~*[ ]*`},{begin:"```",end:"```+[ ]*$"},{begin:`~~~`,end:`~~~+[ ]*$`},{begin:"`.+?`"},{begin:`(?=^( {4}|\\t))`,contains:[{begin:`^( {4}|\\t)`,end:`(\\n)$`}],relevance:0}]},a={className:`bullet`,begin:`^[ ]*([*+-]|(\\d+\\.))(?=\\s+)`,end:`\\s+`,excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:`symbol`,begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:`link`,begin:/:\s*/,end:/$/,excludeBegin:!0}]},s={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:`string`,relevance:0,begin:`\\[`,end:`\\]`,excludeBegin:!0,returnEnd:!0},{className:`link`,relevance:0,begin:`\\]\\(`,end:`\\)`,excludeBegin:!0,excludeEnd:!0},{className:`symbol`,relevance:0,begin:`\\]\\[`,end:`\\]`,excludeBegin:!0,excludeEnd:!0}]},c={className:`strong`,contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},l={className:`emphasis`,contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},u=e.inherit(c,{contains:[]}),d=e.inherit(l,{contains:[]});c.contains.push(d),l.contains.push(u);let f=[n,s];return[c,l,u,d].forEach(e=>{e.contains=e.contains.concat(f)}),f=f.concat(c,l),{name:`Markdown`,aliases:[`md`,`mkdown`,`mkd`],contains:[{className:`section`,variants:[{begin:`^#{1,6}`,end:`$`,contains:f},{begin:`(?=^.+?\\n[=-]{2,}$)`,contains:[{begin:`^[=-]*$`},{begin:`^`,end:`\\n`,contains:f}]}]},n,a,r,c,l,{className:`quote`,begin:`^>\\s+`,contains:f,end:`$`},i,s,o,{scope:`literal`,match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function Ti(e){let t=e.regex,n=/[\p{XID_Start}_]\p{XID_Continue}*/u,r=`and.as.assert.async.await.break.case.class.continue.def.del.elif.else.except.finally.for.from.global.if.import.in.is.lambda.lazy.match.nonlocal|10.not.or.pass.raise.return.try.while.with.yield`.split(`.`),i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:`__import__.abs.aiter.all.anext.any.ascii.bin.bool.breakpoint.bytearray.bytes.callable.chr.classmethod.compile.complex.delattr.dict.dir.divmod.enumerate.eval.exec.filter.float.format.frozendict.frozenset.getattr.globals.hasattr.hash.help.hex.id.input.int.isinstance.issubclass.iter.len.list.locals.map.max.memoryview.min.next.object.oct.open.ord.pow.print.property.range.repr.reversed.round.sentinel.set.setattr.slice.sorted.staticmethod.str.sum.super.tuple.type.vars.zip`.split(`.`),literal:[`__debug__`,`Ellipsis`,`False`,`None`,`NotImplemented`,`True`],type:[`Any`,`Callable`,`Coroutine`,`Dict`,`List`,`Literal`,`Generic`,`Optional`,`Sequence`,`Set`,`Tuple`,`Type`,`Union`]},a={className:`meta`,begin:/^(>>>|\.\.\.) /},o={className:`subst`,begin:/\{/,end:/\}/,keywords:i,illegal:/#/},s={begin:/\{\{/,relevance:0},c={className:`string`,contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l=`[0-9](_?[0-9])*`,u=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,d=`\\b|${r.join(`|`)}`,f={className:`number`,relevance:0,variants:[{begin:`(\\b(${l})|(${u}))[eE][+-]?(${l})[jJ]?(?=${d})`},{begin:`(${u})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${l})[jJ](?=${d})`}]},p={className:`comment`,begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={className:`params`,variants:[{className:``,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:[`self`,a,f,c,e.HASH_COMMENT_MODE]}]};return o.contains=[c,f,a],{name:`Python`,aliases:[`py`,`gyp`,`ipython`],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[a,f,{scope:`variable.language`,match:/\bself\b/},{beginKeywords:`if`,relevance:0},{match:/\bor\b/,scope:`keyword`},c,p,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:`keyword`,3:`title.function`},contains:[m]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:`keyword`,3:`title.class`,6:`title.class.inherited`}},{className:`meta`,begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[f,m,c]}]}}function Ei(e){let t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),a={scope:`title.function.invoke`,relevance:0,begin:t.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,i,t.lookahead(/\s*\(/))},o=`([ui](8|16|32|64|128|size)|f(16|32|64|128))?`,s=`abstract.as.async.await.become.box.break.const.continue.crate.do.dyn.else.enum.extern.false.final.fn.for.if.impl.in.let.loop.macro.match.mod.move.mut.override.priv.pub.raw.ref.return.self.Self.static.struct.super.trait.true.try.type.typeof.union.unsafe.unsized.use.virtual.where.while.yield`.split(`.`),c=[`true`,`false`,`Some`,`None`,`Ok`,`Err`],l=`drop .Copy.Send.Sized.Sync.Drop.Fn.FnMut.FnOnce.ToOwned.Clone.Debug.PartialEq.PartialOrd.Eq.Ord.AsRef.AsMut.Into.From.Default.Iterator.Extend.IntoIterator.DoubleEndedIterator.ExactSizeIterator.SliceConcatExt.ToString.assert!.assert_eq!.bitflags!.bytes!.cfg!.col!.concat!.concat_idents!.debug_assert!.debug_assert_eq!.env!.eprintln!.panic!.file!.format!.format_args!.include_bytes!.include_str!.line!.local_data_key!.module_path!.option_env!.print!.println!.select!.stringify!.try!.unimplemented!.unreachable!.vec!.write!.writeln!.macro_rules!.assert_ne!.debug_assert_ne!`.split(`.`),u=[`i8`,`i16`,`i32`,`i64`,`i128`,`isize`,`u8`,`u16`,`u32`,`u64`,`u128`,`usize`,`f16`,`f32`,`f64`,`f128`,`str`,`char`,`bool`,`Box`,`Option`,`Result`,`String`,`Vec`];return{name:`Rust`,aliases:[`rs`],keywords:{$pattern:e.IDENT_RE+`!?`,type:u,keyword:s,literal:c,built_in:l},illegal:`</`,contains:[e.C_LINE_COMMENT_MODE,e.COMMENT(`/\\*`,`\\*/`,{contains:[`self`]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{scope:`symbol`,begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:`string`,variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:`char.escape`,match:/\\('|"|\\|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{scope:`number`,variants:[{begin:`\\b0b([01_]+)`+o},{begin:`\\b0o([0-7_]+)`+o},{begin:`\\b0x([A-Fa-f0-9_]+)`+o},{begin:`\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)`+o}],relevance:0},{begin:[/\bsafe/,/\s+/,/extern/],scope:{1:`keyword`,3:`keyword`}},{begin:[/fn/,/\s+/,r],scope:{1:`keyword`,3:`title.function`}},{scope:`meta`,begin:`#!?\\[`,end:`\\]`,contains:[{scope:`string`,begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],scope:{1:`keyword`,3:`keyword`,4:`variable`}},{begin:[/for/,/\s+/,r,/\s+/,/in/],scope:{1:`keyword`,3:`variable`,5:`keyword`}},{begin:[/type/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}},{begin:e.IDENT_RE+`::`,keywords:{keyword:`Self`,built_in:l,type:u}},{scope:`punctuation`,begin:`->`},a]}}function Di(e){return{name:`Shell Session`,aliases:[`console`,`shellsession`],contains:[{className:`meta.prompt`,begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:`bash`}}]}}function Oi(e){let t=e.regex,n=e.COMMENT(`--`,`$`),r={scope:`string`,variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},i={begin:/"/,end:/"/,contains:[{match:/""/}]},a=[`true`,`false`,`unknown`],o=[`double precision`,`large object`,`with timezone`,`without timezone`],s=`bigint.binary.blob.boolean.char.character.clob.date.dec.decfloat.decimal.float.int.integer.interval.nchar.nclob.national.numeric.real.row.smallint.time.timestamp.varchar.varying.varbinary`.split(`.`),c=[`add`,`asc`,`collation`,`desc`,`final`,`first`,`last`,`view`],l=`abs.acos.all.allocate.alter.and.any.are.array.array_agg.array_max_cardinality.as.asensitive.asin.asymmetric.at.atan.atomic.authorization.avg.begin.begin_frame.begin_partition.between.bigint.binary.blob.boolean.both.by.call.called.cardinality.cascaded.case.cast.ceil.ceiling.char.char_length.character.character_length.check.classifier.clob.close.coalesce.collate.collect.column.commit.condition.connect.constraint.contains.convert.copy.corr.corresponding.cos.cosh.count.covar_pop.covar_samp.create.cross.cube.cume_dist.current.current_catalog.current_date.current_default_transform_group.current_path.current_role.current_row.current_schema.current_time.current_timestamp.current_path.current_role.current_transform_group_for_type.current_user.cursor.cycle.date.day.deallocate.dec.decimal.decfloat.declare.default.define.delete.dense_rank.deref.describe.deterministic.disconnect.distinct.double.drop.dynamic.each.element.else.empty.end.end_frame.end_partition.end-exec.equals.escape.every.except.exec.execute.exists.exp.external.extract.false.fetch.filter.first_value.float.floor.for.foreign.frame_row.free.from.full.function.fusion.get.global.grant.group.grouping.groups.having.hold.hour.identity.in.indicator.initial.inner.inout.insensitive.insert.int.integer.intersect.intersection.interval.into.is.join.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.language.large.last_value.lateral.lead.leading.left.like.like_regex.listagg.ln.local.localtime.localtimestamp.log.log10.lower.match.match_number.match_recognize.matches.max.member.merge.method.min.minute.mod.modifies.module.month.multiset.national.natural.nchar.nclob.new.no.none.normalize.not.nth_value.ntile.null.nullif.numeric.octet_length.occurrences_regex.of.offset.old.omit.on.one.only.open.or.order.out.outer.over.overlaps.overlay.parameter.partition.pattern.per.percent.percent_rank.percentile_cont.percentile_disc.period.portion.position.position_regex.power.precedes.precision.prepare.primary.procedure.ptf.range.rank.reads.real.recursive.ref.references.referencing.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.release.result.return.returns.revoke.right.rollback.rollup.row.row_number.rows.running.savepoint.scope.scroll.search.second.seek.select.sensitive.session_user.set.show.similar.sin.sinh.skip.smallint.some.specific.specifictype.sql.sqlexception.sqlstate.sqlwarning.sqrt.start.static.stddev_pop.stddev_samp.submultiset.subset.substring.substring_regex.succeeds.sum.symmetric.system.system_time.system_user.table.tablesample.tan.tanh.then.time.timestamp.timezone_hour.timezone_minute.to.trailing.translate.translate_regex.translation.treat.trigger.trim.trim_array.true.truncate.uescape.union.unique.unknown.unnest.update.upper.user.using.value.values.value_of.var_pop.var_samp.varbinary.varchar.varying.versioning.when.whenever.where.width_bucket.window.with.within.without.year`.split(`.`),u=`abs.acos.array_agg.asin.atan.avg.cast.ceil.ceiling.coalesce.corr.cos.cosh.count.covar_pop.covar_samp.cume_dist.dense_rank.deref.element.exp.extract.first_value.floor.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.last_value.lead.listagg.ln.log.log10.lower.max.min.mod.nth_value.ntile.nullif.percent_rank.percentile_cont.percentile_disc.position.position_regex.power.rank.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.row_number.sin.sinh.sqrt.stddev_pop.stddev_samp.substring.substring_regex.sum.tan.tanh.translate.translate_regex.treat.trim.trim_array.unnest.upper.value_of.var_pop.var_samp.width_bucket`.split(`.`),d=[`current_catalog`,`current_date`,`current_default_transform_group`,`current_path`,`current_role`,`current_schema`,`current_transform_group_for_type`,`current_user`,`session_user`,`system_time`,`system_user`,`current_time`,`localtime`,`current_timestamp`,`localtimestamp`],f=[`create table`,`insert into`,`primary key`,`foreign key`,`not null`,`alter table`,`add constraint`,`grouping sets`,`on overflow`,`character set`,`respect nulls`,`ignore nulls`,`nulls first`,`nulls last`,`depth first`,`breadth first`],p=u,m=[...l,...c].filter(e=>!u.includes(e)),h={scope:`variable`,match:/@[a-z0-9][a-z0-9_]*/},g={scope:`operator`,match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},_={match:t.concat(/\b/,t.either(...p),/\s*\(/),relevance:0,keywords:{built_in:p}};function v(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,`\\s+`))),/\b/)}let y={scope:`keyword`,match:v(f),relevance:0};function b(e,{exceptions:t,when:n}={}){let r=n;return t||=[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}return{name:`SQL`,case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:b(m,{when:e=>e.length<3}),literal:a,type:s,built_in:d},contains:[{scope:`type`,match:v(o)},y,_,h,r,i,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,g]}}var ki=`[A-Za-z$_][0-9A-Za-z$_]*`,Ai=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),ji=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],Mi=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),Ni=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],Pi=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],Fi=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],Ii=[].concat(Pi,Mi,Ni);function Li(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=ki,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:ki,keyword:Ai,literal:ji,built_in:Ii,"variable.language":Fi},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:r+`(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...Mi,...Ni]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let O={match:t.concat(/\b/,D([...Pi,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},k={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},A={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ee=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,j={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ee)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},j,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ee,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},k,{match:`\\$`+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},O,E,S,A,{match:/\$[(.]/}]}}function Ri(e){let t=e.regex,n=Li(e),r=ki,i=[`any`,`void`,`number`,`boolean`,`string`,`object`,`never`,`symbol`,`bigint`,`unknown`],a={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:`keyword`,3:`title.class`}},o={beginKeywords:`interface`,end:/\{/,excludeEnd:!0,keywords:{keyword:`interface extends`,built_in:i},contains:[n.exports.CLASS_REFERENCE]},s={className:`meta`,relevance:10,begin:/^\s*['"]use strict['"]/},c={$pattern:ki,keyword:Ai.concat([`type`,`interface`,`public`,`private`,`protected`,`implements`,`declare`,`abstract`,`readonly`,`enum`,`override`,`satisfies`]),literal:ji,built_in:Ii.concat(i),"variable.language":Fi},l={className:`meta`,begin:`@`+r},u=(e,t,n)=>{let r=e.contains.findIndex(e=>e.label===t);if(r===-1)throw Error(`can not find mode to replace`);e.contains.splice(r,1,n)};Object.assign(n.keywords,c),n.exports.PARAMS_CONTAINS.push(l);let d=n.contains.find(e=>e.scope===`attr`),f=Object.assign({},d,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,d,f]),n.contains=n.contains.concat([l,a,o,f]),u(n,`shebang`,e.SHEBANG()),u(n,`use_strict`,s);let p=n.contains.find(e=>e.label===`func.def`);return p.relevance=0,Object.assign(n,{name:`TypeScript`,aliases:[`ts`,`tsx`,`mts`,`cts`]}),n}function zi(e){let t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,i={className:`symbol`,begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:`keyword`,begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(a,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:`string`}),c=e.inherit(e.QUOTE_STRING_MODE,{className:`string`}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:`attr`,begin:r,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:`string`,endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[i]},{begin:/'/,end:/'/,contains:[i]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:`HTML, XML`,aliases:[`html`,`xhtml`,`rss`,`atom`,`xjb`,`xsd`,`xsl`,`plist`,`wsf`,`svg`],case_insensitive:!0,unicodeRegex:!0,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,c,s,o,{begin:/\[/,end:/\]/,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,contains:[a,o,c,s]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},i,{className:`meta`,end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[c]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:`tag`,begin:/<style(?=\s|>)/,end:/>/,keywords:{name:`style`},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:`css`}},{className:`tag`,begin:/<script(?=\s|>)/,end:/>/,keywords:{name:`script`},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:`javascript`}},{className:`tag`,begin:/<>|<\/>/},{className:`tag`,begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:`name`,begin:n,relevance:0,starts:l}]},{className:`tag`,begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:`name`,begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function Bi(e){let t=`true false yes no null`,n=`[\\w#;/?:@&=+$,.~*'()[\\]]+`,r={className:`attr`,variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:`template-variable`,variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:`string`,relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:`char.escape`,relevance:0}]},o={className:`string`,relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,i]},s=e.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),c={className:`number`,begin:`\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b`},l={end:`,`,endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},u={begin:/\{/,end:/\}/,contains:[l],illegal:`\\n`,relevance:0},d={begin:`\\[`,end:`\\]`,contains:[l],illegal:`\\n`,relevance:0},f=[r,{className:`meta`,begin:`^---\\s*$`,relevance:10},{className:`string`,begin:`[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*`},{begin:`<%[%=-]?`,end:`[%-]?%>`,subLanguage:`ruby`,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:`type`,begin:`!\\w+!`+n},{className:`type`,begin:`!<`+n+`>`},{className:`type`,begin:`!`+n},{className:`type`,begin:`!!`+n},{className:`meta`,begin:`&`+e.UNDERSCORE_IDENT_RE+`$`},{className:`meta`,begin:`\\*`+e.UNDERSCORE_IDENT_RE+`$`},{className:`bullet`,begin:`-(?=[ ]|$)`,relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},c,{className:`number`,begin:e.C_NUMBER_RE+`\\b`,relevance:0},u,d,a,o],p=[...f];return p.pop(),p.push(s),l.contains=p,{name:`YAML`,case_insensitive:!0,aliases:[`yml`],contains:f}}for(let[e,t]of Object.entries({bash:ti,css:ui,diff:di,go:fi,javascript:xi,json:Ci,markdown:wi,python:Ti,rust:Ei,shell:Di,sql:Oi,typescript:Ri,xml:zi,yaml:Bi}))ei.registerLanguage(e,t);function Vi(e){for(let t of e.querySelectorAll(`pre code[class]`)){let e=/(?:language|lang)-(\S+)/.exec(t.className)?.[1]?.toLowerCase();!e||!ei.getLanguage(e)||(t.innerHTML=ei.highlight(t.textContent??``,{language:e}).value)}}var Hi={ts:`typescript`,tsx:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,jsx:`javascript`,mjs:`javascript`,cjs:`javascript`,py:`python`,rs:`rust`,sh:`bash`,zsh:`bash`,md:`markdown`,yml:`yaml`,html:`xml`,htm:`xml`,svg:`xml`,patch:`diff`};function Ui(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Hi[t]??t;return ei.getLanguage(n)?n:null}function Wi(e,t){let n=document.createElement(`span`);return t&&e.length<=500?n.innerHTML=ei.highlight(e,{language:t}).value:n.textContent=e,n}var Gi=null,Ki=`cursor-pointer rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[12.5px] text-indigo-700 transition-colors hover:border-indigo-300 hover:bg-indigo-100`;function qi(){Gi=null}function Ji(e,t,n){if(Gi?.remove(),Gi=null,!t.length)return;let r=W(`div`,`mt-1.5 flex flex-wrap gap-1.5`);for(let e of t){let t=W(`button`,Ki,e);t.type=`button`,t.onclick=()=>{Gi===r&&(Gi=null),r.remove(),n(e)},r.append(t)}e.append(r),Gi=r}var Yi=8e3,Xi=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Zi,Qi;function $i(e,t){Zi=e,Qi=t}var ea={queued:`border-amber-200 bg-amber-50 text-amber-800`,running:`border-green-200 bg-green-50 text-green-800`,succeeded:`border-neutral-200 bg-neutral-50 text-neutral-600`,failed:`border-red-200 bg-red-50 text-red-700`,cancelled:`border-neutral-200 bg-neutral-50 text-neutral-500`,interrupted:`border-amber-200 bg-amber-50 text-amber-800`,skipped:`border-neutral-200 bg-neutral-50 text-neutral-500`},ta=new Map;async function na(e){let t=await e;t.sent&&t.error&&Qi.append(`error`,t.error)}async function ra(e,t){try{let n=await fetch(e,{method:`POST`});n.ok||Qi.append(`error`,await u(n,t))}catch(e){Qi.append(`error`,`${t}: ${String(e)}`)}}async function ia(e){let t=Zi.sessionId();t&&await na(d(`Reply to subagent`,`/api/task-messages/${e}/reply`,{sourceSessionId:t},`reply failed`))}function aa(e){let t=W(`button`,`flex-none text-[11px] font-semibold normal-case text-cyan-800 hover:underline`,`Reply`);return t.onclick=()=>void ia(e),t}function oa(e){for(let[e,t]of ta)t.isConnected||ta.delete(e);let t=ta.get(e.runId);t||(t=W(`div`,`mx-5 my-1.5 border px-3 py-2 text-[13px]`),t.dataset.kind=`background-run`,Qi.el.append(t),ta.set(e.runId,t)),t.className=`mx-5 my-1.5 border px-3 py-2 text-[13px] ${ea[e.state]}`;let n=e.state===`queued`||e.state===`running`,r=`/api/task-runs/${e.runId}`,i=n?W(`span`,`spinner`):W(`span`,`w-3 flex-none text-center`,e.state===`succeeded`?`✓`:e.state===`failed`?`✕`:`·`),a=W(`button`,`min-w-0 truncate text-left font-medium hover:underline`,e.taskName);a.onclick=()=>Zi.showTasks(e.taskId);let o=W(`div`,`flex items-center gap-2`,i,W(`span`,`flex-none text-[11px] font-semibold uppercase`,e.state),a),s=W(`div`,`ml-auto flex flex-none items-center gap-2`);if(e.targetSessionId){let t=W(`button`,`font-mono text-[11px] hover:underline`,`Open`);t.title=`Open ${e.targetSessionId}`,t.onclick=()=>Zi.select(e.targetSessionId),s.append(t)}if(n){let e=W(`button`,`text-[11px] font-semibold hover:underline`,`Steer`),t={mode:`steer`,sourceSessionId:Zi.sessionId()};e.onclick=()=>void na(d(`Steer subagent`,`${r}/steer`,t,`could not steer the run`));let n=W(`button`,`text-[11px] font-semibold hover:underline`,`Stop`);n.onclick=()=>void ra(`${r}/cancel`,`could not stop the run`),s.append(e,n)}else if(e.targetSessionId&&e.sessionMode!==null){let e=W(`button`,`text-[11px] font-semibold hover:underline`,`Continue`),t={sourceSessionId:Zi.sessionId()};e.onclick=()=>void na(d(`Continue subagent`,`${r}/resume`,t,`could not continue`)),s.append(e)}o.append(s);let c=Math.max(0,Math.round(((e.finishedAt??Date.now())-(e.startedAt??e.queuedAt))/1e3));t.replaceChildren(o,W(`div`,`mt-1 text-[11px] opacity-70`,`${e.sessionMode??`task`} · depth ${e.depth} · ${c}s · ${e.runId}`)),Qi.scroll()}var sa=null,ca=new WeakMap,la=e=>{let t=ca.get(e)??[];return ca.set(e,t),t};function ua(){sa&&!sa.toolRows.size&&Sa(`done`)}var da=null;function fa(){sa=null,da=null,ta.clear()}function pa(){let e=da;return!e||sa?.el===e||(da=null,e!==Qi.el.lastElementChild)?null:(e.remove(),e.dataset.adopted=`1`,ha(e,e.dataset.status),e)}var ma={running:`text-green-700 open:bg-green-50`,done:`text-neutral-400 hover:text-neutral-600 open:bg-black/[0.02] open:text-neutral-500 dark:open:bg-neutral-100`,failed:`text-red-600 open:bg-red-50`,interrupted:`text-amber-700 open:bg-amber-50`};function ha(e,t){e.dataset.status=t,e.className=`${e.dataset.adopted?`float-left min-w-[6.5rem] pr-3 tabular-nums mt-[3px] open:float-none open:mt-0 open:mb-1.5 open:min-w-0 open:pr-0`:`mx-5 my-1.5`} rounded-md text-[11.5px] leading-[1.35] open:border open:border-black/[0.06] open:px-2 open:py-1.5 dark:open:border-neutral-200 ${ma[t]}`}var ga={failed:`✕`,interrupted:`⏸`};function _a(e){return e===`running`?W(`span`,`spinner`):e===`done`?W(`span`,`hidden`):W(`span`,`flex-none text-[12px] font-bold`,ga[e])}function va(e){if(sa)return sa;let t=_a(`running`),n=W(`span`,`truncate`,`working…`),{el:r}=qn(``,[t,n]);r.dataset.kind=`activity`,ha(r,`running`);let i=W(`div`,`mt-1.5 flex max-h-64 flex-col gap-1 overflow-y-auto overscroll-contain border-t border-black/5 pt-1.5 dark:border-neutral-200`);return r.append(i),ya(r,i),Qi.el.append(r),da=r,Qi.scroll(),sa={el:r,statusIcon:t,headline:n,rowsEl:i,toolRows:new Map,thinking:null,steps:0,failedSteps:0,startTs:e,sawError:!1},sa}function ya(e,t){t.dataset.follow=`1`,t.addEventListener(`scroll`,()=>{let e=t.scrollHeight-t.scrollTop-t.clientHeight<24;t.dataset.follow=e?`1`:``}),e.addEventListener(`toggle`,()=>{e.open&&(t.scrollTop=t.scrollHeight,t.dataset.follow=`1`)})}function ba(e){Qi.bulk()||!e.el.open||!e.rowsEl.dataset.follow||(e.rowsEl.scrollTop=e.rowsEl.scrollHeight)}function xa(e,t,n){let r=Math.max(1,Math.round((Date.now()-e.startTs)/1e3)),i=`${e.steps} step${e.steps===1?``:`s`} · ${r}s`;e.headline.textContent=t===`running`&&n?`${i} · ${n}`:t===`done`?i:`${i} · ${t}`,ha(e.el,t);let a=_a(t);e.statusIcon.replaceWith(a),e.statusIcon=a}function Sa(e){if(!sa)return;for(let{statusEl:e}of sa.toolRows.values())e.textContent===`running…`&&(e.textContent=`interrupted`);let t=sa.steps>0&&sa.failedSteps===sa.steps;xa(sa,(sa.sawError||t)&&e===`done`?`failed`:e),sa=null}function Ca(){sa&&(sa.sawError=!0)}function wa(e){let t=e.slice(0,400).replace(/\s+/g,` `);return t.length>100?t.slice(0,100)+`…`:t}function Ta(e,t,n,r){let i=va(e);i.steps+=1,i.thinking=null;let a=JSON.stringify(r,null,2)??``,o=W(`span`,`ml-auto flex-none text-neutral-400`,`running…`),s=W(`span`,`truncate text-neutral-500`,wa(a)),{el:c}=qn(`rounded-md px-1 py-0.5 font-mono text-[12.5px] hover:bg-black/[0.03] dark:hover:bg-neutral-100`,[W(`span`,`flex-none font-semibold`,n),s,o]),l=W(`pre`,`max-h-40 overflow-y-auto whitespace-pre-wrap rounded bg-black/[0.04] p-1.5 text-[12px] dark:bg-neutral-100`,a),u=W(`pre`,`hidden max-h-56 overflow-y-auto whitespace-pre-wrap rounded bg-black/[0.04] p-1.5 text-[12px] dark:bg-neutral-100`);c.append(W(`div`,`mt-1 flex flex-col gap-1 pl-4`,l,u)),la(i.el).push({tool:n,call:t,preview:s,argsPre:l,outputPre:u}),i.toolRows.set(t,{el:c,statusEl:o,outputPre:u}),i.rowsEl.append(c),ba(i),xa(i,`running`,n),Qi.scroll()}function Ea(e,t,n){let r=sa;if(!r)return;let i=r.toolRows.get(e);r.toolRows.delete(e),i&&(i.statusEl.textContent=t?`failed`:`ok`,i.statusEl.className=`ml-auto flex-none ${t?`text-red-600`:`text-green-700`}`,i.el.classList.toggle(`bg-red-50`,t),i.el.classList.toggle(`text-red-700`,t),n&&(i.outputPre.textContent=n.length>8e3?n.slice(0,Yi)+`…`:n,i.outputPre.classList.remove(`hidden`)),t&&(r.failedSteps+=1)),xa(r,`running`)}function Da(e,t){let n=va(e);if(!n.thinking){let{el:e,summary:t}=qn(`rounded-md px-1 py-0.5 text-[12.5px] italic text-neutral-500 hover:bg-black/[0.03] dark:hover:bg-neutral-100`,[W(`span`,`truncate`,`thinking…`)]),r=W(`div`,`mt-1 max-h-56 overflow-y-auto whitespace-pre-wrap pl-4 not-italic text-neutral-500`,``);e.append(r),n.rowsEl.append(e),n.thinking={pre:r,summary:t},ba(n),xa(n,`running`,`thinking…`)}let r=n.thinking;r.pre.textContent=((r.pre.textContent??``)+t).slice(-4e3);let i=(r.pre.textContent??``).split(`
72
+ `).filter(Boolean).pop()??`thinking…`,a=r.summary.lastElementChild;a.textContent=i.length>90?`…`+i.slice(-90):i}var Oa=0;function ka(e,t=0,n=!1,r){let i=Date.now()-t,a=va(i).el;for(let t of e){if(t.kind===`thinking`){Da(i,t.text??``);continue}let e=t.id??`replay-${++Oa}`;Ta(i,e,t.toolName??``,t.args),t.done&&Ea(e,t.isError??!1,t.output??``)}r!==void 0&&e.some(e=>e.kind===`tool`&&e.args===void 0)&&Aa(a,r),!n&&Sa(e.some(e=>e.kind===`tool`&&!e.done)?`interrupted`:`done`)}function Aa(e,t){let n=()=>{e.open&&(e.removeEventListener(`toggle`,n),ja(e,t))};e.addEventListener(`toggle`,n)}async function ja(e,t){let n=Zi.sessionId(),r=la(e),i=new Set(r.filter(e=>!e.argsPre.textContent)),a=e=>{for(let t of i)t.argsPre.textContent=e};if(a(`loading…`),!n)return a(`no session`);let o;try{let e=await fetch(`/api/sessions/${n}/turns/${t}/steps`);if(!e.ok)return a(await u(e,`could not load these steps`));o=(await e.json()).steps}catch(e){return a(`could not load these steps: ${String(e)}`)}let s=o.filter(e=>e.kind===`tool`);for(let[e,t]of r.entries()){if(!i.has(t))continue;let n=s[e];if(!(n&&(n.id?n.id===t.call:n.toolName===t.tool))){t.argsPre.textContent=`detail no longer available — reload the session`;continue}let r=JSON.stringify(n.args,null,2)??``;t.argsPre.textContent=r,t.preview.textContent=wa(r),n.output&&(t.outputPre.textContent=n.output,t.outputPre.classList.remove(`hidden`))}}var Ma,Y=U(`#turns`);function Na(e){Ma=e,$i(e,{el:Y,append:X,scroll:Ba,bulk:()=>Pa})}var Pa=!1,Fa=()=>Y.scrollHeight-Y.scrollTop-Y.clientHeight<80,Ia=!0;Y.addEventListener(`scroll`,()=>{Pa||(Ia=Fa())},{passive:!0});var La=0;function Ra(){!Ia||Pa||La||(La=requestAnimationFrame(()=>{La=0,Ia&&!Pa&&(Y.scrollTop=Y.scrollHeight)}))}new ResizeObserver(Ra).observe(Y),Y.addEventListener(`load`,Ra,!0),new MutationObserver(Ra).observe(Y,{childList:!0,subtree:!0,characterData:!0});function za(){Fa()&&(Ia=!0)}function Ba(e=!1){Pa||(e&&(Ia=!0),Ia&&(Y.scrollTop=Y.scrollHeight))}var Va=500,Ha=0,Ua=0,Wa=null;function Ga(){for(;Y.childElementCount>Va;){let e=Y.firstElementChild;e.remove(),e!==Wa&&(e.dataset.kind===`user`&&Ha++,Ua++)}Ua&&(Wa||(Wa=W(`div`,`px-5 py-2 text-center text-[11.5px] italic text-neutral-400`),Wa.dataset.kind=`trim`),Wa.textContent=`${Ua} earlier row${Ua===1?``:`s`} not shown — still in the transcript, not on this screen`,Y.firstElementChild!==Wa&&Y.prepend(Wa))}var Ka={user:{row:`border-l-indigo-500 bg-indigo-50`,body:`text-neutral-900`},assistant:{row:`border-l-transparent`,body:`text-neutral-900`},error:{row:`border-l-red-400 bg-red-50`,body:`text-red-700`},system:{row:`border-l-cyan-500 bg-cyan-50`,body:`text-neutral-800`}};function X(e,t,n=!1){ua();let r=e===`assistant`?pa():null,i=Ka[e],a=W(`div`,`group relative border-l-2 px-5 ${Y.lastElementChild?.dataset.kind===e?`pt-1 pb-2.5`:`mt-1.5 py-2.5`} ${i.row}`);a.dataset.kind=e;let o=e===`user`?$r(t):null,s=o?.text??t,c=e===`user`?Ln(s):null,l=c?.id||c?.when?c:null,u=W(`div`,`whitespace-pre-wrap break-words ${i.body}`,l?.text??s);(o?.paths.length||l)&&(u.dataset.raw=t),n&&$a(u,t),r&&(a.classList.add(`flow-root`),a.append(r)),l&&a.append(qa(l)),a.append(u);let d=Ma.sessionId();if(o?.paths.length&&d){let e=jr(a);for(let t of o.paths)e.append(Wr(d,t))}if(e===`user`){let e=W(`button`,`absolute right-2 top-1 hidden h-6 w-6 items-center justify-center rounded text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700 group-hover:flex pointer-coarse:flex`);e.title=`Edit — resends from here; this message and later turns leave the context`,e.setAttribute(`aria-label`,`Edit message`),e.innerHTML=`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="h-3.5 w-3.5"><path d="m10.7 2.3 3 3L6 13H3v-3l7.7-7.7zM9.3 3.7l3 3"/></svg>`,e.onclick=()=>Ya(a,u),a.append(e)}return Y.append(a),Ga(),Ba(),u}function qa(e){let t=W(`div`,`mb-1 flex items-baseline gap-2 text-[11.5px] leading-tight`),n=e.name??e.id;if(n){let r=W(`span`,`font-semibold text-indigo-700`,n);e.id&&(r.title=e.id),t.append(r)}return e.when&&t.append(W(`span`,`text-neutral-400`,e.when)),t}function Ja(e,t){let n=t.kind===`task-callback`?`Task callback`:t.kind===`task-message`?t.messageKind===`decision`?`Decision needed`:`Task ${t.messageKind.replace(`_`,` `)}`:`Agent task input`;ua();let r=W(`div`,`mt-1.5 border-l-2 border-l-cyan-500 bg-cyan-50 px-5 py-2.5`);r.dataset.kind=`system`;let i=W(`div`,`mb-1 flex items-center gap-2 text-[11px] font-semibold uppercase text-cyan-800`,W(`span`,``,n));if(t.sourceSessionId&&t.sourceSessionId!==`console`){let e=W(`button`,`truncate font-mono normal-case text-cyan-700 hover:underline`,t.sourceSessionId.slice(0,12));e.title=`Open source session`,e.onclick=()=>Ma.select(t.sourceSessionId),i.append(W(`span`,`text-cyan-400`,`from`),e)}let a=W(`button`,`ml-auto flex-none font-mono normal-case text-cyan-700 hover:underline`,`run ${t.runId.slice(0,8)}`);a.onclick=()=>Ma.showTasks(t.taskId),i.append(a),t.kind===`task-message`&&t.messageKind===`decision`&&i.append(aa(t.messageId));let o=[`max-h-[min(18rem,40dvh)]`,`overflow-hidden`],s=W(`div`,`whitespace-pre-wrap break-words text-[14px] text-neutral-800 ${o.join(` `)}`,e);r.append(i,s),Y.append(r);let c=e.length>800||e.split(`
73
+ `).length>12;if(s.clientHeight?s.scrollHeight>s.clientHeight+1:c){let e=W(`button`,`mx-auto mt-1.5 block w-fit rounded border border-cyan-200 bg-white px-2 py-1 text-[12px] font-medium text-cyan-800 shadow-sm hover:bg-cyan-100 pointer-coarse:py-3.5`,`Show full message`);e.setAttribute(`type`,`button`),e.onclick=()=>{let t=s.classList.toggle(o[0]);s.classList.toggle(o[1],t),e.textContent=t?`Show full message`:`Collapse message`,s.tabIndex=-1,s.focus({preventScroll:!0})},r.append(e)}else s.classList.remove(...o);Ga(),Ba()}function Ya(e,t){if(Ma.sessionState()!==`idle`){X(`error`,`can't edit while streaming — stop the turn first`);return}if(e.querySelector(`textarea`))return;let n=document.createElement(`textarea`);n.value=t.dataset.raw??t.textContent??``,n.className=`block w-full resize-none rounded-md border border-indigo-300 bg-white px-2 py-1 focus:outline-none`;let r=()=>{n.style.height=`auto`,n.style.height=`${Math.min(n.scrollHeight,192)}px`};n.oninput=r,t.classList.add(`hidden`),t.after(n),r(),n.focus(),n.setSelectionRange(n.value.length,n.value.length);let i=()=>{n.remove(),t.classList.remove(`hidden`)};n.onkeydown=t=>{if(!(t.isComposing||t.keyCode===229)&&(t.key===`Escape`&&i(),t.key===`Enter`&&!t.shiftKey)){t.preventDefault();let r=n.value.trim();if(!r)return i();Xa(e,r)}}}async function Xa(e,t){let n=Ma.sessionId();if(!n)return;let r=Ha+[...Y.querySelectorAll(`[data-kind="user"]`)].indexOf(e);for(;e.nextElementSibling;)e.nextElementSibling.remove();e.remove(),Ma.ownTurn(t),X(`user`,t),Ba(!0);let i=await l(`/api/sessions/${n}/turns/${r}/edit`,{text:t});if(!i.ok){let e=await u(i,`edit failed`);await Ma.reload(n),X(`error`,e)}}function Za(e,t){if(!t)return;let n=new Date(t.completedAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hour12:!1});(e.parentElement??e).append(W(`span`,`absolute -top-2.5 right-3 z-10 hidden rounded border border-neutral-200 bg-white px-1.5 py-0.5 text-[11.5px] text-neutral-500 shadow-sm group-hover:inline`,`${n} · ${hr(t)}`))}function Qa(e){for(let t of e.querySelectorAll(`pre`)){let e=t.querySelector(`code`);if(!e)continue;let n=W(`div`,`group/code relative`);t.replaceWith(n),n.append(t,Kn(`absolute right-1.5 top-1.5 cursor-pointer rounded border border-black/[0.08] bg-white/85 px-1.5 py-0.5 text-[11px] text-neutral-500 opacity-0 transition-opacity hover:bg-white hover:text-neutral-800 focus:opacity-100 group-hover/code:opacity-100 pointer-coarse:opacity-100 dark:border-neutral-200`,()=>e.textContent??``))}}function $a(e,t,n=!1){let r=Ma.sessionId(),i=r?Hr(t,r):t;e.innerHTML=nt.sanitize(H.parse(i,{async:!1})),e.classList.remove(`whitespace-pre-wrap`),e.classList.add(`md`),Wn(e),!n&&(Vi(e),Qa(e),Xr(e))}function eo(e,t,n,r=!1){let{text:i,suggestions:a}=xr(t);return dr({text:i,suggestions:a})?to(e,br(t)):$a(e,i),Za(e,n),r&&Ji(e.parentElement??e,a,e=>Ma.send(`auto`,e)),e}function to(e,t){e.classList.remove(`md`,`whitespace-pre-wrap`),e.replaceChildren(W(`span`,`text-[12.5px] italic text-neutral-400`,t?`Stayed silent — ${t}`:`Stayed silent.`))}var no=(e,t,n=!1)=>eo(X(`assistant`,``),e,t,n),ro=null,io=null,ao=!1,oo=80;function so(){if(io){ao=!0;return}ao=!1,ro&&($a(ro,xr(ro.dataset.raw??``).text,!0),Ba()),io=setTimeout(()=>{io=null,ao&&so()},oo)}function co(){io&&clearTimeout(io),io=null,ao=!1}function lo(e){ro||=X(`assistant`,``),ro.dataset.raw=(ro.dataset.raw??``)+e,so()}function uo(e=!1){if(!ro)return;let t=ro;ro=null,co(),eo(t,t.dataset.raw??``,void 0,e)}function fo(e,t){Sa(`done`),ro?(e&&(ro.dataset.raw=e),Za(ro,t)):e&&no(e,t,!0),uo(!0)}function po(){Sa(`interrupted`),uo()}function mo(){Y.replaceChildren(),Ha=0,Ua=0,Wa=null,ro=null,co(),fa(),qi()}function ho(e){if(!e){Y.querySelector(`[data-kind="loading"]`)?.remove();return}let t=W(`div`,`flex flex-col gap-3 px-5 py-4`);t.dataset.kind=`loading`;for(let e of[`w-2/5`,`w-4/5`,`w-3/5`,`w-1/3`,`w-2/3`])t.append(W(`div`,`skeleton h-3.5 ${e}`));Y.append(t)}function go(e,t,n){ho(!1);let r=new Map(n.map(e=>[e.runId,e])),i=e=>[...r].filter(([,t])=>t.queuedAt<=e).map(([e])=>e),a=e=>{for(let t of e){let e=r.get(t);e&&(oa(e),r.delete(t))}},o=e.reduce((e,t,n)=>t.role===`assistant`?n:e,-1);Pa=!0;try{for(let[n,r]of e.entries()){let s=t===`streaming`&&n===e.length-1&&(!r.text||(r.steps?.some(e=>e.kind===`tool`&&!e.done)??!1)),c=r.steps;if(c?.length&&(ka(c,r.meta?.durationMs,s,n),r.meta&&a(i(r.meta.completedAt))),r.text){if(r.role===`system`&&r.origin){a(r.origin.kind===`task-message`?[r.origin.runId]:r.origin.runIds??[r.origin.runId]),Ja(r.text,r.origin);continue}r.role===`assistant`?no(r.text,r.meta,t===`idle`&&n===o):X(r.role,r.text)}}for(let e of r.values())oa(e)}finally{Pa=!1}Ba(!0)}var _o=window.fetch.bind(window),vo=20,yo=6e4,bo=[],xo=new Map,So=e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:void 0;function Co(e,t){let n=t===void 0?e:`${e}: ${String(t)}`,r=Date.now();return r-(xo.get(n)??-6e4)<yo||(xo.size>100&&xo.clear(),xo.set(n,r),bo=bo.filter(e=>r-e<6e4),bo.length>=vo)?null:(bo.push(r),_o(`/api/client-log`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({message:n,stack:So(t),view:location.hash||`/`}),keepalive:!0}).catch(()=>{}),X(`error`,n))}function wo(){window.__pierReporting=!0,window.addEventListener(`error`,e=>{Co(`script error: ${e.message}`,e.error)}),window.addEventListener(`unhandledrejection`,e=>{Co(`unhandled rejection`,e.reason)})}var To=window.fetch.bind(window),Eo=()=>{location.assign(`/login?next=${encodeURIComponent(location.pathname+location.hash)}`)};function Do(){window.fetch=async(...e)=>{let t=await To(...e);return t.status===401&&Eo(),t}}function Oo(e,t){if(e.readyState!==EventSource.CLOSED)return;let n=()=>{let e=Co(`${t} stream disconnected`);if(!e)return;let n=G(`Reload`);n.classList.add(`ml-2`,`align-middle`),n.onclick=()=>location.reload(),e.append(` `,n)};To(`/api/projects`).then(e=>e.status===401?Eo():n(),n)}var ko=/Mac|iP(?:hone|ad|od)/.test(navigator.userAgent),Ao=ko?`⌘`:`Ctrl+`,jo=ko?`⇧`:`Shift+`,Mo=e=>{let t=e.startsWith(`meta+`),n=t?e.slice(5):e;return n.startsWith(`shift+`)?{key:n.slice(6),shift:!0,meta:t}:{key:n,shift:!1,meta:t}};function No(e){let{key:t,shift:n,meta:r}=Mo(e);return`${r?`⌘`:Ao}${n?jo:``}${t.toUpperCase()}`}var Po=`pointer-events-none fixed z-50 flex items-center gap-2 whitespace-nowrap rounded-md bg-neutral-800 px-2 py-1 text-[11.5px] text-neutral-100 shadow-lg`;function Fo(e,t,n){e.removeAttribute(`title`);let r=null,i=()=>{r?.remove(),r=null,document.removeEventListener(`keydown`,i,!0)};e.addEventListener(`pointerenter`,a=>{if(a.pointerType!==`mouse`)return;i(),r=W(`div`,Po,t,W(`kbd`,`rounded bg-white/15 px-1 py-px font-sans text-[10.5px]`,n)),document.body.append(r);let o=e.getBoundingClientRect(),s=o.bottom+6,c=s+r.offsetHeight+8<=window.innerHeight;r.style.top=`${c?s:Math.max(8,o.top-r.offsetHeight-6)}px`,r.style.left=`${Math.max(8,Math.min(o.left,window.innerWidth-r.offsetWidth-8))}px`,document.addEventListener(`keydown`,i,!0)}),e.addEventListener(`pointerleave`,i),e.addEventListener(`pointerdown`,i)}function Io(e,t,n,r,i){Fo(e,n,No(t)),Bo(t,r,i)}function Lo(e,t,n,r){Fo(e,t,`Esc`),document.addEventListener(`keydown`,e=>{e.key!==`Escape`||e.isComposing||e.defaultPrevented||document.querySelector(`dialog[open]`)||!r()||(e.preventDefault(),n())})}var Ro=`input, textarea, select, [contenteditable]`;function zo(e,t,n,r,i){Fo(e,n,t[0].toUpperCase()),document.addEventListener(`keydown`,e=>{e.metaKey||e.ctrlKey||e.altKey||e.isComposing||e.defaultPrevented||t.includes(e.key.toLowerCase())&&(e.target?.closest?.(Ro)||document.querySelector(`dialog[open]`)||!i()||(e.preventDefault(),r()))})}function Bo(e,t,n){let{key:r,shift:i,meta:a}=Mo(e);document.addEventListener(`keydown`,e=>{e.key.toLowerCase()!==r||e.altKey||e.shiftKey!==i||(a?!e.metaKey:!e.metaKey&&!e.ctrlKey)||!e.metaKey&&e.target?.closest?.(`[data-owns-keyboard]`)||n?.()||(e.preventDefault(),e.stopPropagation(),t())},!0)}var Vo,Ho=U(`#composer`),Z=U(`#input`),Uo=U(`#send`),Wo=U(`#send-plane`),Go=U(`#send-queue`),Ko=U(`#stop`),qo=U(`#queue-panel`),Jo=U(`#queue-rows`),Yo=U(`#queue-label`),Xo=U(`#image-strip`),Zo=U(`#attach-input`),Qo=!1,$o=[],es=[];function ts(){let e=window.visualViewport;if(!e)return;let t=()=>{let t=e.scale<=1.05&&window.innerHeight-e.height-e.offsetTop>80;t?document.body.dataset.kb=``:delete document.body.dataset.kb,document.body.style.height=t?`${String(e.height)}px`:``,t&&window.scrollY&&window.scrollTo(0,0)};e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t)}function ns(){Z.focus()}function rs(e){let t=es.indexOf(e);return t<0?!1:(es.splice(t,1),!0)}function is(e){es.push(e)}function as(){es=[]}function os(){let e=Vo.sessionState()===`streaming`;Uo.className=`flex h-7 w-7 flex-none cursor-pointer items-center justify-center rounded-lg ${e?`bg-amber-100 text-amber-700 hover:bg-amber-200 active:bg-amber-300`:`bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-700 dark:text-neutral-50`}`,Uo.title=e?`Queue — delivered when the turn ends`:`Send`,Wo.classList.toggle(`hidden`,e),Go.classList.toggle(`hidden`,!e),Ko.classList.toggle(`hidden`,!e),Ko.classList.toggle(`flex`,e)}function ss(){let e=Vo.chatVisible()&&Qo;qo.classList.toggle(`hidden`,!e),qo.classList.toggle(`flex`,e)}function cs(e,t){let n=[...e.map(e=>({mode:`steer`,text:e})),...t.map(e=>({mode:`queued`,text:e}))];Qo=n.length>0,Yo.textContent=n.length>1?`Queued · ${n.length}`:`Queued`,ss(),Jo.replaceChildren(...n.map(e=>{let t=W(`li`,`flex items-start gap-2 text-[13px] leading-[18px]`);return e.mode===`steer`&&t.append(W(`span`,`flex-none rounded bg-indigo-100 px-1 py-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-indigo-700`,e.mode)),t.append(W(`span`,`min-w-0 whitespace-pre-wrap break-words text-neutral-700`,e.text)),t}))}var ls=8;function us(){Xo.classList.toggle(`hidden`,$o.length===0),Xo.classList.toggle(`flex`,$o.length>0),Xo.replaceChildren(...$o.map((e,t)=>{let n=e.mimeType.startsWith(`image/`)?Mr(`data:${e.mimeType};base64,${e.data}`):W(`span`,`flex h-16 max-w-40 items-center truncate rounded-md border border-neutral-200 bg-neutral-50 px-2 text-[12px] text-neutral-700`,e.name??`file`),r=W(`button`,`absolute -right-1.5 -top-1.5 h-4 w-4 cursor-pointer rounded-full bg-neutral-700 text-[10px] leading-none text-white hover:bg-red-600`,`×`);return r.onclick=()=>{$o.splice(t,1),us()},W(`div`,`relative`,n,r)}))}function ds(e){if($o.length>=ls){X(`error`,`attachment limit is ${ls} files per message`);return}if(e.size>33554432){X(`error`,`${e.name||`file`} is too large (32MB max)`);return}let t=new FileReader;t.onload=()=>{let n=t.result;$o.push({data:n.slice(n.indexOf(`,`)+1),mimeType:e.type||`application/octet-stream`,name:e.name||void 0}),us()},t.readAsDataURL(e)}async function fs(e){let t=[];for(let n of e){let e=await l(`/api/inbox`,n);if(!e.ok)return null;let{path:r}=await e.json();t.push(Zr(r))}return t}var ps=e=>`pier.draft.${e}`;function ms(){let e=Vo.sessionId();e&&(Z.value.trim()?localStorage.setItem(ps(e),Z.value):localStorage.removeItem(ps(e)))}function hs(e){Z.value=localStorage.getItem(ps(e))??``,gs(),$o=[],us()}function gs(){Z.style.height=`auto`,Z.style.height=`${Math.min(Z.scrollHeight,192)}px`}var _s=!1;async function vs(e,t){let n=(t??Z.value).trim(),r=t===void 0?$o:[],i=Vo.sessionId();if(!(!n&&r.length===0||!i)){if(t===void 0){if(_s)return;_s=!0,Z.value=``,gs(),ms(),$o=[],us()}try{let t=[];if(r.length){let e=await fs(r);if(e===null){X(`error`,`attachment upload failed`),Z.value=[n,Z.value.trim()].filter(Boolean).join(`
74
+ `),gs(),ms(),$o=r,us();return}t=e}let a=[n,...t].filter(Boolean).join(`
75
+ `),o=Vo.sessionState()===`idle`&&e===`auto`;o?Vo.setState(`streaming`):os(),(o||e===`steer`)&&(is(a),X(`user`,a),Ba(!0));let s=await l(`/api/sessions/${i}/messages`,{text:a,mode:e});if(!s.ok){let e=await u(s,`send failed`);await Vo.reload(i),X(`error`,e)}}finally{t===void 0&&(_s=!1)}}}async function ys(e){let t=Vo.sessionId();if(!t)return;cs([],[]);let n=await l(`/api/sessions/${t}/queue/deliver`,{mode:e});n.ok||X(`error`,`queue ${e} failed: ${n.status}`)}async function bs(){let e=Vo.sessionId();if(!e)return;let t=await fetch(`/api/sessions/${e}/queue/recall`,{method:`POST`});if(!t.ok)return;let{messages:n}=await t.json();n.length&&(Z.value=[Z.value.trim(),...n].filter(Boolean).join(`
76
+ `),gs(),ms(),Z.focus()),cs([],[])}function xs(e){Vo=e,ts();let t=()=>{let e=Vo.sessionId();e&&fetch(`/api/sessions/${e}/abort`,{method:`POST`})};Ko.onclick=t,Lo(Ko,`Stop the running turn`,t,()=>Vo.sessionState()===`streaming`&&Vo.chatVisible()),U(`#queue-steer`).onclick=()=>void ys(`steer`),U(`#queue-restart`).onclick=()=>void ys(`restart`),U(`#queue-recall`).onclick=()=>void bs(),Ho.onsubmit=e=>{e.preventDefault(),vs(`auto`)},zo(Z,[`/`],`Write a message`,ns,Vo.chatVisible),Z.onfocus=za,Z.oninput=()=>{gs(),ms()};let n=!matchMedia(`(pointer: coarse)`).matches;Z.onkeydown=e=>{e.isComposing||e.keyCode===229||n&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),vs(`auto`))},Z.onpaste=e=>{for(let t of e.clipboardData?.items??[]){let e=t.kind===`file`?t.getAsFile():null;e&&ds(e)}let t=e.clipboardData?.getData(`text/plain`)??``,n=t.trim();!n||n===t||(e.preventDefault(),Z.setRangeText(n,Z.selectionStart??0,Z.selectionEnd??0,`end`),gs(),ms())},Y.ondragover=e=>e.preventDefault(),Y.ondrop=e=>{e.preventDefault();for(let t of e.dataTransfer?.files??[])ds(t)},U(`#attach`).onclick=()=>Zo.click(),Zo.onchange=()=>{for(let e of Zo.files??[])ds(e);Zo.value=``},os()}var Ss=`pier.push`,Cs=`/sw.js`,ws=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.maxTouchPoints>1&&/Macintosh/.test(navigator.userAgent),Ts=()=>matchMedia(`(display-mode: standalone)`).matches||navigator.standalone===!0;function Es(){return window.isSecureContext?ws()&&!Ts()?`On iPhone and iPad, notifications work only from the installed app: Share → Add to Home Screen, then open Pier from that icon.`:!(`serviceWorker`in navigator)||!(`PushManager`in window)||!(`Notification`in window)?`This browser has no Web Push support.`:``:`Notifications need HTTPS. Reach this Pier through its public URL, not over plain http.`}var Ds=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android/,`Android`],[/Macintosh/,`Mac`],[/Windows/,`Windows`]],Os=[[/Edg\//,`Edge`],[/Chrome\//,`Chrome`],[/Firefox\//,`Firefox`],[/Safari\//,`Safari`]];function ks(){let e=navigator.userAgent,t=(t,n)=>t.find(([t])=>t.test(e))?.[1]??n;return`${t(Ds,`Linux`)} · ${t(Os,`browser`)}${Ts()?` (installed)`:``}`}var As=e=>{let t=atob(e.replace(/-/g,`+`).replace(/_/g,`/`)),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},js=null;async function Ms(){return!(`serviceWorker`in navigator)||!window.isSecureContext?null:(js??=await navigator.serviceWorker.register(Cs,{scope:`/`}).catch(e=>(console.warn(`service worker registration failed`,e),null)),js)}var Ns=(e,t)=>{let n=e?new Uint8Array(e):null;return n?.length===t.length&&n.every((e,n)=>e===t[n])};async function Ps(e){let{publicKey:t}=await(await fetch(`/api/push`)).json(),n=As(t),r=await e.pushManager.getSubscription();if(r){if(Ns(r.options.applicationServerKey,n))return r;await r.unsubscribe()}return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n})}async function Fs(e){return l(`/api/push/subscribe`,{...e.toJSON(),label:ks()})}async function Is(){zs();let e=await Ms();if(!(!e||localStorage.getItem(Ss)!==`on`)&&!(!(`Notification`in window)||Notification.permission!==`granted`))try{await Fs(await Ps(e))}catch(e){console.warn(`re-registering this browser for notifications failed`,e)}}var Ls=null,Rs=null;function zs(){window.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Ls=e,Rs?.()}),window.addEventListener(`appinstalled`,()=>{Ls=null,Rs?.()})}function Bs(e){let t=navigator;(e>0?t.setAppBadge?.(e):t.clearAppBadge?.())?.catch(()=>{})}function Vs(){let e=W(`span`,`text-[11.5px]`,``),t=G(`Send a test notification`),n=W(`div`,`flex items-center gap-3`,t,e),r=W(`div`,`flex flex-col gap-4`),i=()=>localStorage.getItem(Ss)===`on`;async function a(){J(e,`saving`,`asking this browser…`);let t=await Notification.requestPermission();if(t!==`granted`)return localStorage.setItem(Ss,`off`),c(),J(e,`failed`,t===`denied`?`Notifications are blocked for this site — allow them in the browser's site settings, then try again.`:`No answer to the permission prompt.`);let n=await Ms();if(!n)return J(e,`failed`,`This browser refused to register a service worker.`);try{let t=await Fs(await Ps(n));if(!t.ok)return J(e,`failed`,await u(t,`Could not register this browser`));localStorage.setItem(Ss,`on`),c(),J(e,`saved`,`This browser will be notified when a turn finishes unseen.`)}catch(t){J(e,`failed`,`Could not subscribe: ${String(t)}`)}}async function o(){localStorage.setItem(Ss,`off`),c();let t=await(await Ms())?.pushManager.getSubscription();t&&(await l(`/api/push/unsubscribe`,{endpoint:t.endpoint}),await t.unsubscribe()),J(e,`idle`,`This browser will not be notified.`)}t.onclick=()=>{J(e,`saving`,`sending…`),(async()=>{let t=await l(`/api/push/test`,{});if(!t.ok)return J(e,`failed`,await u(t,`Could not send`));let{sent:n,failed:r}=await t.json();J(e,r?`failed`:`saved`,`Handed ${String(n)} device(s) to their push service${r?`, ${String(r)} refused`:``}.`)})()};function s(){if(!Ls)return[];let e=G(`Install Pier`,!0);return e.onclick=()=>{let e=Ls;e&&e.prompt().then(()=>e.userChoice).finally(()=>{Ls=null,c()})},[W(`div`,`flex items-center gap-3`,e,W(`span`,`text-[11.5px] leading-snug text-neutral-500`,`Its own window and icon — and where notifications look like an app's.`))]}function c(){let e=Es();if(e){r.replaceChildren(...s(),W(`p`,`text-[12.5px] leading-snug text-neutral-500`,e));return}let c=i()&&Notification.permission===`granted`;t.disabled=!c,r.replaceChildren(...s(),rr(`Notify this device`,`A turn that finishes while nobody is looking at it becomes a notification here. Per browser — each device is enabled on its own.`,c,e=>void(e?a():o())),n)}return Rs=c,c(),Qn(`Notifications`,`Web Push, so a finished turn reaches you with the workbench closed. Installed — Chrome's address-bar icon, or Share → Add to Home Screen on iOS — Pier notifies you the way an app does.`,r)}var Hs=null;function Us(e){Hs&&!Hs.contains(e.target)&&Q()}function Ws(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),Q())}function Gs(e){Hs&&!Hs.contains(e.target)&&Q()}function Q(){Hs&&=(document.removeEventListener(`pointerdown`,Us,!0),document.removeEventListener(`keydown`,Ws,!0),window.removeEventListener(`scroll`,Gs,!0),window.removeEventListener(`resize`,Q),Hs.remove(),null)}var Ks=()=>window.innerWidth<640;function qs(e,t){Q();let n=Ks();if(Hs=W(`div`,`fixed z-50 rounded-lg border border-neutral-200 bg-white py-1 shadow-lg ${n?`inset-x-2 bottom-2 max-h-[70dvh] overflow-y-auto pb-[calc(0.25rem+env(safe-area-inset-bottom))] text-[16px]`:`min-w-52 max-w-[min(42rem,calc(100vw-1rem))] text-[13px]`}`),Hs.append(t),(e.closest(`dialog[open]`)??document.body).append(Hs),!n){let t=e.getBoundingClientRect();Hs.style.top=`${Math.max(8,Math.min(t.bottom+4,window.innerHeight-Hs.offsetHeight-8))}px`,Hs.style.left=`${Math.max(8,Math.min(t.left,window.innerWidth-Hs.offsetWidth-8))}px`}document.addEventListener(`pointerdown`,Us,!0),document.addEventListener(`keydown`,Ws,!0),window.addEventListener(`scroll`,Gs,!0),window.addEventListener(`resize`,Q)}function Js(e){let t=W(`button`,`flex w-full cursor-pointer items-center gap-2 px-3 text-left hover:bg-neutral-100 active:bg-neutral-100 ${Ks()?`py-3`:`py-1.5`}`,W(`span`,`flex-none w-3 text-indigo-600`,e.checked?`✓`:``),W(`span`,`truncate`,e.label));return e.hint&&t.append(W(`span`,`ml-auto flex-none text-[11.5px] text-neutral-400`,e.hint)),t.onclick=()=>e.onSelect(),t}function Ys(e,t){qs(e,W(`div`,``,...t.map(Js)))}var Xs=e=>`${e.provider}/${e.id}`,Zs=`pier.modelFavorites`,Qs=e=>`${Xs(e)}@${e.thinking}`,$s=null;async function ec(){let e=await fetch(`/api/settings`);if(!e.ok)throw Error(`HTTP ${e.status}`);return(await e.json()).modelMenu}function tc(){try{let e=JSON.parse(localStorage.getItem(Zs)??`[]`);return Array.isArray(e)?e.filter(e=>{let t=e;return!!t&&typeof t==`object`&&typeof t.provider==`string`&&typeof t.id==`string`&&typeof t.thinking==`string`}):[]}catch{return[]}}function nc(e){let t=W(`button`,`flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-3 py-1.5 text-left`,W(`span`,`w-3 flex-none text-indigo-600`,e.checked?`✓`:``),W(`span`,`truncate`,e.label));e.hint&&t.append(W(`span`,`ml-auto flex-none text-[11.5px] text-neutral-400`,e.hint)),e.title&&(t.title=e.title),t.onclick=()=>e.onSelect();let n=W(`button`,`flex-none cursor-pointer px-2 py-1.5 leading-none ${e.starred?`text-amber-500`:`text-neutral-300 opacity-0 hover:text-amber-500 group-hover/row:opacity-100`}`,e.starred?`★`:`☆`);return n.title=e.starred?`Unstar`:`Star this model + reasoning`,n.onclick=t=>{t.stopPropagation(),e.onStar()},W(`div`,`group/row flex w-full items-center hover:bg-neutral-100`,t,n)}function rc({models:e,current:t,thinkingLevel:n,thinkingLevels:r,onPick:i,onThinkingPick:a}){let o=tc(),s=n,c=W(`div`,`flex w-72 flex-col`),l=W(`div`,`flex flex-col gap-2 border-b border-neutral-200 px-2 py-2`),u=document.createElement(`input`);if(u.type=`search`,u.placeholder=`Search models`,u.setAttribute(`aria-label`,`Search models`),u.className=`w-full rounded-md border border-neutral-300 px-2 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`,l.append(u),r.length){let e=W(`label`,`flex items-center gap-2 px-1 text-[12px] text-neutral-500`),t=document.createElement(`select`);t.className=`select ml-auto rounded-md border border-neutral-300 px-2 py-1 text-[12px] text-neutral-700 focus:border-indigo-400 focus:outline-none`,t.setAttribute(`aria-label`,`Reasoning level`);for(let e of r){let n=document.createElement(`option`);n.value=e,n.textContent=fr(e),t.append(n)}t.value=n,t.onchange=()=>{s=t.value,g(u.value),a(s)},e.append(W(`span`,`font-medium`,`Reasoning`),t),l.append(e)}let d=e=>{let t=Qs(e);o=o.some(e=>Qs(e)===t)?o.filter(e=>Qs(e)!==t):[...o,e],localStorage.setItem(Zs,JSON.stringify(o)),g(u.value)},f=(e,t)=>o.some(n=>Qs(n)===`${Xs(e)}@${t}`),p=W(`div`,`max-h-72 overflow-y-auto py-1`),m=new Map(e.map(e=>[Xs(e),e])),h=(e,n,r)=>{let a=n.map(e=>({e,model:m.get(Xs(e))})).filter(e=>!!e.model&&(!r||Xs(e.model).toLowerCase().includes(r)));a.length&&p.append(W(`div`,`px-3 pb-0.5 pt-1 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),...a.map(({e,model:n})=>{let r=e.thinking??s;return nc({label:n.id,hint:e.thinking?fr(e.thinking):void 0,title:e.note,checked:!!t&&Xs(t)===Xs(n)&&s===r,starred:f(n,r),onSelect:()=>i(n,e.thinking),onStar:()=>d({provider:n.provider,id:n.id,thinking:r})})}),W(`div`,`my-1 border-t border-neutral-100`))},g=n=>{p.replaceChildren();let r=n.trim().toLowerCase();h(`Pinned`,$s??[],r),h(`Starred`,o,r);let a=new Map;for(let t of e){if(r&&!Xs(t).toLowerCase().includes(r))continue;let e=a.get(t.provider);e?e.push(t):a.set(t.provider,[t])}if(!a.size){p.append(W(`div`,`px-3 py-2 text-[12.5px] text-neutral-400`,e.length?`No matching models.`:`No models available.`));return}for(let[e,n]of a){let a=n.some(e=>!!t&&Xs(t)===Xs(e)),o=document.createElement(`details`);o.open=a||r.length>0;let c=W(`summary`,`flex cursor-pointer select-none items-center gap-1.5 px-3 py-1 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400 hover:bg-neutral-100`,W(`span`,`chev`,`▶`),W(`span`,`truncate`,e),W(`span`,`ml-auto flex-none normal-case text-neutral-300`,String(n.length)));o.append(c,...n.map(e=>nc({label:e.id,checked:!!t&&Xs(t)===Xs(e),starred:f(e,s),onSelect:()=>i(e),onStar:()=>d({provider:e.provider,id:e.id,thinking:s})}))),p.append(o)}};return u.oninput=()=>g(u.value),g(``),ec().then(e=>{let t=JSON.stringify(e)!==JSON.stringify($s);$s=e,t&&g(u.value)}).catch(e=>Co(`model menu unavailable`,e)),c.append(l,p),queueMicrotask(()=>u.focus()),c}function ic(e,t,n,r){let i=Yn(t.model?`${t.model.id}${t.thinking?` · ${fr(t.thinking)}`:``}`:t.thinking?`Pi default · ${fr(t.thinking)}`:`Pi default`,`${$n} flex cursor-pointer items-center gap-1.5 truncate text-left hover:bg-neutral-50 ${t.model?`text-neutral-700`:`text-neutral-400`}`);return i.title=t.model?`${t.model.provider}/${t.model.id}`:`Whatever the project and Pi pick`,i.onclick=()=>{let e=rc({models:n,current:t.model,thinkingLevel:t.thinking??`medium`,thinkingLevels:[...Xi],onPick:(e,n)=>{Q(),r({model:e,thinking:n??t.thinking})},onThinkingPick:e=>r({...t,thinking:e})}),a=Yn(`Pi default`,`w-full cursor-pointer px-3 py-1.5 text-left text-[12.5px] text-neutral-500 hover:bg-neutral-100`);a.onclick=()=>{Q(),r({model:null,thinking:null})};let o=W(`div`,`flex flex-col`);o.append(e,W(`div`,`border-t border-neutral-200`),a),qs(i,o)},K(e,i)}var ac=async e=>{let t=e?.startsWith(`/`)?`?path=${encodeURIComponent(e)}`:``,n=await fetch(`/api/fs/dirs${t}`);return n.ok?await n.json():null},oc=(e,t,n)=>{let r=Yn(e,`flex w-full cursor-pointer items-center gap-1.5 px-3 py-1 text-left ${t}`);return r.onclick=n,r};function sc(e,t){let n=W(`div`,`flex-none border-t border-neutral-200`),r=oc(`+ New folder`,`text-[12px] text-neutral-500 hover:bg-neutral-100`,()=>{let r=document.createElement(`input`);r.className=`w-full border-0 bg-transparent px-3 py-1 font-mono text-[12.5px] focus:outline-none`,r.placeholder=`folder-name`;let i=W(`p`,`hidden px-3 pb-1 text-[11.5px] text-red-600`);r.onkeydown=async n=>{if(n.key!==`Enter`)return;n.preventDefault();let a=await l(`/api/fs/dirs`,{path:e,name:r.value});if(!a.ok){i.textContent=(await a.json()).error??`could not create`,i.classList.remove(`hidden`);return}t((await a.json()).path)},n.replaceChildren(r,i),r.focus()});return n.append(r),n}function cc(e,t,n){let r=e=>{n(e),Q()};async function i(t){let n=await ac(t);if(!n)return;let a=W(`div`,`flex max-h-80 w-80 flex-col`),o=Yn(`Use`,`ml-auto flex-none cursor-pointer rounded bg-indigo-600 px-2 py-0.5 text-[11.5px] text-white dark:text-neutral-50`);o.onclick=()=>r(n.path);let s=W(`div`,`flex flex-none items-center gap-2 border-b border-neutral-200 px-3 py-1.5`,W(`span`,`truncate font-mono text-[11.5px] text-neutral-500`,n.path),o),c=W(`div`,`min-h-0 flex-1 overflow-y-auto py-0.5 text-[12.5px]`);n.parent&&c.append(oc(`../`,`font-mono text-neutral-500 hover:bg-neutral-100`,()=>void i(n.parent)));for(let e of n.entries)c.append(oc(e,`truncate hover:bg-neutral-100`,()=>void i(`${n.path}/${e}`.replace(`//`,`/`))));n.entries.length||c.append(W(`p`,`px-3 py-1.5 text-[12px] text-neutral-400`,`No sub-folders.`)),a.append(s,c,sc(n.path,e=>void i(e))),qs(e,a)}i(t)}function lc(e,t){let n=Yn(`Browse…`,`flex-none cursor-pointer rounded-md border border-neutral-300 px-2 py-1 text-[12px] text-neutral-600 hover:bg-neutral-100`);return n.onclick=()=>cc(n,e.value.trim()||void 0,n=>{e.value=n,e.dispatchEvent(new Event(`input`,{bubbles:!0})),t?.(n)}),n}function uc(e,t,n){let r=document.createElement(`input`);return r.className=`min-w-0 flex-1 rounded-md border border-neutral-300 bg-white px-2 py-1 font-mono text-[12.5px] focus:border-indigo-400 focus:outline-none`,r.value=e,r.placeholder=t,r.oninput=()=>n(r.value),{el:W(`div`,`flex items-center gap-1.5`,r,lc(r,n)),input:r}}var $,dc=U(`#project-tree`),fc=U(`#archive-dialog`),pc=U(`#archive-list`),mc=U(`#archive-search`),hc=U(`#archive-count`),gc=U(`#new-dialog`),_c=U(`#known-projects`),vc=`pier.collapsedProjects`,yc=new Set(bc());function bc(){try{let e=JSON.parse(localStorage.getItem(vc)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function xc(e,t){t?yc.add(e):yc.delete(e),localStorage.setItem(vc,JSON.stringify([...yc]))}function Sc(e){let t=new Map;for(let n of e){let e=t.get(n.cwd);e?e.push(n):t.set(n.cwd,[n])}return t}function Cc(e,t){return e===t?0:e===void 0?-1:t===void 0?1:e-t}function wc(e){let t=[...Sc(e)].map(([e,t])=>[e,[...t].sort((e,t)=>Cc(e.sort,t.sort)||t.createdAt-e.createdAt)]),n=e=>e.find(e=>e.projectSort!==void 0)?.projectSort,r=e=>Math.min(...e.map(e=>e.createdAt));return t.sort(([,e],[,t])=>Cc(n(e),n(t))||r(t)-r(e))}function Tc(e,t,n,r){let i=e.filter(e=>e!==t);return i.splice(i.indexOf(n)+ +!!r,0,t),i}var Ec=()=>wc($.sessions().filter(e=>e.pinned));function Dc(e,t,n,r){let i=new Map(e.map((e,t)=>[e,t]));for(let e of $.sessions()){let r=i.get(t(e));r!==void 0&&n(e,r)}Rc();let a=()=>void $.loadSessions();l(`/api/projects/order`,r).then(e=>{e.ok||a()},a)}function Oc(e,t,n,r){let i=Ec().find(([t])=>t===e);if(!i)return;let a=Tc(i[1].map(e=>e.id),t,n,r);Dc(a,e=>e.id,(e,t)=>e.sort=t,{sessions:a})}function kc(e,t,n){let r=Tc(Ec().map(([e])=>e),e,t,n);Dc(r,e=>e.cwd,(e,t)=>e.projectSort=t,{projects:r})}var Ac=null;function jc(e,t){e.style.boxShadow=t===null?``:`inset 0 ${t?-2:2}px 0 0 #818cf8`}function Mc(e,t,n,r){e.draggable=!0,e.ondragstart=e=>{e.stopPropagation(),Ac={list:t,key:n},e.dataTransfer?.setData(`text/plain`,n)},e.ondragend=()=>{Ac=null,Rc()};let i=t=>{let n=e.getBoundingClientRect();return t.clientY>n.top+n.height/2},a=e=>!Ac||Ac.list!==t||Ac.key===n?!1:(e.preventDefault(),e.stopPropagation(),!0);e.ondragover=t=>{a(t)&&jc(e,i(t))},e.ondragleave=()=>jc(e,null),e.ondrop=t=>{let n=Ac?.key;jc(e,null),a(t)&&n&&r(n,i(t))}}var Nc=`ml-auto hidden flex-none rounded px-1 leading-none text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700 group-hover:block pointer-coarse:block`;function Pc(e){let[t,n]=e.state===`streaming`?[`bg-green-500 animate-pulse`,`working…`]:e.unread?[`bg-amber-500`,`turn finished — not viewed yet`]:e.activeRuns>0?[`bg-sky-500`,`${e.activeRuns} subagent${e.activeRuns>1?`s`:``} running`]:[`bg-neutral-300`,`idle`],r=W(`span`,`h-2 w-2 flex-none rounded-full ${t}`);return r.title=n,r}async function Fc(e,t){e.pinned=t,Rc(),$.onPinsChanged(),(await l(`/api/sessions/${e.id}/pin`,{pinned:t,cwd:e.cwd,createdAt:e.createdAt,...e.title?{title:e.title}:{}})).ok||(e.pinned=!t,Rc(),$.onPinsChanged())}function Ic(e){let t=W(`li`,`group flex cursor-pointer items-center gap-1.5 py-1.5 pl-6 pr-3 hover:bg-neutral-100 ${e.id===$.currentId()?`bg-indigo-50 hover:bg-indigo-50`:``}`),n=W(`button`,Nc,`⋯`);return n.title=`Session actions`,n.onclick=t=>{t.stopPropagation(),$.sessionMenu(n,e)},t.append(Pc(e),W(`span`,`truncate`,e.title??`untitled`),n),t.onclick=()=>$.select(e.id),t.title=`Drag to reorder`,Mc(t,e.cwd,e.id,(t,n)=>Oc(e.cwd,t,e.id,n)),t}function Lc(e,t){let n=W(`span`,`flex-none text-[11px] text-neutral-400 group-hover:hidden`,String(t.length)),r=W(`button`,Nc,`⋯`);r.title=`Project actions`,r.onclick=n=>{n.preventDefault(),n.stopPropagation(),Ys(r,[{label:`New session here`,hint:Bn(e),onSelect:()=>{Q(),$.createSession(e)}},{label:`Browse files`,onSelect:()=>{Q(),$.openFiles(e)}},{label:`Terminal here`,onSelect:()=>{Q(),$.openTerminal(e)}},{label:`Remove ${t.length} session${t.length>1?`s`:``} from Projects`,onSelect:()=>{Q();for(let e of t)Fc(e,!1)}}])};let{el:i,summary:a}=qn(`border-b border-neutral-200/70`,[W(`span`,`truncate font-mono text-[11px] font-semibold uppercase tracking-wide text-neutral-500`,Bn(e)),W(`div`,`ml-auto flex flex-none items-center gap-1.5`,n,r)]);a.className+=` group px-3 py-1.5 hover:bg-neutral-100`,a.title=`${e}\nDrag to reorder`,Mc(a,``,e,(t,n)=>kc(t,e,n)),i.open=!yc.has(e),i.ontoggle=()=>xc(e,!i.open);let o=W(`ul`,`pb-1`);return o.append(...t.map(Ic)),i.append(o),i}function Rc(){let e=$.sessions();Bs(e.filter(e=>e.unread&&e.channel===`web`).length);let t=Ec();dc.replaceChildren(...t.length?t.map(([e,t])=>Lc(e,t)):[W(`p`,`px-3 py-2 text-[12.5px] leading-snug text-neutral-400`,`No projects yet — create a session, or pin one from All sessions.`)]),_c.replaceChildren(...[...Sc(e).keys()].map(e=>{let t=document.createElement(`option`);return t.value=e,t})),fc.open&&Jc()}var zc=[{name:`activity`,label:`Activity`,detail:`Console — runs, scheduled tasks, dependencies`},{name:`boards`,label:`Boards`,detail:`Console — the static pages Pier publishes`},{name:`settings`,label:`Settings`,detail:`Console — models and providers, agent files and extensions, channels, password, sign out, security`}],Bc=[],Vc=0,Hc={ArrowDown:1,ArrowUp:-1},Uc={n:1,j:1,p:-1,k:-1};function Wc(e){Bc.length&&(Vc=(e+Bc.length)%Bc.length,Bc.forEach(({el:e},t)=>e.classList.toggle(`bg-indigo-50`,t===Vc)),Bc[Vc]?.el.scrollIntoView({block:`nearest`}))}function Gc(e){let t=W(`button`,`flex-none rounded px-1.5 py-0.5 text-[11.5px] ${e.pinned?`bg-indigo-50 text-indigo-600`:`text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700`}`,e.pinned?`pinned`:`pin`);return t.title=e.pinned?`Remove from Projects`:`Pin to Projects`,t.onclick=t=>{t.stopPropagation(),Fc(e,!e.pinned)},t}function Kc(e){let t=W(`li`,`flex cursor-pointer items-center gap-2 px-3 py-1.5`);return t.append(e.session?Pc(e.session):W(`span`,`h-2 w-2 flex-none`)),t.append(W(`span`,`min-w-0 flex-1 truncate`,e.label),W(`span`,`max-w-[45%] flex-none truncate text-[11.5px] text-neutral-400`,e.detail)),e.session&&t.append(W(`span`,`flex-none text-[11px] text-neutral-400`,Rn(e.session.createdAt)),Gc(e.session)),t.onmouseenter=()=>Wc(Bc.findIndex(e=>e.el===t)),t.onclick=e.open,t}var qc=e=>W(`li`,`px-3 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-neutral-400`,e);function Jc(){let e=mc.value.trim().toLowerCase(),t=t=>!e||t.toLowerCase().includes(e),n=e=>()=>{fc.close(),e()},r=$.sessions().filter(e=>t(`${e.title??``} ${e.cwd}`)),i=(e,t)=>t.createdAt-e.createdAt,a=e=>({label:e.title??`untitled`,detail:Bn(e.cwd),open:n(()=>$.select(e.id)),session:e}),o=r.filter(e=>e.state===`streaming`),s=r.filter(e=>e.state!==`streaming`),c=[`Console`,zc.filter(e=>t(`${e.label} ${e.detail}`)).map(({name:e,label:t,detail:r})=>({label:t,detail:r,open:n(()=>$.openConsole(e))}))],l=[[`Running`,o.sort(i).map(a)],[`Projects`,s.filter(e=>e.pinned).sort(i).map(a)],[`Other sessions`,s.filter(e=>!e.pinned).sort(i).map(a)]];e?l.unshift(c):l.push(c),Bc=[];let u=[];for(let[e,t]of l)if(t.length){u.push(qc(e));for(let e of t){let t=Kc(e);Bc.push({el:t,open:e.open}),u.push(t)}}pc.replaceChildren(...u.length?u:[W(`li`,`px-3 py-3 text-[13px] text-neutral-400`,`Nothing matches.`)]),hc.textContent=String(Bc.length),Wc(Vc)}function Yc(){if(fc.open)return fc.close();mc.value=``,Vc=0,Jc(),fc.showModal(),mc.focus(),$.loadSessions().then(()=>{fc.open&&Jc()})}function Xc(e){$=e,U(`#new-cwd-row`).append(lc(U(`#new-cwd`)));let t=U(`#new-session`),n=()=>{let e=$.sessions().find(e=>e.id===$.currentId())?.cwd??``,t=U(`#new-cwd`);t.value=e,gc.showModal(),t.select()};t.onclick=n,Io(t,`shift+o`,`New session`,n,()=>gc.open),U(`#new-cancel`).onclick=()=>gc.close(),U(`#new-form`).onsubmit=()=>void $.createSession(U(`#new-cwd`).value.trim());let r=U(`#open-archive`);r.onclick=Yc,Io(r,`k`,`Search sessions and Console`,Yc,()=>fc.open),U(`#archive-close`).onclick=()=>fc.close(),mc.oninput=()=>{Vc=0,Jc()},mc.onkeydown=e=>{let t=e.altKey||e.metaKey||e.shiftKey?void 0:e.ctrlKey?Uc[e.key.toLowerCase()]:Hc[e.key];if(t!==void 0){e.preventDefault(),Wc(Vc+t);return}e.key===`Enter`&&!e.ctrlKey&&(e.preventDefault(),Bc[Vc]?.open())}}var Zc;function Qc(e){Zc=e,Bo(el,()=>{let e=Zc.currentSession();e&&(Q(),Fc(e,!e.pinned))},$c),Bo(tl,()=>{Zc.currentSession()&&(Q(),Zc.toggleFiles())},$c)}var $c=()=>document.querySelector(`dialog[open]`)!==null,el=`d`,tl=`i`,nl=U(`#chat-title`),rl=U(`#chat-menu`),il=U(`#session-meta`),al=null,ol=null,sl=null;function cl(){al=null,ol=null,sl=null,ml()}function ll(e,t,n){al=e,ol=t,sl=n,dl()}function ul(e){ol&&(ol={...ol,tokens:e},ml())}function dl(){let e=Zc.currentSession();nl.textContent=e?e.title??`Untitled session`:`no session`,rl.classList.toggle(`hidden`,!e),e&&(rl.onclick=()=>bl(rl,e)),ml(),Zc.syncBar()}var fl=(e,t)=>Math.min(100,Math.round(e/t.contextWindow*100)),pl=e=>e.tokens===null?`?/${pr(e.contextWindow)}`:`${pr(e.tokens)}/${pr(e.contextWindow)} · ${100-fl(e.tokens,e)}% left`;function ml(){let e=ol,t=e?.tokens??null,n=Zc.currentId(),r=[];if(n){let e=(e,t)=>{let r=W(`button`,`flex-none cursor-pointer font-mono ${t}`,e);return r.title=`Change model or reasoning`,r.onclick=()=>void gl(r,n),r};al&&r.push(e(al.id,`rounded bg-indigo-50 px-1.5 py-px font-medium text-indigo-700 hover:bg-indigo-100`)),sl&&r.push(e(sl,`text-neutral-500 hover:text-indigo-700`))}if(e&&t!==null){let n=fl(t,e),i=n>=90?`text-red-700`:n>=70?`text-amber-700`:`text-neutral-500`;r.push(W(`span`,`flex-none font-mono ${i}`,pr(t).toLowerCase()))}let i=r.flatMap((e,t)=>t===0?[e]:[W(`span`,`text-neutral-300`,`·`),e]);il.replaceChildren(...i),il.classList.toggle(`hidden`,r.length===0),il.classList.toggle(`flex`,r.length>0)}function hl(e,t){let n=[[`Title`,t.title??`untitled`],[`Directory`,t.cwd],[`Session`,t.id]];t.id===Zc.currentId()&&(n.push([`Model`,al?.id??`—`]),n.push([`Context`,ol?pl(ol):`—`]));let r=W(`div`,`flex max-w-80 flex-col gap-1.5 px-3 py-2`);for(let[e,t]of n){let n=W(`div`,`flex items-center gap-1.5`,W(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),Kn(`cursor-pointer text-[10.5px] uppercase tracking-wide text-neutral-400 opacity-0 hover:text-neutral-700 focus:opacity-100 group-hover:opacity-100 pointer-coarse:opacity-100`,()=>t));r.append(W(`div`,`group flex flex-col`,n,W(`span`,`break-all font-mono text-[12px] text-neutral-700`,t)))}qs(e,r)}async function gl(e,t){try{let[n,r]=await Promise.all([fetch(`/api/sessions/${t}/models`),fetch(`/api/sessions/${t}/thinking`)]);if(!n.ok||!r.ok)throw Error(`HTTP ${n.ok?r.status:n.status}`);let i=await n.json(),a=await r.json();qs(e,rc({models:i,current:t===Zc.currentId()?al:null,thinkingLevel:a.level,thinkingLevels:a.levels,onPick:(e,n)=>{Q(),_l(t,e,n)},onThinkingPick:e=>void yl(t,e)}))}catch(e){X(`error`,`model options failed: ${String(e)}`)}}async function _l(e,t,n){await vl(e,t)&&n&&await yl(e,n)}async function vl(e,t){let n=al;e===Zc.currentId()&&(al=t,dl());let r=await l(`/api/sessions/${e}/model`,t);if(!r.ok){let{error:t}=await r.json().catch(()=>({}));return e===Zc.currentId()&&(al=n,dl()),X(`error`,`model change failed: ${t??r.status}`),!1}let{model:i}=await r.json();return e===Zc.currentId()&&i&&(al=i,dl()),!0}async function yl(e,t){let n=await l(`/api/sessions/${e}/thinking`,{level:t});if(!n.ok){X(`error`,`reasoning change failed: ${n.status}`);return}let{level:r}=await n.json();e===Zc.currentId()&&(sl=r,ml())}function bl(e,t){let n=t.id===Zc.currentId();Ys(e,[{label:`Session info`,onSelect:()=>hl(e,t)},{label:t.pinned?`Remove from Projects`:`Pin to Projects`,hint:n?No(el):``,checked:t.pinned,onSelect:()=>{Q(),Fc(t,!t.pinned)}},{label:`Model`,hint:n?al?.id??`…`:``,onSelect:()=>void gl(e,t.id)},{label:`Browse files`,hint:n?No(tl):``,onSelect:()=>{Q(),Zc.openFiles(n?void 0:t.cwd)}}])}var xl=U(`#sidebar`),Sl=U(`#drawer-scrim`),Cl=U(`#mobile-title`),wl=U(`#mobile-menu`);function Tl(){delete xl.dataset.open,Sl.classList.add(`hidden`)}function El(e,t){Cl.textContent=e,wl.classList.toggle(`hidden`,!t)}var Dl=`pier.railClosed`;localStorage.getItem(Dl)===`1`&&(document.body.dataset.rail=`closed`);function Ol(e){document.body.dataset.rail=e?`closed`:``,localStorage.setItem(Dl,e?`1`:`0`)}function kl(){if(xl.dataset.open!==void 0)return Tl();xl.dataset.open=``,Sl.classList.remove(`hidden`)}var Al=()=>window.innerWidth<768,jl=20,Ml=.35,Nl=8;function Pl(){let e=-1,t=0,n=!1,r=!1,i=1,a=e=>{xl.style.transition=`none`,xl.style.transform=`translateX(${String(e-i)}px)`,Sl.classList.remove(`hidden`),Sl.style.opacity=String(e/i)},o=t=>{xl.style.transition=``,xl.style.transform=``,Sl.style.opacity=``,t?(xl.dataset.open=``,Sl.classList.remove(`hidden`)):Tl(),e=-1,r=!1};window.addEventListener(`touchstart`,a=>{if(r||(e=-1,!Al()||a.touches.length!==1))return;let o=a.touches[0],s=xl.dataset.open!==void 0;if(i=xl.offsetWidth||1,s){if(o.clientX>i)return}else{if(o.clientX>jl||a.target?.closest(`button, a, input, textarea, select`))return;a.preventDefault()}e=o.clientX,t=o.clientY,n=!s},{passive:!1}),window.addEventListener(`touchmove`,o=>{if(e<0)return;let s=o.touches[0],c=s.clientX-e;if(!r){if(Math.abs(s.clientY-t)>Math.abs(c))return void(e=-1);if(Math.abs(c)<Nl)return;r=!0}o.preventDefault(),a(Math.max(0,Math.min(i,n?c:i+c)))},{passive:!1});let s=()=>{if(e<0)return;if(!r)return void(e=-1);let t=xl.getBoundingClientRect().right;o(n?t>i*Ml:t>i*.65)};window.addEventListener(`touchend`,s),window.addEventListener(`touchcancel`,s)}function Fl(e){Pl(),U(`#drawer-toggle`).onclick=kl,Sl.onclick=Tl,wl.onclick=()=>e.sessionMenu(wl);let t=U(`#rail-toggle`);t.onclick=()=>Ol(document.body.dataset.rail!==`closed`),Io(t,`meta+b`,`Toggle sidebar`,()=>Al()?kl():Ol(document.body.dataset.rail!==`closed`))}var Il=`pier.theme`,Ll=[`system`,`light`,`dark`],Rl=window.matchMedia(`(prefers-color-scheme: dark)`),zl={system:`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5"><circle cx="8" cy="8" r="5.25"/><path d="M8 2.75a5.25 5.25 0 0 0 0 10.5z" fill="currentColor" stroke="none"/></svg>`,light:`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" class="h-3.5 w-3.5"><circle cx="8" cy="8" r="3.1"/><path d="M8 1.5v1.4M8 13.1v1.4M1.5 8h1.4M13.1 8h1.4M3.4 3.4l1 1M11.6 11.6l1 1M12.6 3.4l-1 1M4.4 11.6l-1 1"/></svg>`,dark:`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" class="h-3.5 w-3.5"><path d="M13 9.4A5.6 5.6 0 0 1 6.6 3a5.6 5.6 0 1 0 6.4 6.4z"/></svg>`},Bl=()=>{let e=null;try{e=localStorage.getItem(Il)}catch{return`system`}return e===`light`||e===`dark`?e:`system`},Vl=()=>{let e=Bl();return e===`system`?Rl.matches?`dark`:`light`:e};function Hl(){let e=Vl();document.documentElement.dataset.theme=e,U(`meta[name="theme-color"]`).setAttribute(`content`,e===`dark`?`#1c1c1c`:`#fafafa`),window.dispatchEvent(new Event(`pier:theme`))}function Ul(){let e=U(`#theme-toggle`),t=()=>{let t=Bl();e.title=`Theme: ${t}${t===`system`?` (${Vl()})`:``}`,e.innerHTML=zl[t],Hl()};e.onclick=()=>{let e=Ll[(Ll.indexOf(Bl())+1)%Ll.length];try{e===`system`?localStorage.removeItem(Il):localStorage.setItem(Il,e)}catch{}t()},Rl.addEventListener(`change`,t),t()}var Wl=`https://github.com/timqi/pier`,Gl=[`text-neutral-400`,`hover:text-neutral-700`],Kl=[`rounded-full`,`bg-emerald-50`,`px-1.5`,`text-emerald-700`,`ring-1`,`ring-inset`,`ring-emerald-600/20`,`hover:bg-emerald-100`],ql=18e5,Jl=null,Yl=U(`#version`);function Xl(e){let t=Jl?.available===!0&&Jl.latest!==null;Yl.textContent=`v${e}`,Yl.title=t?`Pier ${Jl?.latest} is out`:``,Yl.classList.remove(...t?Gl:Kl),Yl.classList.add(...t?Kl:Gl)}var Zl=e=>W(`p`,`px-3 py-1 text-[12px] leading-snug text-neutral-500`,e);function Ql(){let e=W(`div`,`flex w-72 flex-col gap-1 py-1`);if(!Jl)return e.append(Zl(`Checking the registry…`)),e;let{current:t,latest:n,available:r,canApply:i,problem:a}=Jl;e.append(W(`p`,`px-3 py-1 text-[12.5px] font-medium text-neutral-700`,r?`Pier ${n} is out`:`Pier ${t}`)),e.append(Zl(r?`You are running ${t}.`:n===null?`The registry could not be reached, so this may not be the latest.`:`This is the latest release.`));let o=W(`span`,`px-3 text-[11.5px] text-neutral-400`,``),s=W(`div`,`flex items-center gap-2 px-3 py-1.5`);if(a&&e.append(W(`p`,`mx-3 my-1 rounded-md bg-red-50 px-2 py-1.5 text-[11.5px] leading-snug text-red-700`,a)),r&&i&&!a){let e=G(`Update now`,!0);e.onclick=()=>{e.disabled=!0,o.className=`px-3 text-[11.5px] text-neutral-400`,o.textContent=`starting the updater…`,(async()=>{let t=await l(`/api/update`,{});if(!t.ok){e.disabled=!1,o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await u(t,`Could not update`);return}let{draining:n}=await t.json();o.textContent=n?`Waiting for running work to finish — Pier then stops, installs and starts again.`:`Pier is stopping, installing and starting again — this page reconnects on its own.`})()},s.append(e)}let c=W(`a`,`btn text-[12.5px] no-underline`,`Source`);c.href=r?`${Wl}/releases`:Wl,c.target=`_blank`,c.rel=`noreferrer`,c.title=`Pier is free software (AGPL-3.0)`,s.append(c),e.append(s,o),r&&!i&&!a&&e.append(Zl(`No service manager owns this Pier, so it cannot restart itself — update it with: pier update`));let d=rr(`Update automatically`,i?`Installs a new release once nothing is running — no turn in flight, no task run.`:`Needs the systemd service (pier service install); nothing here can restart Pier.`,Jl.autoUpdate,e=>{Jl&&(Jl.autoUpdate=e),(async()=>{let t=await l(`/api/settings`,{autoUpdate:e},`PUT`);if(t.ok)return;Jl&&(Jl.autoUpdate=!e);let n=d.querySelector(`input`);n&&(n.checked=!e),o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await u(t,`Could not save`)})()});if(!i){let e=d.querySelector(`input`);e&&(e.disabled=!0)}return e.append(W(`div`,`mt-1 border-t border-neutral-200 px-3 pb-1 pt-2`,d)),e}async function $l(e){let t=await fetch(`/api/update`);t.ok&&(Jl=await t.json(),Xl(Jl.current||e))}function eu(e){Xl(e),Yl.onclick=e=>{e.preventDefault(),qs(Yl,Ql())};let t=()=>void $l(e).catch(()=>{});t(),setInterval(t,ql)}var tu=(e,t={})=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);return n},nu=e=>e===null?`-`:Vn(Date.now()-e),ru={light:{edge:`#a3a3a3`,callback:`#0891b2`,message:`#d97706`,scheduler:{fill:`#f5f3ff`,stroke:`#a78bfa`,text:`#5b21b6`},console:{fill:`#eff6ff`,stroke:`#93c5fd`,text:`#1d4ed8`},task:{fill:`#fffbeb`,stroke:`#fbbf24`,text:`#92400e`},process:{fill:`#f5f5f5`,stroke:`#a3a3a3`,text:`#525252`,dash:`4 3`},streaming:{fill:`#ffffff`,stroke:`#10b981`,text:`#262626`},idle:{fill:`#fafafa`,stroke:`#d4d4d4`,text:`#737373`}},dark:{edge:`#7a7a7a`,callback:`#3fc3dd`,message:`#e0a13a`,scheduler:{fill:`#2b2440`,stroke:`#7d63c9`,text:`#c9b8f5`},console:{fill:`#1f2a3d`,stroke:`#4a7fbf`,text:`#a8c8f0`},task:{fill:`#3a2f1c`,stroke:`#b8862a`,text:`#f0d49a`},process:{fill:`#262626`,stroke:`#5c5c5c`,text:`#a3a3a3`,dash:`4 3`},streaming:{fill:`#22302a`,stroke:`#10b981`,text:`#e5e5e5`},idle:{fill:`#212121`,stroke:`#4a4a4a`,text:`#9a9a9a`}}},iu=()=>ru[document.documentElement.dataset.theme===`dark`?`dark`:`light`];function au(e,t,n){let r=`sessions`,i=`active`,a={sessions:[],runs:[],messages:[]};async function o(){let t=await fetch(`/api/activity?scope=${i}`);if(!t.ok){e.replaceChildren(W(`p`,`p-4 text-[13px] text-red-600`,`Failed to load activity: ${t.status}`));return}let n=await t.json();a={...n,sessions:n.sessions.map(e=>({...e,title:zn(e.title)}))},s()}function s(){let t=W(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 px-4 max-md:hidden`,W(`span`,`font-medium`,`Activity`)),a=W(`div`,`tabstrip`);a.append(Xn(`Sessions`,r===`sessions`,()=>{r=`sessions`,s()}),Xn(`Dependencies`,r===`dependencies`,()=>{r=`dependencies`,s()}),Xn(`Tasks`,!1,()=>n()));let u=W(`div`,`ml-auto flex gap-1 max-md:ml-0 max-md:w-full`);u.append(Xn(`Active`,i===`active`,()=>{i=`active`,o()}),Xn(`Last 24h`,i===`recent`,()=>{i=`recent`,o()})),a.append(u);let d=W(`div`,`min-h-0 flex-1 overflow-auto`);r===`sessions`?c(d):l(d),e.replaceChildren(t,a,d)}function c(e){let n=document.createElement(`table`);n.className=`w-full min-w-[38rem] table-fixed text-left text-[12.5px]`,n.innerHTML=`<thead class="bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
77
+ <th class="w-[34%] px-4 py-2 font-semibold">Session</th>
78
+ <th class="w-[38%] px-2 py-2 font-semibold">Project</th>
79
+ <th class="w-[14%] px-2 py-2 font-semibold">State</th>
80
+ <th class="px-2 py-2 font-semibold">Duration</th></tr></thead>`;let r=document.createElement(`tbody`);for(let e of a.sessions){let n=document.createElement(`tr`);n.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,n.onclick=()=>t(e.id),n.append(W(`td`,`px-4 py-2.5`,W(`div`,`truncate font-medium`,e.title??`Untitled session`),W(`div`,`truncate font-mono text-[11px] text-neutral-400`,e.id)),W(`td`,`truncate px-2 py-2.5 font-mono text-[11.5px]`,e.cwd||`-`),W(`td`,`px-2 py-2.5`,W(`span`,`mr-2 inline-block h-2 w-2 rounded-full ${e.state===`streaming`?`animate-pulse bg-green-500`:`bg-neutral-300`}`),e.state),W(`td`,`px-2 py-2.5 text-neutral-500`,nu(e.stateSince))),r.append(n)}n.append(r),e.append(n),a.sessions.length||e.append(W(`p`,`p-4 text-[13px] text-neutral-400`,i===`active`?`No active sessions.`:`No sessions in the last 24 hours.`))}function l(e){let r=new Map,o=[],s=(e,t,n,i)=>{r.has(e)||r.set(e,{id:e,label:t,kind:n,state:i})};for(let e of a.sessions)s(e.id,e.title??e.id.slice(0,10),`session`,e.state);for(let e of a.runs){let t=e.invokedBySessionId??`scheduler`,n=e.targetSessionId??(e.context.definition.action.type===`bash`?`process:${e.id}`:`task:${e.id}`);s(t,t===`scheduler`?`Scheduler`:t.slice(0,10),t===`scheduler`?`scheduler`:`session`),s(n,e.targetSessionId?e.targetSessionId.slice(0,10):e.context.definition.action.type===`bash`?`Bash process`:`Task`,e.targetSessionId?`session`:e.context.definition.action.type===`bash`?`process`:`task`),o.push({from:t,to:n,run:e,kind:`invocation`}),e.callbackSessionId&&(s(e.callbackSessionId,e.callbackSessionId.slice(0,10),`session`),o.push({from:n,to:e.callbackSessionId,run:e,kind:`callback`}))}for(let e of a.messages){if(!e.fromSessionId||!e.toSessionId||e.fromSessionId===e.toSessionId)continue;let t=a.runs.find(t=>t.id===e.runId);if(t){for(let t of[e.fromSessionId,e.toSessionId])s(t,t===`console`?`Console`:t.slice(0,10),t===`console`?`console`:`session`);o.push({from:e.fromSessionId,to:e.toSessionId,run:t,kind:`message`})}}if(!r.size){e.append(W(`p`,`p-4 text-[13px] text-neutral-400`,i===`active`?`No active dependencies.`:`No dependencies in the last 24 hours.`));return}let c=[...r.values()],l=new Set(o.map(e=>e.to)),u=new Map,d=c.filter(e=>!l.has(e.id)).map(e=>e.id);d.length||d.push(c[0].id);for(let e of d)u.set(e,0);for(;d.length;){let e=d.shift();for(let t of o)t.from!==e||u.has(t.to)||(u.set(t.to,u.get(e)+1),d.push(t.to))}for(let e of c)u.has(e.id)||u.set(e.id,0);let f=new Map;for(let e of c){let t=u.get(e.id);f.set(t,[...f.get(t)??[],e])}let p=Math.max(...f.keys())+1,m=Math.max(...[...f.values()].map(e=>e.length)),h=o.some(e=>e.from!==e.to&&u.get(e.from)===u.get(e.to))?40:0,g=56+p*180+(p-1)*110+h,_=56+m*46+(m-1)*30,v=new Map;for(let[e,t]of f)t.forEach((t,n)=>v.set(t.id,{x:28+e*290+90,y:28+n*76+23}));let y=tu(`svg`,{width:String(g),height:String(_),viewBox:`0 0 ${g} ${_}`,class:`block`}),b=tu(`defs`),x=iu();for(let[e,t]of[[`activity-arrow`,x.edge],[`activity-arrow-cb`,x.callback],[`activity-arrow-msg`,x.message]]){let n=tu(`marker`,{id:e,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`});n.append(tu(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:t})),b.append(n)}y.append(b);let S=new Set;for(let e of o){let t=`${e.from}→${e.to}:${e.kind}`;if(S.has(t))continue;S.add(t);let r=v.get(e.from),i=v.get(e.to),a=tu(`path`,{d:r.x===i.x?`M ${r.x+90} ${r.y} C ${r.x+90+46} ${r.y}, ${i.x+90+46} ${i.y}, ${i.x+90} ${i.y}`:(()=>{let e=i.x>r.x,t=r.x+(e?90:-90),n=i.x+(e?-90:90),a=Math.max(36,Math.abs(n-t)*.45)*(e?1:-1);return`M ${t} ${r.y} C ${t+a} ${r.y}, ${n-a} ${i.y}, ${n} ${i.y}`})(),fill:`none`,stroke:e.kind===`callback`?x.callback:e.kind===`message`?x.message:x.edge,"stroke-width":`1.5`,"marker-end":e.kind===`callback`?`url(#activity-arrow-cb)`:e.kind===`message`?`url(#activity-arrow-msg)`:`url(#activity-arrow)`});e.kind===`callback`&&a.setAttribute(`stroke-dasharray`,`6 5`),e.kind===`message`&&a.setAttribute(`stroke-dasharray`,`2 5`),a.classList.add(`cursor-pointer`),a.onclick=()=>n(e.run.taskId),y.append(a)}let C=/[\u1100-\u11FF\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/,w=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)if(n+=C.test(e[r])?2:1,n>t)return`${e.slice(0,r)}…`;return e};for(let e of c){let n=v.get(e.id),r=e.kind===`session`?e.state===`streaming`?x.streaming:x.idle:x[e.kind],i=tu(`g`,{transform:`translate(${n.x},${n.y})`});e.kind===`session`&&i.classList.add(`cursor-pointer`),i.onclick=()=>{e.kind===`session`&&t(e.id)};let a=tu(`rect`,{x:`-90`,y:`-23`,width:`180`,height:`46`,rx:`10`,fill:r.fill,stroke:r.stroke,"stroke-width":e.kind===`session`&&e.state===`streaming`?`1.5`:`1`});r.dash&&a.setAttribute(`stroke-dasharray`,r.dash),i.append(a);let o=-78;if(e.kind===`session`){let t=tu(`circle`,{cx:`-75`,cy:`0`,r:`3.5`,fill:r.stroke});if(e.state===`streaming`){let e=tu(`animate`,{attributeName:`opacity`,values:`1;0.3;1`,dur:`1.6s`,repeatCount:`indefinite`});t.append(e)}i.append(t),o=-64}let s=tu(`text`,{x:String(o),"text-anchor":`start`,"dominant-baseline":`middle`,"font-size":`11.5`,"font-weight":e.kind===`session`?`500`:`400`,fill:r.text});s.textContent=w(e.label,e.kind===`session`?22:25);let c=tu(`title`);c.textContent=e.label===e.id?e.id:`${e.label}\n${e.id}`,i.append(s,c),y.append(i)}let T=e=>W(`span`,`inline-block h-2 w-2 rounded-full ${e}`);e.append(W(`div`,`w-max p-4`,y),W(`div`,`flex flex-wrap gap-x-5 gap-y-1 border-t border-neutral-200 px-4 py-2 text-[11px] text-neutral-500`,W(`span`,``,`Solid: task invocation`),W(`span`,`text-cyan-700`,`Dashed: callback`),W(`span`,`text-amber-700`,`Dotted: supervisor/control`),W(`span`,`inline-flex items-center gap-1.5`,T(`bg-emerald-500`),`streaming`),W(`span`,`inline-flex items-center gap-1.5`,T(`bg-neutral-300`),`idle`)))}let u=Hn(e,e=>{e===`dependencies`?r=`dependencies`:e===`sessions`&&(r=`sessions`),o()},()=>{e.replaceChildren(),a={sessions:[],runs:[],messages:[]}});return window.addEventListener(`pier:theme`,()=>{u.visible&&s()}),Object.assign(u,{refresh(){u.visible&&o()}})}function ou(e,t){let n=[],r=``,i=W(`header`,`sticky top-0 z-30 flex h-10 items-center gap-3 border-b border-neutral-200 bg-white px-4`,W(`span`,`font-medium max-md:hidden`,`Boards`)),a=W(`div`,`px-4 py-5`);e.append(W(`div`,`min-h-0 flex-1 overflow-y-auto`,i,a));async function o(e,t){let n=await l(`/api/boards/${e}`,{public:t},`PATCH`);n.ok||(r=`Could not change ${e}: ${n.status}`,await f())}async function s(e){let t=await fetch(`/api/boards/${e}`,{method:`DELETE`});t.ok||(r=`Could not delete ${e}: ${t.status}`),await f()}function c(e){let n=W(`div`,`group flex flex-col gap-1 border-b border-neutral-200/70 px-1 py-2.5 last:border-b-0`),r=document.createElement(`a`);r.className=`truncate font-medium text-neutral-800 hover:text-indigo-700`,r.href=`/boards/${e.slug}/`,r.target=`_blank`,r.rel=`noreferrer`,r.textContent=e.title;let i=W(`div`,`flex items-center gap-2`,r,W(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,e.slug)),a=rr(``,``,e.public,t=>{e.public=t,o(e.slug,t)});a.className=`ml-auto flex flex-none cursor-pointer items-center gap-1.5 text-[11.5px] text-neutral-500`,a.append(W(`span`,``,`Public`));let c=Yn(`Delete`,`flex-none cursor-pointer text-[11.5px] text-neutral-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100`);c.title=`Renames the folder on disk; nothing is erased`,c.onclick=()=>void s(e.slug),i.append(a,c),n.append(i);let l=W(`div`,`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-neutral-500`);e.description&&l.append(W(`span`,`min-w-0 truncate`,e.description)),l.append(W(`span`,`flex-none text-neutral-400`,Rn(Date.parse(e.updatedAt))));for(let n of e.sessions){let e=Yn(n.slice(0,8),`flex-none cursor-pointer font-mono text-indigo-600 hover:underline`);e.title=`Open session ${n}`,e.onclick=()=>t(n),l.append(e)}if(e.public){let t=W(`span`,`flex-none font-mono text-neutral-400`,`/p/${e.slug}/`);t.title=`Public URL — anyone who can reach Pier can read this`,l.append(t)}return n.append(l),n}let u=[{title:`Public`,hint:`Readable at /p/<slug>/ by anyone who can reach Pier.`,wanted:!0},{title:`Private`,hint:`Reachable from the Console only.`,wanted:!1}];function d(){let e=W(`div`,`mx-auto flex max-w-3xl flex-col`);n.length===0&&e.append(W(`p`,`rounded-xl border border-dashed border-neutral-300 px-4 py-6 text-center text-[12.5px] text-neutral-500`,`No boards yet. Ask an agent to build one — it writes a folder under ~/.pier/boards.`));for(let{title:t,hint:r,wanted:i}of u){let a=n.filter(e=>e.public===i);if(a.length===0)continue;let o=W(`section`,`mb-6`);o.append(W(`h2`,`text-[13px] font-semibold text-neutral-700`,t)),o.append(W(`p`,`mb-1 text-[11.5px] leading-snug text-neutral-500`,r));let s=W(`div`,`rounded-xl border border-neutral-200 bg-white px-3`);s.append(...a.map(c)),o.append(s),e.append(o)}a.replaceChildren(...r?[W(`p`,`mb-3 text-[13px] text-red-600`,r)]:[],e)}async function f(){let e=await fetch(`/api/boards`);if(!e.ok)return r=`Could not load boards: ${e.status}`,d();n=await e.json(),d(),r=``}let p=Hn(e,()=>void f());return window.addEventListener(`focus`,()=>{p.visible&&f()}),p}var su=2e4,cu=e=>e.map((e,t)=>({nums:[t+1],text:e,tone:``}));function lu(e,t){let n=e.length<=su?t:null,r=Math.max(2,...e.map(e=>e.nums.reduce((e,t)=>Math.max(e,String(t).length),0))),i=W(`div`,`py-2 font-mono text-[12px] leading-[1.5]`);for(let t of e){let e=W(`div`,`flex pl-2 pr-4 ${t.tone===`add`?`bg-emerald-50`:t.tone===`del`?`bg-red-50`:``}`);for(let n of t.nums){let t=W(`span`,`flex-none select-none pr-1.5 text-right text-neutral-300`,n===``?``:String(n));t.style.width=`calc(${r}ch + 0.375rem)`,e.append(t)}e.append(uu(t,n)),i.append(e)}return i}function uu(e,t){let n=`min-w-0 flex-1 whitespace-pre-wrap [overflow-wrap:anywhere]`;if(!e.mark||e.mark[0]>=e.mark[1]){let r=Wi(e.text,t);return r.className=n,r}let[r,i]=e.mark,a=Wi(e.text.slice(r,i),t);return a.className=`rounded-xs ${e.tone===`add`?`bg-emerald-200/80`:`bg-red-200/70`}`,W(`span`,n,Wi(e.text.slice(0,r),t),a,Wi(e.text.slice(i),t))}var du=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},fu=e=>[e.subject,e.body,[[e.author,e.email?`<${e.email}>`:``].filter(Boolean).join(` `),e.at?du(e.at):``].filter(Boolean).join(` · `)].filter(Boolean).join(`
81
+
82
+ `),pu=null;function mu(){pu&&(pu.remove(),pu=null,document.removeEventListener(`pointerdown`,mu,!0),window.removeEventListener(`scroll`,mu,!0))}function hu(e,t){e.onmouseenter=()=>{mu();let n=t();if(!n)return;pu=W(`div`,`pointer-events-none fixed z-50 max-w-96 whitespace-pre-wrap rounded-lg bg-neutral-800/95 px-3 py-2 font-sans text-[11.5px] leading-snug text-neutral-100 shadow-lg`),pu.textContent=n,document.body.append(pu),document.addEventListener(`pointerdown`,mu,!0),window.addEventListener(`scroll`,mu,!0);let r=e.getBoundingClientRect();pu.style.left=`${Math.max(8,Math.min(r.left,window.innerWidth-pu.offsetWidth-8))}px`,pu.style.top=r.bottom+6+pu.offsetHeight>window.innerHeight?`${r.top-pu.offsetHeight-6}px`:`${r.bottom+6}px`},e.onmouseleave=mu}function gu(e,t,n){let r=W(`button`,`flex w-full cursor-pointer items-center gap-1.5 px-2 py-1 text-left hover:bg-neutral-100`,W(`span`,`w-3 flex-none text-indigo-600`,e.value===t?`✓`:``),W(`span`,`flex-none font-mono text-[11.5px] text-neutral-800`,e.label??e.value));return e.subject&&r.append(W(`span`,`min-w-0 truncate text-[11px] text-neutral-400`,e.subject)),e.author&&r.append(W(`span`,`ml-auto flex-none pl-1.5 text-[10.5px] text-neutral-400`,`${e.author} · ${e.at?Rn(e.at):``}`)),hu(r,()=>fu(e)),r.onclick=()=>n(e.value),r}function _u(e,t,n,r,i){let{base:a,head:o}=n,s=()=>o&&a===`${o}~1`?o:``,c=s()?`commit`:`compare`,l=t.commits[0],u=e=>[...e?[{value:``,label:`Working tree`,subject:`the files on disk, uncommitted changes included`}]:[],{...l,value:`HEAD`},...t.refs.map(e=>({value:e.name,subject:e.subject})),...t.commits.map(e=>({...e,value:e.hash}))],d=W(`div`,`flex w-[38rem] max-w-full flex-col`);function f(){let e=(e,t)=>{let n=W(`button`,`cursor-pointer rounded-full px-2.5 py-0.5 text-[11.5px] ${c===t?`bg-indigo-50 font-medium text-indigo-700`:`text-neutral-500 hover:bg-neutral-100`}`,e);return n.onclick=()=>{c=t,f()},n},n=(e,t,n,r)=>W(`div`,`flex min-w-0 flex-1 flex-col`,W(`div`,`flex-none px-2 pb-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),W(`div`,`min-h-0 flex-1 overflow-y-auto`,...t.map(e=>gu(e,n,r)))),l=c===`compare`?W(`div`,`flex h-72 min-h-0 divide-x divide-neutral-200 pb-1`,n(`base`,u(!1),a,e=>{a=e,f(),r(a,o)}),n(`to`,u(!0),o,e=>{o=e,f(),r(a,o)})):W(`div`,`flex h-72 min-h-0 flex-col overflow-y-auto pb-1`,...t.commits.map(e=>gu({value:e.hash,...e},s(),e=>{a=`${e}~1`,o=e,Q(),r(a,o)}))),p=W(`div`,`flex-none border-t border-neutral-200`,gu({value:i,label:`↺ ${i} ↔ Working tree`,subject:`back to the default: the main line's tip vs the files on disk`},a===i&&o===``?i:``,()=>{a=i,o=``,f(),r(a,o)}));d.replaceChildren(W(`div`,`flex flex-none items-center gap-1 border-b border-neutral-200 px-2 py-1.5`,e(`Compare two points`,`compare`),e(`One commit`,`commit`)),l,...c===`compare`?[p]:[])}f(),qs(e,d)}var vu=/\.(png|jpe?g|gif|webp|avif|bmp|svg)$/i,yu={A:`text-emerald-600`,M:`text-amber-600`,D:`text-red-600`},bu=30,xu=`pier.filesPrefs`,Su=50,Cu=()=>{try{let e=JSON.parse(localStorage.getItem(xu)??`{}`);return e&&typeof e==`object`?e:{}}catch{return{}}},wu=e=>{let t=e?Cu()[e]:void 0;return typeof t?.cwd==`string`&&typeof t.base==`string`&&typeof t.head==`string`?{cwd:t.cwd,base:t.base,head:t.head}:null},Tu=(e,t)=>{let n=Cu();delete n[e],n[e]=t;let r=Object.keys(n);for(let e of r.slice(0,Math.max(0,r.length-Su)))delete n[e];try{localStorage.setItem(xu,JSON.stringify(n))}catch(e){console.warn(`Files: could not remember this folder`,e)}},Eu=(e,t=`indigo`)=>{let n=W(`button`,`min-w-0 cursor-pointer truncate rounded-md px-2 py-0.5 text-left font-mono text-[11.5px] ${t===`indigo`?`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`:`bg-neutral-100 text-neutral-600 hover:bg-neutral-200`}`,e);return n.type=`button`,n};function Du(e,t,n,r,i){let a=``,o=``,s={branch:null,refs:[],commits:[]},c=`HEAD`,l=``,u=new Map,d=!0,f=!1,p=[],m=new Set,h=null,g=null,_=W(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),v=W(`div`,`flex-none border-b border-neutral-200`),y=W(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),b=W(`aside`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[12.5px] max-md:h-2/5 max-md:w-full max-md:border-b max-md:border-r-0`,v,y),x=W(`div`,`h-full min-w-0 overflow-auto`),S=W(`div`,`pointer-events-none absolute inset-y-0 right-0 z-20 hidden w-2`),C=W(`section`,`relative min-w-0 flex-1`,x,S);e.append(_,W(`div`,`flex min-h-0 flex-1 max-md:flex-col`,b,C));let w=(e,t)=>`/api/explorer/${e}?${new URLSearchParams({root:a,...t})}`;async function T(e){let t=await fetch(e),n=null;try{n=await t.json()}catch{}if(!t.ok||n===null)throw Error(n?.error??`HTTP ${t.status}`);return n}let E=(e,t=`text-neutral-400`)=>W(`p`,`px-4 py-3 text-[12.5px] ${t}`,e),D=e=>{let t=0;for(let n of u.keys())n.startsWith(`${e}/`)&&t++;return t};function O(e,t){let n=new Set(t.map(e=>e.name)),r=e?`${e}/`:``;for(let[e,i]of u){if(i.status!==`D`||!e.startsWith(r))continue;let a=e.slice(r.length).split(`/`)[0];n.has(a)||(n.add(a),t.push({name:a,dir:e.slice(r.length).includes(`/`)}))}let i=t;return d&&s.branch&&(i=t.filter(e=>e.dir?D(`${r}${e.name}`)>0:u.has(`${r}${e.name}`))),i.sort((e,t)=>Number(t.dir)-Number(e.dir)||e.name.localeCompare(t.name)),i.map(e=>e.dir?A(`${r}${e.name}`,e.name):j(`${r}${e.name}`,e.name))}async function k(e,t){try{let{entries:n}=await T(w(`ls`,{path:t}));e.replaceChildren(...O(t,n)),e.childElementCount||e.append(E(d?`No changes.`:`Empty.`))}catch(n){let r=O(t,[]);r.length?e.replaceChildren(...r):e.replaceChildren(E(String(n),`text-red-600`))}}function A(e,t){let n=D(e),r=[W(`span`,`truncate`,t)];n&&r.push(W(`span`,`ml-auto flex-none rounded bg-amber-100/80 px-1 font-mono text-[10px] text-amber-700`,String(n)));let{el:i,summary:a}=qn(``,r);a.className+=` px-2 py-0.5 hover:bg-neutral-100`;let o=W(`div`,`pl-3`);i.append(o);let c=!1,l=()=>{c||(c=!0,o.append(E(`…`)),k(o,e))};return i.ontoggle=()=>{m[i.open?`add`:`delete`](e),i.open&&l()},(d&&s.branch&&!f||m.has(e))&&(i.open=!0,l()),i}function ee(e){g?.classList.remove(`bg-indigo-50`,`text-indigo-700`),g=e,e.classList.add(`bg-indigo-50`,`text-indigo-700`)}function j(e,t){let n=u.get(e)?.status,r=W(`button`,`flex w-full cursor-pointer items-center gap-1.5 px-2 py-0.5 pl-6 text-left hover:bg-neutral-100`,W(`span`,`truncate`,t));return n&&r.append(W(`span`,`ml-auto flex-none font-mono text-[10.5px] font-semibold ${yu[n]??`text-neutral-500`}`,n)),r.title=e,e===h&&ee(r),r.onclick=()=>{ee(r),h=e,se(e)},r}let te=()=>void k(y,``),M=(e,t)=>[...e?[W(`span`,`flex-none font-mono text-[10.5px] font-semibold text-emerald-600`,`+${e}`)]:[],...t?[W(`span`,`flex-none font-mono text-[10.5px] font-semibold text-red-600`,`−${t}`)]:[]];function ne(e,t,n){let r=u.get(e),i=W(`div`,`sticky top-0 z-10 flex items-center gap-2 border-b border-neutral-200 bg-white px-4 py-1.5 font-mono text-[11.5px] text-neutral-500`,W(`span`,`truncate`,e));r&&(i.append(W(`span`,`flex-none font-semibold ${yu[r.status]??``}`,r.status)),i.append(...M(r.add,r.del)));let a=W(`div`,`ml-auto flex flex-none items-center gap-2`);if(n&&a.append(n),t){let t=document.createElement(`a`);t.className=`flex-none text-neutral-400 hover:text-indigo-700 hover:underline`,t.href=w(`file`,{path:e}),t.download=Bn(e),t.textContent=`Download`,a.append(t)}return i.append(a),i}function N(e){let t=0;for(;t<e.length;){if(e[t].tone!==`del`){t++;continue}let n=t;for(;t<e.length&&e[t].tone===`del`;)t++;let r=t;for(;t<e.length&&e[t].tone===`add`;)t++;let i=Math.min(r-n,t-r);for(let t=0;t<i;t++){let i=e[n+t],a=e[r+t],o=Math.min(i.text.length,a.text.length),s=0;for(;s<o&&i.text[s]===a.text[s];)s++;let c=0;for(;c<o-s&&i.text[i.text.length-1-c]===a.text[a.text.length-1-c];)c++;s+c!==0&&(i.mark=[s,i.text.length-c],a.mark=[s,a.text.length-c])}}}let re=me();function ie(){S.classList.add(`hidden`),S.replaceChildren(),re.set([],[])}let ae=0,oe=e=>e===ae;function se(e){let t=++ae;return u.has(e)?P(e,t):ce(e,t)}async function ce(e,t){if(!oe(t))return;ie();let n=w(`file`,{path:e}),r=W(`div`,`min-w-0`);if(x.classList.remove(`flex`,`flex-col`),x.replaceChildren(ne(e,!0),r),vu.test(e)){let e=W(`img`,`max-w-full p-4`);e.src=n,e.onerror=()=>r.replaceChildren(E(`Could not load image.`,`text-red-600`)),r.append(e);return}if(e.toLowerCase().endsWith(`.pdf`)){let t=document.createElement(`iframe`);t.className=`h-full w-full`,t.src=n,x.replaceChildren(ne(e,!0),t),x.classList.add(`flex`,`flex-col`);return}r.append(E(`…`));let i=await fetch(n);if(!oe(t))return;if(!i.ok){let{error:e}=await i.json().catch(()=>({}));r.replaceChildren(E(e??`HTTP ${i.status}`,`text-red-600`));return}if(!(i.headers.get(`content-type`)??``).startsWith(`text/plain`)){r.replaceChildren(E(`Binary file — use Download.`));return}let a=(await i.text()).split(`
83
+ `);oe(t)&&(a.at(-1)===``&&a.pop(),r.replaceChildren(lu(cu(a),Ui(e))))}function le(e){let t=[],n=0,r=0,i=!1,a=e.split(`
84
+ `);a.at(-1)===``&&a.pop();for(let e of a){let a=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);if(a){i&&t.push({nums:[``,``],text:`⋯`,tone:``}),[n,r]=[Number(a[1]),Number(a[2])],i=!0;continue}!i||e.startsWith(`\\`)||(e.startsWith(`+`)?t.push({nums:[``,r++],text:e.slice(1),tone:`add`}):e.startsWith(`-`)?t.push({nums:[n++,``],text:e.slice(1),tone:`del`}):t.push({nums:[n++,r++],text:e.slice(1),tone:``}))}return t}function ue(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].tone;if(!r)continue;let i=t.at(-1);i&&i.end===n-1?(i.end=n,(r===`add`&&i.tone===`del`||r===`del`&&i.tone===`add`)&&(i.tone=`mixed`)):t.push({start:n,end:n,tone:r})}return t}let de={add:`bg-emerald-400`,del:`bg-red-400`,mixed:`bg-amber-400`};function fe(e,t,n){S.replaceChildren(...e.map(e=>{let r=W(`button`,`pointer-events-auto absolute w-full cursor-pointer ${de[e.tone]}`);return r.style.top=`${e.start/t*100}%`,r.style.height=`${Math.max(.4,(e.end-e.start+1)/t*100)}%`,r.title=`line ${pe(n,e.start)}`,r.onclick=()=>n[e.start].scrollIntoView({block:`center`}),r})),S.classList.remove(`hidden`)}let pe=(e,t)=>e[t]?.querySelector(`span`)?.textContent?.trim()||String(t+1);function me(){let t=[],n=[],r=-1,i=W(`span`,`flex-none text-[10.5px] text-neutral-400`),a=e=>{t.length&&(r=(r+e+t.length)%t.length,n[t[r].start].scrollIntoView({block:`center`}),i.textContent=`${r+1}/${t.length}`)},o=()=>t.length>0&&!e.classList.contains(`hidden`),s=(e,t,n,r)=>{let i=W(`button`,`icon-btn flex-none`,e);return i.onclick=()=>a(t),zo(i,r,n,()=>a(t),o),i};return{el:W(`div`,`flex flex-none items-center gap-1`,i,s(`↑`,-1,`Previous change`,[`p`,`k`]),s(`↓`,1,`Next change`,[`n`,`j`])),set(e,a){t=e,n=a,r=-1,i.textContent=`${e.length} change${e.length===1?``:`s`}`}}}async function P(e,t){ie(),x.classList.remove(`flex`,`flex-col`);let n=u.get(e)?.status!==`D`;x.replaceChildren(ne(e,n),E(`…`));try{let{diff:r}=await T(w(`diff`,{base:c,head:l,file:e,context:`99999`}));if(!oe(t))return;if(!r||/^Binary files /m.test(r))return ce(e,t);let i=le(r);N(i);let a=lu(i,Ui(e)),o=[...a.children],s=ue(i);re.set(s,o),x.replaceChildren(ne(e,n,re.el),a),fe(s,i.length,o)}catch(n){oe(t)&&x.replaceChildren(ne(e,!1),E(String(n),`text-red-600`))}}let he=()=>l&&c===`${l}~1`?l:``,F=()=>s.commits.find(e=>e.hash===he())?.subject??``,ge=()=>he()?`${he()} — ${F()||`commit`}`:`${c} ↔ ${l||`working tree`}`,_e=(e,t,n,r)=>{let i=W(`button`,`flex h-6 w-6 flex-none cursor-pointer items-center justify-center rounded-md ${n?`bg-indigo-50 text-indigo-700`:`text-neutral-400 hover:bg-neutral-100 hover:text-neutral-700`}`);return i.innerHTML=e,i.title=t,i.onclick=r,i};function ve(){let e=_e(`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5"><path d="M2.5 3h11l-4.25 5v4.5l-2.5 1.25V8L2.5 3z" stroke-linejoin="round"/></svg>`,`Show only files that differ`,d,()=>{d=!d,ve(),te()}),t=_e(`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5"><path d="m4.5 2.5 3.5 3 3.5-3M4.5 13.5l3.5-3 3.5 3" stroke-linecap="round" stroke-linejoin="round"/></svg>`,f?`Restore folders`:`Collapse all folders`,f,()=>{if(f=!f,f)p=[...m],m.clear();else for(let e of p)m.add(e);ve(),te()});if(!s.branch){v.replaceChildren(W(`div`,`flex items-center justify-end gap-1 p-1.5`,t));return}let n=Eu(ge());if(he()){let e=s.commits.find(e=>e.hash===he());hu(n,()=>e?fu(e):``)}else n.title=`Choose what to diff`;n.onclick=async()=>{await we(),_u(n,s,{base:c,head:l},(e,t)=>{c=e,l=t,Se()},Te())};let[r,i]=[0,0];for(let e of u.values())r+=e.add,i+=e.del;v.replaceChildren(W(`div`,`flex flex-col gap-1 p-2`,n,W(`div`,`flex items-center gap-1.5 pl-1`,W(`span`,`text-[11px] text-neutral-400`,`${u.size} changed file${u.size===1?``:`s`}`),...M(r,i),W(`span`,`ml-auto`),e,t)))}let ye=()=>{o&&a&&Tu(o,{cwd:a,base:c,head:l})},be=e=>{let t=e.replace(/~\d+$/,``);return!t||t===`HEAD`||s.refs.some(e=>e.name===t)||s.commits.some(e=>e.hash===t)};async function xe(){if(u=new Map,!s.branch)return;let{files:e}=await T(w(`diff`,{base:c,head:l}));for(let t of e)u.set(t.path,{status:t.status,add:t.add,del:t.del});if(u.size<=bu)for(let e of u.keys()){let t=e.split(`/`);for(let e=1;e<t.length;e++)m.add(t.slice(0,e).join(`/`))}}async function Se(){ye();try{await xe()}catch(e){ve(),y.replaceChildren(E(String(e),`text-red-600`));return}ve(),te(),h&&se(h)}function Ce(){let e=Eu(a||`Choose a folder…`,`neutral`);e.className+=` max-w-72`,e.title=`Switch folder`,e.onclick=()=>Ys(e,[...t().map(e=>({label:e,checked:e===a,onSelect:()=>{Q(),r(e)}})),{label:`Browse…`,onSelect:()=>cc(e,a||void 0,r)}]);let n=W(`button`,`icon-btn ml-auto`,`✕`);n.type=`button`,n.title=`Close Files`,n.setAttribute(`aria-label`,`Close Files`),n.onclick=i,_.replaceChildren(e,W(`span`,`truncate font-mono text-[11.5px] text-neutral-400`,s.branch?`⎇ ${s.branch}`:`no git`),n)}async function we(){if(a)try{s=await T(w(`git`,{})),Ce()}catch(e){x.replaceChildren(E(String(e),`text-red-600`))}}let Te=()=>s.refs.some(e=>e.name===`main`)?`main`:s.refs.some(e=>e.name===`master`)?`master`:`HEAD`;async function Ee(){if(Ce(),h=null,g=null,m.clear(),ie(),x.classList.remove(`flex`,`flex-col`),x.replaceChildren(E(`Select a file.`)),!a){v.replaceChildren(),y.replaceChildren(),x.replaceChildren(E(`No folder yet — pick one from the chip above.`));return}try{s=await T(w(`git`,{}))}catch(e){s={branch:null,refs:[],commits:[]},x.replaceChildren(E(String(e),`text-red-600`))}let e=wu(o),t=e&&e.cwd===a&&be(e.base)&&be(e.head)?e:null;c=t?.base??Te(),l=t?.head??``,Ce(),await Se()}return Hn(e,e=>{let r=n(),i=r?.id??``,s=e?.startsWith(`/`)?e:(i===o?a:``)||wu(i)?.cwd||r?.cwd||t()[0]||``;if(s===a&&i===o&&y.childElementCount){Ce(),we().then(Se);return}o=i,a=s,Ee()},()=>{ie(),x.classList.remove(`flex`,`flex-col`),x.replaceChildren(E(`Select a file.`))})}var Ou={display_information:{name:`Pier`,description:`Coding agent sessions in Slack threads`,background_color:`#262626`},features:{bot_user:{display_name:`Pier`,always_online:!1},app_home:{messages_tab_enabled:!0,messages_tab_read_only_enabled:!1}},oauth_config:{scopes:{bot:[`chat:write`,`reactions:write`,`channels:history`,`channels:read`,`groups:history`,`groups:read`,`im:history`,`im:write`,`mpim:history`,`mpim:read`,`mpim:write`,`users:read`,`files:read`]}},settings:{event_subscriptions:{bot_events:[`message.channels`,`message.groups`,`message.im`,`message.mpim`]},interactivity:{is_enabled:!0},socket_mode_enabled:!0,token_rotation_enabled:!1}},ku=()=>`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(Ou))}`,Au=()=>sr(`Getting a bot token`,[`Open [@BotFather](https://t.me/BotFather) in Telegram.`,"Send `/newbot`, pick a display name, then a username ending in `bot`.","Copy the token it prints (`123456789:AA…`) and paste it here.","Send `/setprivacy` → `Disable` if the bot should see plain group messages. Left enabled it only ever receives mentions, replies and commands — the usual reason a bot looks dead in a group.","Send `/setjoingroups` → `Enable`, then add the bot to your group or forum."]),ju=(e=`left`)=>sr(`Enabling topics on a group`,["In Telegram open the group → `Edit` → turn on `Topics`. Owner only; group size no longer matters.","The group becomes a forum supergroup and the existing chat becomes its `General` topic.","Make the bot an admin with `Manage Topics`. That is the one right topic creation needs — without it Pier logs the failure and answers in General instead.","Send one message in the group so Pier discovers it, then enable it under `Chats` below.","After that, a message in General opens its own topic with its own session. A reply, or anything starting with `/`, stays where it was sent."],e);function Mu(){let e=G(`Create Slack app ↗`,!0);e.classList.add(`mt-1`,`w-fit`),e.onclick=()=>window.open(ku(),`_blank`,`noreferrer`);let t=Kn(`btn w-fit text-[12.5px]`,()=>JSON.stringify(Ou,null,2));return sr(`Creating a Slack app`,[cr(`Opens Slack with every scope, event and Socket Mode already filled in. Pick your workspace → Create.`,e),"`Install to Workspace` → allow. Then `OAuth & Permissions` → copy the bot token (`xoxb-…`) into the field above.","`Basic Information` → `App-Level Tokens` → `Generate` with scope `connections:write`. Paste that `xapp-…` token below. The manifest cannot mint this one for you.","In Slack, invite the bot where you want it: `/invite @Pier`. It answers in threads only, so it never adds noise to the channel.",cr(`Prefer to paste it yourself? Create the app from a manifest and use this:`,t)])}var Nu=()=>sr(`What agent access allows`,["Gives agent sessions a `slack` tool: read a channel's history for a time range, read one thread, and post a message.",`Pier performs every call itself — the bot token is never given to the agent, and Slack's own membership rules still apply, so the bot reaches only channels it was invited to.`,`Every read fetches live from Slack — Pier keeps no message archive.`,`This includes sessions started by tasks and subagents. Switch it off if an agent should never post to your workspace on its own.`]),Pu=(e=`left`)=>sr(`How Slack threads work here`,[`Pier never posts in a channel's main flow. A message in the channel is answered in *its own thread*; a message in a thread is answered in that thread.`,`Each thread is its own Pi session, so one channel hosts many parallel sessions.`,`The same applies in a DM: every new message you send there starts its own thread and its own session. Reply *inside* a thread to continue that conversation.`,"Inside a thread Pier already owns, no `@mention` is needed — continuing that thread is addressing it.","Commands are bare words after a mention: `@bot settings`, `@bot stop`, `@bot bind <code>`. Slack's client swallows an unregistered `/command` before it ever reaches an app."],e),Fu=()=>sr(`Creating a Feishu app`,["On [open.feishu.cn](https://open.feishu.cn/app) create a 企业自建应用 (custom app). `Credentials & Basic Info` shows the App ID (`cli_…`) and App Secret — paste both here.","`Add Features` → enable **Bot** (机器人).","`Permissions` (权限管理), add: `im:message` (read messages), `im:message:send_as_bot` (send), `im:resource` (download attachments), `im:message.reactions:create` + `:read` + `:delete` (the 👀 receipt), `im:chat:readonly` (chat names for this page), `contact:user.base:readonly` (speaker names).","`Events & Callbacks` → set the mode to **长连接 (long connection)** — no public URL needed. Under Events subscribe `im.message.receive_v1` (接收消息); Callbacks gain `card.action.trigger` automatically once cards are sent, add it if listed.",`**Publish a version** (版本管理与发布 → 创建版本 → 申请发布). Nothing above takes effect until this is approved — the usual reason a configured bot stays silent.`,`Add the bot to a group (群设置 → 群机器人), or DM it directly.`]),Iu=(e=`left`)=>sr(`How Lark topics work here`,[`Pier never posts in a chat's main flow. A message in the chat is answered in *its own topic* (话题); a message inside a topic is answered there.`,`Each topic is its own Pi session, so one group hosts many parallel sessions.`,`The same applies in a DM: every new message starts its own topic and its own session. Reply *inside* a topic to continue that conversation.`,`Inside a topic Pier already owns, no @mention is needed — continuing that topic is addressing it.`,"Commands are slash words: `/stop`, `/settings`, `/bind <code>`. A bare @mention with nothing else also opens the settings panel."],e),Lu=[[`telegram`,`Telegram`],[`slack`,`Slack`],[`lark`,`Lark`]],Ru=(e,t)=>W(`span`,`flex items-center gap-1.5 text-[13px] text-neutral-400`,W(`span`,``,e),t),zu={dm:`bg-sky-50 text-sky-700 ring-sky-200`,group:`bg-neutral-100 text-neutral-600 ring-neutral-200`,forum:`bg-violet-50 text-violet-700 ring-violet-200`},Bu=`pier.channelsPlatform`;function Vu(e){let t=localStorage.getItem(Bu),n=Lu.some(([e])=>e===t)?t:`telegram`,r=null,i=[],a=W(`div`,`ml-auto flex items-center gap-1.5 text-[11.5px]`),o=W(`div`,`sticky top-0 z-30 flex items-center gap-1 border-b border-neutral-200 bg-white px-4 py-2`,a),s=W(`div`,`px-4 py-5`);e.append(W(`div`,`min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,o,s));function c(){o.replaceChildren(...Lu.map(([e,t])=>Zn(t,e===n,()=>{u&&_(),n=e,localStorage.setItem(Bu,e),v()})),a)}let u,d=!1,f=null;function p(e){if(a.replaceChildren(),e!==`clean`){if(a.className=`ml-auto flex items-center gap-1.5 text-[11.5px] ${ir[e]}`,e===`saving`)a.append(W(`span`,`spinner`),W(`span`,``,`Saving…`));else if(e===`saved`)a.append(W(`span`,``,`✓`),W(`span`,``,`Saved`)),setTimeout(()=>{a.textContent?.includes(`Saved`)&&p(`clean`)},2e3);else{let e=Yn(`Retry`,`cursor-pointer underline`);e.onclick=_,a.append(W(`span`,``,`⚠`),W(`span`,``,`Save failed`),e)}}}function m(){p(`saving`),clearTimeout(u),u=setTimeout(_,500)}let h=e=>t=>{e(t),m()};async function g(e){d=!0,p(`saving`);try{p((await l(`/api/channels/${e.platform}`,e.config,`PUT`)).ok?`saved`:`failed`)}catch{p(`failed`)}finally{d=!1;let e=f;f=null,e&&g(e)}}function _(){if(clearTimeout(u),u=void 0,!r)return;let e={platform:n,config:r};d?f=e:g(e)}async function v(){if(!i.length){let e=await fetch(`/api/models`);e.ok&&(i=await e.json())}let e=await fetch(`/api/channels/${n}`);if(!e.ok){r=null,c(),s.replaceChildren(or(`Failed to load: ${e.status}`));return}r=await e.json(),p(`clean`),w()}function y(e){let t=n===`slack`,r=n===`lark`,i=er(e.token,t?`xoxb-…`:r?`cli_…`:`123456789:AA…`,h(t=>e.token=t),!0),a=er(e.appToken,r?``:`xapp-…`,h(t=>e.appToken=t),!0),o=uc(e.cwd,`(pier process cwd)`,h(t=>e.cwd=t));return Qn(`Connection`,t?`Pier connects over Socket Mode; no public URL or webhook needed.`:r?`Pier connects over Feishu's WebSocket long connection; no public URL or webhook needed.`:`Pier polls Telegram for updates; no public URL or webhook needed.`,rr(`Enabled`,`Start the adapter when Pier boots.`,e.enabled,h(t=>{e.enabled=t,c()})),K(r?`App ID`:`Bot token`,i,{hint:`Stored locally, shown masked once saved.`,help:n===`telegram`?Au():t?Mu():Fu()}),...t?[K(`App-level token`,a,{hint:`Opens the Socket Mode connection. Needs connections:write.`}),rr(`Agent access`,`Let agent sessions read channel history and post through the slack tool. Off makes the tool refuse; inbound messages are unaffected.`,e.agentTool,h(t=>e.agentTool=t),Nu())]:[],...r?[K(`App Secret`,a,{hint:`From Credentials & Basic Info, beside the App ID.`})]:[],K(`Default working directory`,o.el,{hint:`Where sessions this channel opens start.`}))}function b(e){return Qn(`Defaults for new chats`,`Copied into a group the first time the bot sees it; changing them here never touches a group that already exists. DMs are always bound-users-only.`,rr(`Require mention in groups`,`Ignore group messages that do not @mention or reply to the bot.`,e.requireMention,h(t=>e.requireMention=t)),rr(`Require bound user`,`Only users bound with a code below can drive the agent.`,e.requireBind,h(t=>e.requireBind=t)),...n===`slack`?[Ru(`Thread mode: always on`,Pu())]:n===`lark`?[Ru(`Thread mode: always on`,Iu())]:[rr(`Topic mode`,`In a forum group, each new request opens its own topic and its own session.`,e.topicMode,h(t=>e.topicMode=t),ju())],ic(`Model & reasoning`,e,i,h(t=>{e.model=t.model,e.thinking=t.thinking,w()})))}function x(e){let t=W(`span`,`font-mono text-[15px] font-semibold tracking-widest`),r=W(`div`,`hidden items-center gap-2 rounded-lg bg-indigo-50 px-3 py-2 text-[12.5px] text-indigo-800`,t,W(`span`,`text-[11.5px] text-indigo-500`,`DM the bot /bind <code> · expires in 10 min`)),i=G(`Generate bind code`);i.onclick=async()=>{let e=await fetch(`/api/channels/${n}/bind-code`,{method:`POST`});if(!e.ok)return;let{code:i}=await e.json();t.textContent=i,r.classList.replace(`hidden`,`flex`)};let a=W(`div`,`flex flex-col`);e.users.length||a.append(or(`No bound users yet.`));for(let t of e.users){let e=Yn(`Remove`,`cursor-pointer text-[11.5px] text-neutral-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100`);e.onclick=async()=>{await fetch(`/api/channels/${n}/users/${encodeURIComponent(t.id)}`,{method:`DELETE`}),await v()},a.append(W(`div`,`group flex items-center gap-2.5 border-b border-neutral-100 py-2 last:border-0`,W(`span`,`flex h-6 w-6 flex-none items-center justify-center rounded-full bg-neutral-100 text-[11px] font-semibold text-neutral-500`,(t.name[0]??`?`).toUpperCase()),W(`span`,`min-w-0 flex-1 truncate text-[13px] text-neutral-700`,t.name),W(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,t.id),e))}return Qn(`Bound users`,`A code is single-use and expires; redeeming it in a DM binds that account.`,a,W(`div`,`flex flex-col gap-2`,i,r))}function S(e,t){let r=W(`div`,`rounded-xl border px-3.5 py-3 transition-colors ${t.enabled?`border-neutral-200 bg-white`:`border-neutral-200 bg-neutral-50/60`}`),a=W(`div`,`flex items-center gap-2`,W(`span`,`min-w-0 flex-1 truncate text-[13px] font-medium ${t.enabled?`text-neutral-800`:`text-neutral-400`}`,t.name||t.id),ar(t.kind,zu[t.kind]),W(`span`,`flex-none font-mono text-[11px] text-neutral-400`,t.id)),o=rr(``,``,t.enabled,h(e=>{t.enabled=e,w()}));o.classList.add(`flex-none`,`items-center`),a.append(o);let s=W(`div`,`mt-3 flex flex-wrap items-center gap-x-6 gap-y-2`);t.kind===`dm`?s.append(W(`span`,`text-[13px] text-neutral-400`,n===`telegram`?`Direct message · bound users only, mention and topics not applicable`:`Direct message · bound users only, mention not applicable`)):s.append(rr(`Require mention`,``,t.requireMention,h(e=>t.requireMention=e)),rr(`Require bind`,``,t.requireBind,h(e=>t.requireBind=e)),n===`slack`?Ru(`Thread mode: always on`,Pu(`right`)):n===`lark`?Ru(`Thread mode: always on`,Iu(`right`)):t.kind===`forum`?rr(`Topic mode`,``,t.topicMode,h(e=>t.topicMode=e),ju(`right`)):Ru(`Topic mode: forum groups only`,ju(`right`)));let c=W(`div`,`mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2`,K(`Working directory`,uc(t.cwd,``,h(e=>t.cwd=e)).el),ic(`Model & reasoning`,t,i,h(e=>{t.model=e.model,t.thinking=e.thinking,w()})));return r.append(a,s,c),r}function C(e){let t=W(`div`,`flex flex-col gap-2.5`);return e.chats.length?t.append(...e.chats.map(t=>S(e,t))):t.append(or(`None yet. Chats appear here after the bot sees a message in them.`)),Qn(n===`slack`?`Channels`:`Chats`,`Discovered from inbound traffic — no platform reliably lists every chat a bot is in.`,t)}function w(){if(!r)return;c();let e=W(`div`,`mx-auto flex max-w-3xl flex-col gap-4`);e.append(y(r),b(r),x(r),C(r)),s.replaceChildren(e)}return Hn(e,()=>void v(),()=>{u&&_()})}function Hu(e,t){let n=`global`,r=null,i=0,a=0,o=``,s=null,c=[],d=``,f=document.createElement(`select`);f.className=`select w-full rounded-md border border-neutral-300 px-2 py-1 text-[12.5px] focus:border-indigo-400 focus:outline-none`,f.onchange=()=>{n=f.value,r=null,E.clear(),b()};let p=W(`div`,`flex flex-none flex-col gap-1 border-b border-neutral-200 px-3 pb-2.5 pt-2`);p.append(W(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,`Scope`),f);let m=W(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),h=W(`nav`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[13px]`);h.append(p,m);let g=W(`div`,`flex min-w-0 flex-1 flex-col`),_=W(`div`,`flex min-h-0 flex-1`);_.append(h,g),e.append(_);let v=(e=``)=>`?scope=${encodeURIComponent(n)}${e}`;async function y(){if(n!==`global`){c=[],d=``;return}let e=await fetch(`/api/settings`,{cache:`no-store`});if(!e.ok){c=[],d=await u(e,`could not be loaded`);return}c=(await e.json()).extensionCatalog,d=``}async function b(){let e=++i;a++;let[t]=await Promise.all([fetch(`/api/config${v()}`,{cache:`no-store`}),y()]);if(e!==i)return;if(!t.ok){O(null),A(`failed to load config: ${t.status}`);return}let c=await t.json();e===i&&(n===`global`&&c.dir&&(o=c.dir,N()),s=c,O(c),r||k())}function x(e){return W(`div`,`px-3 pb-0.5 pt-2.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e)}let S=()=>{let e=W(`span`,`flex-none rounded bg-neutral-100 px-1 text-[10px] font-semibold uppercase tracking-wide text-neutral-500`,`link`);return e.title=`Reached through a symlink`,e},C=()=>W(`span`,`flex-none rounded bg-emerald-50 px-1 text-[10px] font-semibold uppercase tracking-wide text-emerald-700`,`on`);function w(e,t,n,r,i=0,a){let o=W(`button`,`flex w-full cursor-pointer items-center gap-1.5 py-1 pr-3 text-left hover:bg-neutral-100 ${t?`bg-indigo-50 hover:bg-indigo-50`:``} ${n?`text-neutral-400`:``}`);return o.append(W(`span`,`truncate`,e)),a&&o.append(a),o.style.paddingLeft=`${20+i*14}px`,o.title=e,o.onclick=r,o}function T(e){let t={files:[],dirs:new Map,link:!0};for(let n of e){let e=n.name.split(`/`),r=t;for(let t of e.slice(0,-1)){let e=r.dirs.get(t);e||r.dirs.set(t,e={files:[],dirs:new Map,link:!0}),e.link&&=n.link,r=e}r.files.push({name:e[e.length-1],link:n.link})}return t}let E=new Set;function D(e,t,n,r,i,a){let o=[];for(let[s,c]of t.dirs){let t=n?`${n}/${s}`:s,l=`${e}:${t}`,u=document.createElement(`details`);u.open=E.has(l),u.ontoggle=()=>u.open?E.add(l):E.delete(l);let d=W(`summary`,`flex cursor-pointer select-none items-center gap-1 truncate py-1 pr-3 hover:bg-neutral-100`);d.style.paddingLeft=`${20+r*14}px`,d.title=t,d.append(W(`span`,`chev`,`▶`),W(`span`,`truncate text-neutral-600`,s)),c.link&&d.append(S()),u.append(d,...D(e,c,t,r+1,i,a)),o.push(u)}for(let s of t.files){let t={type:`resource`,kind:e,name:n?`${n}/${s.name}`:s.name};o.push(w(s.name,i(t),!1,()=>a(t),r,s.link?S():void 0))}return o}function O(e){if(!e){m.replaceChildren();return}let t=e=>JSON.stringify(e)===JSON.stringify(r),i=t=>{r=t,O(e),t.type===`file`?j(t.name):t.type===`bundled`?te(t.name):ne(t.kind,t.name)},a=[];a.push(x(`Files`));for(let n of e.files){let e={type:`file`,name:n.name};a.push(w(n.name,t(e),!n.exists,()=>i(e)))}if(n===`global`){a.push(x(`bundled with Pier`)),d?a.push(W(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-red-600`,d)):c.length||a.push(W(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`));for(let e of c){let n={type:`bundled`,name:e.name};a.push(w(e.name,t(n),!1,()=>i(n),0,e.enabled?C():void 0))}}for(let n of[`extensions`,`skills`]){a.push(x(`${n} (read-only)`));let r=e.resources[n];r.length||a.push(W(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`)),a.push(...D(n,T(r),``,0,t,i))}m.replaceChildren(...a)}function k(){g.replaceChildren(W(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Select a file to edit, or browse extensions and skills.`))}function A(e){g.replaceChildren(W(`p`,`px-4 py-3 text-[13px] text-red-600`,e))}let ee=(e,...t)=>W(`div`,`flex flex-none items-center gap-3 border-b border-neutral-200 px-4 py-2`,W(`span`,`font-mono text-[12.5px] text-neutral-500`,e),...t);async function j(e){let t=++a,n=await fetch(`/api/config/files/${encodeURIComponent(e)}${v()}`,{cache:`no-store`});if(!n.ok){t===a&&A(`failed to load ${e}: ${n.status}`);return}let{content:r}=await n.json();if(t!==a)return;let i=r,o=W(`span`,`text-[11.5px] text-neutral-400`,``),s=W(`button`,`btn btn-primary ml-auto text-[12.5px]`,`Save`),c=document.createElement(`textarea`);c.className=`block min-h-0 flex-1 resize-none bg-white p-4 font-mono text-[13px] leading-relaxed focus:outline-none`,c.spellcheck=!1,c.value=r;let d=async()=>{if(s.disabled)return;let t=c.value;s.disabled=!0,J(o,`saving`,`saving…`);try{let n=await l(`/api/config/files/${encodeURIComponent(e)}${v()}`,{content:t,expected:i},`PUT`);if(!n.ok)return J(o,`failed`,await u(n,`save failed`));let r=await n.json();i=r.content,c.value===t?(c.value=r.content,J(o,`saved`,`saved — applies to new sessions`)):J(o,`idle`,`saved; newer changes are unsaved`)}catch(e){J(o,`failed`,`save failed: ${String(e)}`)}finally{s.disabled=!1}};s.onclick=()=>void d(),c.onkeydown=e=>{(e.metaKey||e.ctrlKey)&&e.key===`s`&&(e.preventDefault(),d())},c.oninput=()=>{J(o,`idle`,`unsaved changes`)},g.replaceChildren(ee(e,o,s),c),c.focus()}function te(e,t){a++;let n=c.find(t=>t.name===e);if(!n)return A(`unknown extension: ${e}`);let r=W(`span`,`text-[11.5px] text-neutral-400`,``);t&&J(r,t.state,t.text),g.replaceChildren(ee(n.name,W(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`ships with Pier`)),W(`div`,`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,W(`p`,`max-w-2xl text-[13px] leading-relaxed text-neutral-600`,n.summary),W(`dl`,`flex max-w-2xl flex-col gap-1.5`,...n.tools.flatMap(e=>[W(`dt`,`font-mono text-[12px] text-neutral-700`,e.name),W(`dd`,`text-[12px] leading-snug text-neutral-500`,`needs ${e.needs}`)])),rr(`Enabled`,`Loaded from inside Pier — nothing is installed and no update touches your own extensions. A session mid-turn keeps the tools it started with; the next message picks this up.`,n.enabled,e=>void M(n.name,e)),W(`p`,`max-w-2xl text-[12px] leading-snug text-neutral-400`,`An extension of your own that registers the same tool wins: this copy stands down and says so in the log.`),r))}async function M(e,t){let n=await l(`/api/settings`,{extensions:c.filter(n=>n.name===e?t:n.enabled).map(e=>e.name)},`PUT`);if(!n.ok)return te(e,{state:`failed`,text:await u(n,`could not save`)});c=(await n.json()).extensionCatalog,O(s),te(e,{state:`saved`,text:`Saved — sessions take it on their next message.`})}async function ne(e,t){let n=++a,r=await fetch(`/api/config/resource${v(`&kind=${e}&name=${encodeURIComponent(t)}`)}`,{cache:`no-store`});if(!r.ok){n===a&&A(`failed to load ${t}: ${r.status}`);return}let{content:i}=await r.json();if(n!==a)return;let o=i.split(`
85
+ `);o.at(-1)===``&&o.pop(),g.replaceChildren(ee(t,W(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`read-only`)),W(`div`,`min-h-0 flex-1 overflow-auto`,lu(cu(o),Ui(t))))}function N(){f.replaceChildren(new Option(o?`Global (${o})`:`Global`,`global`),...t().map(e=>new Option(`${Bn(e)} — ${e}`,e))),[...f.options].some(e=>e.value===n)||(n=`global`),f.value=n}return Hn(e,()=>{N(),b()})}var Uu=e=>`${e.provider}/${e.id}`,Wu=[`hardest reasoning — architecture, gnarly debugging`,`long autonomous implementation runs`,`balanced default — implementation, review`,`cheap & fast — listings, extraction, simple checks`,`cross-vendor second opinion`];function Gu(){let e=[],t=[],n=!1,r=W(`span`,`text-[11.5px]`,``),i=G(`Save menu`,!0),a=W(`div`,`flex min-w-0 flex-col gap-2`),o=W(`div`,`flex items-center gap-2`),s=W(`div`,`mx-auto flex w-full max-w-3xl min-w-0 flex-col gap-6`);function c(){n=!0,J(r,`idle`,`unsaved changes`)}function d(t){let n=q(t.note??``);n.classList.remove(`w-full`),n.classList.add(`min-w-0`,`flex-1`),n.placeholder=`why this one — pick a preset or write your own`,n.setAttribute(`list`,`model-menu-notes`),n.oninput=()=>{t.note=n.value,c()};let r=tr([[`thinking: model default`,``],...Xi.map(e=>[`thinking: ${fr(e)}`,e])],t.thinking??``);r.classList.replace(`w-full`,`w-44`),r.classList.add(`flex-none`),r.onchange=()=>{r.value?t.thinking=r.value:delete t.thinking,c()};let i=G(`Remove`);i.classList.add(`flex-none`),i.onclick=()=>{e=e.filter(e=>e!==t),c(),p()};let a=W(`span`,`w-52 flex-none truncate font-mono text-[12px] text-neutral-700`,Uu(t));return a.title=Uu(t),W(`div`,`flex min-w-0 items-center gap-2 rounded-lg border border-neutral-200 bg-white px-3 py-2 shadow-2xs max-md:flex-wrap`,a,r,n,i)}function f(){let n=t.filter(t=>!e.some(e=>Uu(e)===Uu(t))),r=tr(n.map(e=>[Uu(e),Uu(e)]),n[0]?Uu(n[0]):``);r.classList.replace(`w-full`,`flex-1`),r.classList.add(`min-w-0`);let i=G(`+ Pin model`);i.classList.add(`flex-none`,`whitespace-nowrap`),i.disabled=n.length===0,i.onclick=()=>{let t=n.find(e=>Uu(e)===r.value);t&&(e.push({...t}),c(),p())},o.replaceChildren(r,i)}function p(){a.replaceChildren(...e.length?e.map(d):[or(`Nothing pinned — every picker shows the curated catalog as is.`)]),f()}async function m(){J(r,`saving`,`saving…`);let t=await l(`/api/settings`,{modelMenu:e.map(({provider:e,id:t,thinking:n,note:r})=>({provider:e,id:t,...n?{thinking:n}:{},...r?.trim()?{note:r.trim()}:{}}))},`PUT`);if(!t.ok)return J(r,`failed`,await u(t,`Could not save`));e=(await t.json()).modelMenu,n=!1,J(r,`saved`,`Saved — agents see it on their next models call.`),p()}i.onclick=()=>void m();function h(){n||(async()=>{let[n,i]=await Promise.all([fetch(`/api/settings`),fetch(`/api/models`)]);if(!n.ok)return J(r,`failed`,await u(n,`Could not load the menu`));e=(await n.json()).modelMenu,t=i.ok?await i.json():[],r.textContent=``,p()})()}let g=W(`datalist`,``);return g.id=`model-menu-notes`,g.append(...Wu.map(e=>new Option(e))),s.append(Qn(`Model menu`,`Which few models this deployment favors, each with a usual reasoning level and one line of intent. Pinned entries lead every model picker, and agents delegating work match your notes against the task instead of guessing ids.`,K(`Pinned models`,a,{hint:`The note is what an agent matches a task against — say when to reach for it, not what it is.`}),K(`Add`,o,{hint:`The list is the live catalog — only models that exist right now can be pinned.`}),W(`div`,`flex items-center gap-3`,i,r),g)),{el:s,load:h}}var Ku=(e,t)=>{let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`http:`&&n.protocol!==`https:`)return null;let r=W(`a`,`text-indigo-600 hover:underline`,t);return r.href=n.href,r.target=`_blank`,r.rel=`noreferrer`,r};function qu(e,t,n,r){let i=document.createElement(`dialog`);i.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let a=W(`div`,`flex flex-col gap-2`),o=W(`div`,`flex flex-col gap-2`),s=W(`p`,`text-[12.5px] text-neutral-400`,`Starting…`),c=G(`Cancel`),d=(e,t)=>{s.className=`text-[12.5px] ${ir[e]}`,s.textContent=t};i.append(W(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,t),W(`div`,`flex max-h-[65vh] flex-col gap-3 overflow-y-auto px-4 py-3`,a,o,s),W(`div`,`flex justify-end border-t border-neutral-200 px-4 py-2.5`,c)),document.body.append(i),i.showModal();let f=e.id,p=e.state,m,h,g=new Set,_=!1,v=!1,y=async e=>{if(!v){if(e&&p===`running`){v=!0,c.disabled=!0;try{let e=await l(`/api/providers/flows/${f}/cancel`,{});if(!e.ok&&e.status!==404){d(`failed`,await u(e,`Could not cancel authentication flow`));return}}catch(e){d(`failed`,`Could not cancel authentication flow: ${String(e)}`);return}finally{v=!1,c.disabled=!1}}clearTimeout(m),i.close()}};c.onclick=()=>void y(!0),i.oncancel=e=>{e.preventDefault(),y(!0)},i.onclose=()=>{_=!0,clearTimeout(m),i.remove()};let b=e=>{if(e.type===`auth_url`){let t=W(`div`,`flex flex-col gap-1 text-[12.5px] text-neutral-600`);return e.instructions&&t.append(W(`p`,``,e.instructions)),t.append(Ku(e.url,`Open authorization page`)??W(`span`,`text-red-600`,`Invalid authorization URL`)),t}if(e.type===`device_code`){let t=W(`div`,`flex flex-col gap-2 text-[12.5px] text-neutral-600`);return t.append(W(`div`,`flex items-center gap-2`,W(`code`,`font-mono text-[17px] font-semibold text-neutral-800`,e.userCode),Kn(`btn text-[11px]`,()=>e.userCode))),t.append(Ku(e.verificationUri,`Open verification page`)??W(`span`,`text-red-600`,`Invalid verification URL`)),t}let t=W(`div`,`text-[12.5px] text-neutral-600`,e.message);if(e.type===`info`)for(let n of e.links??[]){let e=Ku(n.url,n.label??n.url);e&&t.append(` `,e)}return t},x=(e,t)=>{h=t.id;let n;if(t.type===`select`){let e=document.createElement(`select`);e.append(...t.options.map(e=>new Option(e.description?`${e.label} — ${e.description}`:e.label,e.id))),n=e}else{let e=q(``,t.type===`secret`?`password`:`text`);e.placeholder=t.placeholder??``,e.autocomplete=`off`,n=e}n.className=`${n.tagName===`SELECT`?`select `:``}w-full rounded-lg border border-neutral-300 bg-white px-2.5 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`;let r=G(`Continue`,!0);r.type=`submit`;let i=W(`form`,`flex flex-col gap-2`,W(`label`,`text-[12.5px] font-medium text-neutral-700`,t.message),n,W(`div`,`flex justify-end`,r));i.onsubmit=i=>{i.preventDefault(),r.disabled=!0,(async()=>{try{let r=await l(`/api/providers/flows/${e.id}/respond`,{promptId:t.id,value:n.value});if(_)return;if(!r.ok){d(`failed`,await u(r,`Could not submit response`));return}g.add(t.id),h=void 0,o.replaceChildren(),d(`saving`,`Waiting for provider…`)}catch(e){_||d(`failed`,`Could not submit response: ${String(e)}`)}finally{r.disabled=!1}})()},o.replaceChildren(i),n.focus()},S=e=>{p=e.state,a.replaceChildren(...e.events.map(b));let t=e.prompt&&!g.has(e.prompt.id)?e.prompt:void 0;if(t?.id!==h&&(t?x(e,t):(h=void 0,o.replaceChildren())),e.state===`running`){d(`saving`,t?`Waiting for your response.`:`Waiting for provider…`);return}clearTimeout(m),o.replaceChildren(),e.state===`succeeded`?d(`saved`,`${n} configured.`):d(`failed`,e.state===`cancelled`?`Cancelled.`:e.error??`Authentication failed.`),c.textContent=`Close`,c.onclick=()=>void y(!1),e.state===`succeeded`&&r()},C=async()=>{if(!(_||p!==`running`))try{let e=await fetch(`/api/providers/flows/${f}`,{cache:`no-store`});if(_)return;if(!e.ok){d(`failed`,await u(e,`Authentication status unavailable`)),e.status===404?p=`failed`:m=setTimeout(()=>void C(),1e3);return}S(await e.json()),p===`running`&&(m=setTimeout(()=>void C(),500))}catch(e){if(_)return;d(`failed`,`Authentication status unavailable: ${String(e)}`),m=setTimeout(()=>void C(),1e3)}};S(e),p===`running`&&(m=setTimeout(()=>void C(),500))}var Ju=[`anthropic`,`openai`,`openai-codex`,`google`,`openrouter`,`deepseek`],Yu=[[`OpenAI Chat Completions`,`openai-completions`],[`OpenAI Responses`,`openai-responses`],[`Anthropic Messages`,`anthropic-messages`],[`Google Generative AI`,`google-generative-ai`]],Xu=`__custom__`;async function Zu(e){let t=G(`Add provider`,!0);t.classList.add(`ml-auto`);let n=W(`div`,`flex flex-none items-center gap-3 rounded-t-xl border-b border-neutral-200/70 bg-neutral-50/70 px-4 py-2`,W(`h2`,`text-[13px] font-semibold text-neutral-700`,`Providers`),t),r=W(`div`,`min-h-0 flex-1 overflow-y-auto`);e.replaceChildren(n,r);let i=[],a=``,o=async()=>{r.replaceChildren(W(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Loading…`));try{let[e,n]=await Promise.all([fetch(`/api/providers`,{cache:`no-store`}),fetch(`/api/models`,{cache:`no-store`})]);if(i=n.ok?await n.json():[],a=n.ok?``:await u(n,`the model catalog could not be read`),!e.ok){r.replaceChildren(or(await u(e,`Could not load providers`)));return}let s=await e.json();t.onclick=()=>$u(s,void 0,o),p(s)}catch(e){r.replaceChildren(or(`Could not load providers: ${String(e)}`))}},s=async e=>{if(window.confirm(`Remove the stored credential for ${e.name}?`))try{let t=await l(`/api/providers/${encodeURIComponent(e.id)}/logout`,{});if(!t.ok){window.alert(await u(t,`Could not remove credential`));return}await o()}catch(e){window.alert(`Could not remove credential: ${String(e)}`)}},c=e=>[...new Set([...(e.models??[]).map(e=>e.id),...i.filter(t=>t.provider===e.id).map(e=>e.id)])],d=(e,t)=>W(`div`,`flex flex-col gap-1`,W(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),W(`pre`,`max-h-56 overflow-auto whitespace-pre-wrap break-all rounded-md bg-neutral-50 p-2 font-mono text-[11.5px] leading-relaxed text-neutral-600`,t)),f=async(e,t)=>{try{let n=await l(`/api/providers/${encodeURIComponent(e)}/check`,{model:t});return n.ok?await n.json():await u(n,`Could not test`)}catch(e){return`Could not test: ${String(e)}`}},p=e=>{let t=e.filter(e=>e.configured);if(!t.length){r.replaceChildren(or(`No providers configured.`));return}r.replaceChildren(...t.map(t=>{let n=W(`div`,`min-w-0 flex-1`,W(`div`,`truncate text-[13px] font-medium text-neutral-700`,t.name),W(`div`,`truncate font-mono text-[11px] text-neutral-400`,t.id)),r=t.stored===`api_key`?`API key`:t.stored===`oauth`?`OAuth`:t.source??`configured`,i=t.endpoint??`Default endpoint`,l=W(`div`,`flex min-w-32 flex-col items-start gap-1`,ar(`configured`,`bg-emerald-50 text-emerald-700 ring-emerald-200`),W(`span`,`max-w-48 truncate text-[11px] text-neutral-500`,r),W(`span`,`max-w-48 truncate text-[11px] text-neutral-400`,i));l.title=i;let u=W(`span`,`text-[11.5px]`,``),p=W(`div`,`hidden flex-col gap-2 px-4 pb-3`,u),m=W(`div`,`flex flex-wrap justify-end gap-1.5`),h=c(t);if(!h.length)J(u,`idle`,a||`No models to test: none are configured here.`),p.classList.replace(`hidden`,`flex`);else{let e=tr([[`Model to test…`,``],...h.map(e=>[e,e])],``);e.classList.add(`max-w-52`,`text-[12px]`);let n=G(`Test`);n.disabled=!0,e.onchange=()=>n.disabled=!e.value,n.onclick=()=>{let r=e.value;n.disabled=!0,p.replaceChildren(u),p.classList.replace(`hidden`,`flex`),J(u,`saving`,`asking ${r}…`),f(t.id,r).then(e=>{if(n.disabled=!1,typeof e==`string`)return J(u,`failed`,e);J(u,e.ok?`saved`:`failed`,`${e.model} ${e.ok?`answered`:`did not answer`} in ${e.ms} ms`),p.append(d(`sent`,e.request||`(the request was never made)`),d(e.ok?`answered`:`replied`,e.response))})},m.append(e,n)}if(t.builtin||t.api&&t.models){let n=G(`Edit`);n.onclick=()=>$u(e,t,o),m.append(n)}if(t.stored){let e=G(`Remove credential`);e.onclick=()=>void s(t),m.append(e)}return W(`div`,`border-b border-neutral-100`,W(`div`,`grid grid-cols-[minmax(8rem,1fr)_minmax(8rem,auto)_minmax(9rem,auto)] items-center gap-3 px-4 py-2.5 max-sm:grid-cols-[1fr_auto]`,n,l,m),p)}))};await o()}function Qu(e,t){let n=t.filter(e=>!e.configured&&e.methods.length&&(e.builtin||e.api!==void 0&&e.models!==void 0)),r=(t,n)=>{if(!n.length)return;let r=document.createElement(`optgroup`);r.label=t,r.append(...n.map(e=>new Option(e.name,e.id))),e.append(r)};r(`Common`,Ju.flatMap(e=>n.filter(t=>t.id===e))),r(`More providers`,n.filter(e=>e.builtin&&!Ju.includes(e.id)).sort((e,t)=>e.name.localeCompare(t.name))),r(`Custom providers`,n.filter(e=>!e.builtin).sort((e,t)=>e.name.localeCompare(t.name))),e.append(new Option(`Custom provider…`,Xu))}function $u(e,t,n){let r=document.createElement(`dialog`);r.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let i=document.createElement(`select`);i.className=`${$n} select`,t||Qu(i,e);let a=q(),o=q(),s=q(),c=document.createElement(`select`);c.className=`${$n} select`,c.append(...Yu.map(([e,t])=>new Option(e,t)));let d=nr(``,4);d.placeholder=`model-id
86
+ another-model-id`;let f=document.createElement(`input`);f.type=`checkbox`;let p=document.createElement(`select`);p.className=`${$n} select`;let m=W(`div`,`flex flex-col gap-4`),h=W(`span`,`text-[11.5px] text-red-600`,``),g=G(`Cancel`),_=G(t?`Save`:`Add`,!0);_.type=`submit`;let v=()=>t??e.find(e=>e.id===i.value),y=()=>{let e=v(),n=e?!e.builtin:i.value===Xu;a.value=e?.id??``,a.disabled=t!==void 0,o.value=e?.name??``,s.value=e?.endpoint??``,c.value=e?.api??`openai-completions`,d.value=e?.models?.map(e=>e.id).join(`
87
+ `)??``;let r=e?.models?.map(e=>e.reasoning)??[];f.checked=r.length?r.every(Boolean):!e,f.indeterminate=r.some(Boolean)&&!r.every(Boolean);let l=[];e?.configured&&l.push(new Option(`Keep current authentication`,``));let u=e?.methods??[{type:`api_key`,name:`API key`}];for(let t of u.filter(t=>e?.builtin!==!1||t.type===`api_key`))l.push(new Option(t.name,t.type));p.replaceChildren(...l);let h=[];t||h.push(K(`Provider`,i)),n?h.push(K(`Provider ID`,a),K(`Display name`,o),K(`Endpoint`,s),K(`API format`,c),K(`Models`,d),K(`Model capabilities`,W(`label`,`flex items-center gap-2 text-[12.5px] text-neutral-600`,f,W(`span`,``,`Reasoning`)))):(s.placeholder=`Provider default`,h.push(K(`Endpoint`,s))),h.push(K(`Authentication`,p)),m.replaceChildren(...h)};i.onchange=y,y();let b=W(`form`,`flex flex-col gap-4 px-4 py-3`,m,W(`div`,`flex items-center justify-end gap-2`,h,g,_)),x=!1;g.onclick=()=>{x||r.close()},r.oncancel=e=>{x&&e.preventDefault()},b.onsubmit=e=>{if(e.preventDefault(),x)return;h.textContent=``;let t=v(),m=(t?!t.builtin:i.value===Xu)?{kind:`custom`,id:a.value.trim(),...o.value.trim()?{name:o.value.trim()}:{},endpoint:s.value.trim(),api:c.value,models:[...new Set(d.value.split(`
88
+ `).map(e=>e.trim()).filter(Boolean))].map(e=>({id:e,reasoning:f.indeterminate?t?.models?.find(t=>t.id===e)?.reasoning??f.checked:f.checked}))}:{kind:`builtin`,id:t.id,...s.value.trim()?{endpoint:s.value.trim()}:{}},y=p.value||null;x=!0,_.disabled=!0,g.disabled=!0,(async()=>{try{let e=await l(`/api/providers/setup`,{setup:m,authType:y});if(!e.ok){h.textContent=await u(e,`Could not configure provider`);return}if(r.close(),e.status===202){let t=p.selectedOptions[0]?.textContent??`Authentication`;qu(await e.json(),m.id,t,()=>void n())}else await n()}catch(e){h.textContent=`Could not configure provider: ${String(e)}`}finally{x=!1,_.disabled=!1,g.disabled=!1}})()},r.append(W(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,t?`Edit ${t.name}`:`Add provider`),b),r.onclose=()=>r.remove(),document.body.append(r),r.showModal(),(t?s:i).focus()}var ed=[[`models`,`Models`],[`files`,`Agent`],[`channels`,`Channels`],[`instance`,`Instance`],[`security`,`Security`]],td=e=>ed.some(([t])=>t===e),nd=`pier.settingsTopic`;function rd(e,t,n){let r=localStorage.getItem(nd)??void 0,i=td(r)?r:`models`,a=W(`header`,`flex h-10 flex-none items-center gap-3 border-b border-neutral-200 bg-white px-4 max-md:hidden`,W(`span`,`font-medium`,`Settings`)),o=W(`div`,`tabstrip bg-white`);function s(){o.replaceChildren(...ed.map(([e,t])=>Zn(t,e===i,()=>n(e))))}let c=q();c.placeholder=`https://pier.example.com`,c.autocomplete=`off`;let d=W(`span`,`text-[11.5px]`,``),f=G(`Save`,!0);async function p(){J(d,`saving`,`saving…`);let e=await l(`/api/settings`,{publicUrl:c.value},`PUT`);if(!e.ok)return J(d,`failed`,await u(e,`Could not save`));let{publicUrl:t}=await e.json();c.value=t,J(d,`saved`,t?`Saved — boards link as ${t}/p/<slug>/`:`Cleared.`)}f.onclick=()=>void p(),c.onkeydown=e=>{e.key===`Enter`&&p()};let m=Qn(`Public URL`,`Where this Pier is reached from outside — the proxy's address, not the port it listens on.`,K(`Base URL`,c,{hint:`Agents read it to hand you a clickable board link instead of a path. Nothing here changes what Pier serves; leave it empty if Pier is only reachable locally.`}),W(`div`,`flex items-center gap-3`,f,d)),h=q(``,`password`),g=q(``,`password`),_=q(``,`password`);for(let e of[h,g,_])e.autocomplete=`off`;let v=W(`span`,`text-[11.5px]`,``),y=G(`Change password`,!0);async function b(){if(g.value!==_.value)return J(v,`failed`,`The two new passwords differ.`);J(v,`saving`,`changing…`);let e=await l(`/api/password`,{current:h.value,next:g.value});if(!e.ok)return J(v,`failed`,await u(e,`Could not change the password`));for(let e of[h,g,_])e.value=``;J(v,`saved`,`Changed. Sign in again with the new password.`),location.href=`/login`}y.onclick=()=>void b(),_.onkeydown=e=>{e.key===`Enter`&&b()};let x=Qn(`Password`,`One shared password guards every page and API route. Changing it signs out every signed-in browser, this one included.`,K(`Current password`,h),K(`New password`,g,{hint:`At least 10 characters.`}),K(`Repeat new password`,_),W(`div`,`flex items-center gap-3`,y,v)),S=G(`Reload`,!0),C=W(`span`,`text-[11.5px]`,``);S.onclick=()=>{S.disabled=!0,J(C,`saving`,`reloading…`),(async()=>{let e=await l(`/api/reload`,{});if(S.disabled=!1,!e.ok)return J(C,`failed`,await u(e,`Could not reload`));let{recycled:t,busy:n}=await e.json(),r=t?`Recycled ${t} session(s).`:`No idle session needed it.`,i=n?` ${n} still mid-turn — they take it when the turn ends.`:``;J(C,n?`idle`:`saved`,r+i)})()};let w=Qn(`Reload configuration`,`Re-reads channel configuration and lets go of idle sessions, so the next message opens them with the current agent files, skills and credentials. Saving here does this on its own — use it after something outside the Console changed a file.`,W(`div`,`flex items-center gap-3`,S,C)),T=G(`Sign out`);T.onclick=()=>{l(`/logout`,{}).finally(()=>{location.href=`/login`})};let E=Qn(`Sign out`,`Ends this browser's session. Others keep theirs — change the password to sign out everywhere.`,W(`div`,`flex items-center gap-3`,T)),D=W(`div`,`mx-auto flex max-w-2xl flex-col gap-6`,m,Vs(),w,x,E),O=e=>W(`div`,`hidden min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,W(`div`,`px-4 py-5`,e)),k=Gu(),A=W(`div`,`mx-auto flex w-full min-w-0 max-w-3xl flex-col rounded-xl border border-neutral-200 bg-white shadow-xs`),ee=W(`section`,`hidden min-h-0 flex-1 flex-col`),j=Vu(ee),te=W(`section`,`hidden min-h-0 flex-1 flex-col`),M=Hu(te,t);function ne(){v.textContent=``,(async()=>{let e=await fetch(`/api/settings`);if(!e.ok)return J(d,`failed`,await u(e,`Could not load settings`));c.value=(await e.json()).publicUrl,d.textContent=``})()}let N=W(`div`,`mx-auto flex max-w-2xl flex-col gap-6`);async function re(){let e=await fetch(`/api/secrets`);if(!e.ok){N.replaceChildren(or(await u(e,`Could not load key status`)));return}ie(await e.json())}function ie(e,t){let n=e.state===`locked`,r=W(`span`,`text-[11.5px]`,``);t&&J(r,`saved`,t);let i=W(`div`,`flex items-center gap-2`,ar(e.state,n?`bg-red-50 text-red-700 ring-red-200`:`bg-emerald-50 text-emerald-700 ring-emerald-200`),W(`span`,`text-[12.5px] text-neutral-600`,n?`Stored credentials cannot be read until the key is unlocked.`:e.mode===`vt`?`Key mode: vt:// — unlocking takes one vt approval per process start.`:`Key mode: file — the key sits raw in master.key; switch to vt:// to require an approval.`)),a=W(`a`,`text-indigo-600 hover:underline`,`vt`);a.href=`https://github.com/timqi/vt`,a.target=`_blank`,a.rel=`noreferrer`;let o=[i,W(`p`,`text-[12px] leading-snug text-neutral-500`,a,` is a small local KMS: it keeps the key wrapped and releases it only on an explicit approval — Touch ID on a Mac, a phone passkey on a headless host. Pier only stores the vt:// record, so master.key alone unlocks nothing.`)];if(n){o.push(W(`p`,`text-[12.5px] leading-snug text-red-600`,e.reason??`No reason reported.`));let t=G(`Unlock`,!0);t.onclick=()=>{J(r,`saving`,`unlocking… (vt mode waits on your approval)`),(async()=>{let e=await l(`/api/secrets/unlock`,{});if(!e.ok)return J(r,`failed`,await u(e,`Could not unlock`));ie(await e.json(),`Unlocked — channels are starting.`)})()},o.push(W(`div`,`flex items-center gap-3`,t,r))}else{let t=async(e,t,n)=>{if(!window.confirm(t))return;J(r,`saving`,e===`vt`?`rotating… (vt asks for an approval)`:`rotating…`);let i=await l(`/api/secrets/rotate`,{mode:e});if(!i.ok)return J(r,`failed`,await u(i,`Could not rotate`));ie(await i.json(),n)},n=e.mode??`file`,i=G(`Rotate key`,!0);i.onclick=()=>void t(n,`Generate a new master key? Stored credentials stay valid; the old key stops working.`,`Rotated.`);let a=n===`vt`?`file`:`vt`,s=G(a===`vt`?`Switch to vt://`:`Switch to file`);s.onclick=()=>void t(a,a===`vt`?`Move the master key into vt? Every process start will then wait on a vt approval.`:`Store the master key raw in master.key? Anyone who can read the file can read every credential.`,a===`vt`?`Switched to vt:// mode.`:`Switched to file mode.`),o.push(W(`div`,`flex items-center gap-3`,i,s,r))}N.replaceChildren(Qn(`Master key`,`Seals every credential Pier stores (channel tokens, API keys). Rotating rewraps the key file; no stored data is rewritten.`,...o))}let ae=O(D),oe=O(W(`div`,`flex flex-col gap-6`,A,k.el)),se=O(N),ce=[[`instance`,ae,ne],[`models`,oe,()=>{Zu(A),k.load()}],[`security`,se,()=>void re()]];e.append(a,o,ae,oe,ee,te,se);function le(e){td(e)&&(i=e),localStorage.setItem(nd,i),s();for(let[e,t,n]of ce){let r=e===i;t.classList.toggle(`hidden`,!r),r&&n()}i===`channels`?j.show():j.hide(),i===`files`?M.show():M.hide()}return Hn(e,le)}function id(e,t){let n=e.map(e=>[`${e.title??`Untitled`} · ${e.cwd}`,e.id]);return t&&!n.some(([,e])=>e===t)&&n.push([`Current session · ${t}`,t]),n}function ad(e,t){let n=document.createElement(`dialog`);n.className=`m-auto w-[38.75rem] max-w-[94vw] rounded-lg border border-neutral-200 p-0 shadow-xl backdrop:bg-black/20`;let r=document.createElement(`form`);r.className=`flex max-h-[88vh] flex-col`;let i=W(`span`,`mr-auto text-[12px] text-red-600`),a=W(`header`,`flex h-11 flex-none items-center border-b border-neutral-200 px-4 font-medium`,t?`Edit task`:`New task`),o=W(`div`,`grid min-h-0 flex-1 grid-cols-2 gap-3 overflow-y-auto p-4`),s=q(t?.name??``);s.required=!0;let c=q(t?.description??``),l=q(String(t?.timeoutSeconds??900),`number`);l.min=`1`,l.max=`86400`;let u=tr([[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watch`,`watch`]],t?.trigger.type??`manual`),d=tr([[`Bash`,`bash`],[`Agent`,`agent`],[`Task`,`task`]],t?.action.type??`bash`),f=tr([[`No callback`,`none`],[`Invoking session`,`origin`],[`Specific session`,`session`]],t?.callback.type??`none`),p=t?.callback.type===`session`?t.callback.sessionId:null,m=tr(id(e.sessions(),p),p??``),h=K(`Callback session`,m);h.classList.toggle(`hidden`,f.value!==`session`),f.onchange=()=>h.classList.toggle(`hidden`,f.value!==`session`),o.append(K(`Name`,s),K(`Description`,c),K(`Trigger`,u),K(`Action`,d),K(`Callback`,f),h,K(`Timeout (seconds)`,l));let g=W(`div`,`col-span-2 grid grid-cols-2 gap-3 border-t border-neutral-200 pt-3`);o.append(g);let _=()=>{g.replaceChildren();let a,o,p,h,_,v;if(u.value===`cron`)a=q(t?.trigger.type===`cron`?t.trigger.expression:`0 9 * * *`),o=q(t?.trigger.type===`cron`?t.trigger.timezone:Intl.DateTimeFormat().resolvedOptions().timeZone),g.append(K(`Cron`,a),K(`Timezone`,o));else if(u.value===`watch`){p=nr(t?.trigger.type===`watch`?t.trigger.script:``,4),v=q(t?.trigger.type===`watch`?t.trigger.cwd:e.sessions()[0]?.cwd??``),h=q(String(t?.trigger.type===`watch`?t.trigger.intervalSeconds:60),`number`),_=tr([[`Continue after matches`,`repeat`],[`Stop after first match`,`once`]],t?.trigger.type===`watch`?t.trigger.mode:`repeat`);let n=K(`Probe script (0=match, 1=no match)`,p);n.classList.add(`col-span-2`),g.append(n,K(`Probe directory`,v),K(`Interval (seconds)`,h),K(`Mode`,_))}let y,b,x,S,C,w,T,E,D,O,k;if(d.value===`bash`){b=q(t?.action.type===`bash`?t.action.cwd:e.sessions()[0]?.cwd??``),y=nr(t?.action.type===`bash`?t.action.script:``,6);let n=K(`Bash script`,y);n.classList.add(`col-span-2`),g.append(K(`Working directory`,b),W(`span`,``),n)}else if(d.value===`agent`){let n=e.sessions(),r=t?.action.type===`agent`?t.action:null,i=r?.session.mode===`reuse`?r.session.sessionId:``,a=id(n,i||null);x=tr([[`Reuse session`,`reuse`],[`Fresh child per run`,`fresh`],[`Fork caller context`,`fork`]],r?.session.mode??`fresh`),S=tr(a,i||a[0]?.[1]||``),C=q((r?.session.mode===`fresh`||r?.session.mode===`fork`?r.session.cwd??``:``)||n[0]?.cwd||``),w=nr(r?.prompt??``,6),T=tr([[`Normal project tools`,`write`],[`Read only`,`read`]],r?.launch?.capabilities??`write`),E=tr([[`Project default`,``],[`Off`,`off`],[`Low`,`low`],[`Medium`,`medium`],[`High`,`high`],[`Extra high`,`xhigh`]],r?.launch?.thinking??``),D=q(r?.launch?.model?.provider??``),O=q(r?.launch?.model?.id??``);let o=K(`Session`,S),s=K(`Child directory`,C),c=[K(`Capabilities`,T),K(`Thinking`,E),K(`Model provider (optional)`,D),K(`Model id (optional)`,O)],l=()=>{let e=x?.value===`reuse`;o.classList.toggle(`hidden`,!e),s.classList.toggle(`hidden`,e);for(let t of c)t.classList.toggle(`hidden`,e)};x.onchange=l,l();let u=K(`Prompt`,w);u.classList.add(`col-span-2`),g.append(K(`Session policy`,x),o,s,...c,u)}else k=tr(e.tasks().filter(e=>e.id!==t?.id&&!e.archived).map(e=>[e.name,e.id]),t?.action.type===`task`?t.action.taskId:``),g.append(K(`Target task`,k));r.onsubmit=r=>{r.preventDefault();let g=u.value===`manual`?{type:`manual`}:u.value===`cron`?{type:`cron`,expression:a.value,timezone:o.value}:{type:`watch`,script:p.value,cwd:v.value,intervalSeconds:Number(h.value),mode:_.value},A=d.value===`agent`&&x.value!==`reuse`?{capabilities:T.value,...E.value?{thinking:E.value}:{},...D.value.trim()&&O.value.trim()?{model:{provider:D.value.trim(),id:O.value.trim()}}:{}}:void 0,ee=d.value===`bash`?{type:`bash`,cwd:b.value,script:y.value}:d.value===`agent`?{type:`agent`,prompt:w.value,session:x.value===`reuse`?{mode:`reuse`,sessionId:S.value}:x.value===`fork`?{mode:`fork`,...C.value.trim()?{cwd:C.value.trim()}:{}}:{mode:`fresh`,cwd:C.value},...A?{launch:A}:{}}:{type:`task`,taskId:k.value},j=f.value===`origin`?{type:`origin`}:f.value===`session`?{type:`session`,sessionId:m.value}:{type:`none`},te={name:s.value,description:c.value,trigger:g,action:ee,callback:j,timeoutSeconds:Number(l.value)};i.textContent=``,od(t?.id,te,n,i,e.onSaved)}};u.onchange=_,d.onchange=_,_();let v=G(`Cancel`);v.onclick=()=>n.close();let y=G(`Save`,!0);y.type=`submit`;let b=W(`footer`,`flex flex-none justify-end gap-2 border-t border-neutral-200 px-4 py-3`);b.append(i,v,y),r.append(a,o,b),n.append(r),n.addEventListener(`close`,()=>n.remove()),document.body.append(n),n.showModal(),s.focus()}async function od(e,t,n,r,i){let a=await l(e?`/api/tasks/${e}`:`/api/tasks`,t,e?`PATCH`:`POST`);if(!a.ok){r.textContent=(await a.json()).error??`Task save failed`;return}let o=await a.json(),s=`task`in o?o.task:o;n.close(),i(s.id)}var sd=e=>e===null?`-`:new Date(e).toLocaleString(),cd=e=>e.startedAt===null?`-`:Vn((e.finishedAt??Date.now())-e.startedAt);function ld(e,t,n){let r=W(`div`,`divide-y divide-neutral-100`);for(let i of t){let t=W(`button`,`grid w-full cursor-pointer grid-cols-[7.5rem_1fr_7.5rem_6.25rem] gap-3 px-4 py-2.5 text-left text-[12.5px] hover:bg-neutral-50`);t.append(W(`span`,`font-medium`,i.state),W(`span`,`truncate text-neutral-500`,sd(i.queuedAt)),W(`span`,`text-neutral-500`,i.triggerSource),W(`span`,`text-right text-neutral-500`,cd(i))),t.onclick=()=>void ud(e,i.id,r,n),r.append(t)}t.length||r.append(W(`p`,`p-4 text-[13px] text-neutral-400`,`No runs yet.`)),e.replaceChildren(r)}async function ud(e,t,n,r){let[i,a]=await Promise.all([fetch(`/api/task-runs/${t}`),fetch(`/api/task-runs/${t}/messages`)]);if(!i.ok)return;let o=await i.json(),s=a.ok?await a.json():[],c=G(`Back to runs`);c.onclick=()=>e.replaceChildren(n);let l=W(`div`,`flex items-center gap-2 border-b border-neutral-200 px-4 py-2`);if(l.append(c,W(`span`,`font-mono text-[12px] text-neutral-400`,o.id)),o.targetSessionId){let e=G(`Open session`);e.classList.add(`ml-auto`),e.onclick=()=>r.openSession(o.targetSessionId),l.append(e)}if(o.state===`queued`||o.state===`running`){let e=G(`Steer`);e.onclick=()=>void dd(d(`Steer subagent`,`/api/task-runs/${o.id}/steer`,{mode:`steer`,sourceSessionId:r.currentSessionId()},`Run control failed`),r);let t=G(`Stop`);t.onclick=()=>void r.mutate(`/api/task-runs/${o.id}/cancel`),l.append(e,t)}else if(o.targetSessionId){let e=G(`Continue`);e.onclick=()=>void dd(d(`Continue subagent`,`/api/task-runs/${o.id}/resume`,{sourceSessionId:r.currentSessionId()},`Run control failed`),r),l.append(e)}let u=W(`div`,`min-h-0 flex-1 overflow-auto`),f=W(`pre`,`whitespace-pre-wrap break-words p-4 font-mono text-[12px]`,JSON.stringify(o,null,2));if(u.append(f),s.length){let e=W(`div`,`border-t border-neutral-200`);e.append(W(`div`,`px-4 py-2 text-[11px] font-semibold uppercase text-neutral-400`,`Messages`));for(let t of s){let n=W(`div`,`grid grid-cols-[6.25rem_6.25rem_1fr] gap-3 border-t border-neutral-100 px-4 py-2 text-[12px]`);n.append(W(`span`,`font-medium`,t.kind),W(`span`,`text-neutral-500`,t.state),W(`span`,`whitespace-pre-wrap`,t.content)),e.append(n)}u.append(e)}e.replaceChildren(l,u)}async function dd(e,t){let n=await e;n.sent&&(n.error?t.onError(n.error):await t.reload())}var fd=e=>e.trigger.type===`manual`?`Manual`:e.trigger.type===`cron`?`${e.trigger.expression} (${e.trigger.timezone})`:`Every ${e.trigger.intervalSeconds}s · ${e.trigger.mode}`,pd=e=>e.action.type===`agent`?`Agent · ${e.action.session.mode}`:e.action.type===`bash`?`Bash`:`Task`;function md(e,t,n,r,i,a){let o=[],s=[],c=null,u=`active`;async function d(){let e=await fetch(`/api/tasks?state=${u===`archived`?`archived`:`active`}${u===`subagent`?`&kind=subagent`:``}`);if(!e.ok)return f(`Failed to load tasks: ${e.status}`);o=await e.json(),s=u===`archived`||u===`subagent`?await p():o,u!==`active`&&u!==`archived`&&u!==`subagent`&&(o=o.filter(e=>e.trigger.type===u)),c?await x(c):y()}function f(t){e.replaceChildren(W(`p`,`p-4 text-[13px] text-red-600`,t))}async function p(){let e=await fetch(`/api/tasks?state=active`);return e.ok?await e.json():s}let m={sessions:t,tasks:()=>s,onSaved:e=>{c=e,d()}},h={openSession:r,currentSessionId:i,mutate:w,onError:f,reload:d};function g(e,t){let n=W(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 px-4`);if(n.append(typeof e==`string`?W(`span`,`truncate font-medium max-md:hidden`,e):e),t.length){let e=W(`div`,`ml-auto flex items-center gap-2`);e.append(...t),n.append(e)}return n}function _(){return W(`div`,`tabstrip`,Xn(`Sessions`,!1,()=>a(`sessions`)),Xn(`Dependencies`,!1,()=>a(`dependencies`)),Xn(`Tasks`,!0,v))}function v(){c=null,y()}function y(){let t=G(`New task`,!0);t.onclick=()=>void n().then(()=>ad(m));let r=_(),i=W(`div`,`ml-auto flex flex-none items-center gap-1 pl-1 max-md:ml-0 max-md:w-full max-md:overflow-x-auto max-md:pl-0`);for(let[e,t]of[[`All`,`active`],[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watching`,`watch`],[`Subagents`,`subagent`],[`Archived`,`archived`]])i.append(Xn(e,u===t,()=>{u=t,c=null,d()}));r.append(i);let a=document.createElement(`table`);a.className=`w-full min-w-[52rem] table-fixed text-left text-[12.5px]`,a.innerHTML=`<thead class="sticky top-0 bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
89
+ <th class="w-[24%] px-4 py-2 font-semibold">Name</th><th class="w-[10%] px-2 py-2 font-semibold">Action</th>
90
+ <th class="w-[23%] px-2 py-2 font-semibold">Trigger</th><th class="w-[17%] px-2 py-2 font-semibold">Next</th>
91
+ <th class="w-[14%] px-2 py-2 font-semibold">Last result</th><th class="px-2 py-2 font-semibold"></th></tr></thead>`;let s=document.createElement(`tbody`);for(let e of o)s.append(b(e));a.append(s),e.replaceChildren(g(`Tasks`,[t]),r,W(`div`,`min-h-0 flex-1 overflow-auto`,a))}function b(e){let t=document.createElement(`tr`);t.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,t.onclick=()=>{c=e.id,x(e.id)};let n=e.archived?`Archived`:e.enabled?`Enabled`:`Paused`;t.append(W(`td`,`truncate py-2.5 pl-4 pr-2`,W(`div`,`truncate font-medium`,e.name),W(`div`,`text-[11px] text-neutral-400`,n)));for(let n of[pd(e),fd(e),sd(e.nextRunAt),e.lastRun?`${e.lastRun.state} · ${cd(e.lastRun)}`:`-`])t.append(W(`td`,`truncate px-2 py-2.5`,n));let r=G(`Run`);return r.disabled=e.archived,r.onclick=t=>{t.stopPropagation(),C(e.id)},t.append(W(`td`,`px-2 py-1 text-right`,r)),t}async function x(t){let[r,i]=await Promise.all([fetch(`/api/tasks/${t}`),fetch(`/api/tasks/${t}/runs`)]);if(!r.ok||!i.ok)return f(`Failed to load task`);let a=await r.json(),o=await i.json(),s=G(`Tasks`);s.className=`cursor-pointer text-neutral-500 hover:underline`,s.onclick=v;let c=W(`span`,`flex min-w-0 items-center gap-1.5`,s,W(`span`,`text-neutral-400`,`›`),W(`span`,`truncate font-medium`,a.name)),l=G(`Run now`,!0);l.disabled=a.archived,l.onclick=()=>void C(a.id);let u=G(a.enabled?`Pause`:`Resume`);u.disabled=a.archived||a.trigger.type===`manual`,u.onclick=()=>void w(`/api/tasks/${a.id}/${a.enabled?`pause`:`resume`}`);let d=G(`Edit`);d.disabled=a.archived,d.onclick=()=>void n().then(()=>ad(m,a));let p=G(`Archive`);p.disabled=a.archived,p.onclick=()=>void w(`/api/tasks/${a.id}/archive`);let y=W(`div`,`flex flex-none gap-1 border-b border-neutral-200 px-4 py-2`),b=G(`Definition`),x=G(`Runs (${o.length})`),T=W(`div`,`min-h-0 flex-1 overflow-auto`),E=()=>{b.classList.add(`bg-neutral-200`),x.classList.remove(`bg-neutral-200`),S(T,a)};b.onclick=E,x.onclick=()=>{x.classList.add(`bg-neutral-200`),b.classList.remove(`bg-neutral-200`),ld(T,o,h)},y.append(b,x),e.replaceChildren(g(c,[l,u,d,p]),_(),y,T),o.length?x.click():E()}function S(e,t){let n=W(`div`,`grid max-w-4xl grid-cols-[9.375rem_minmax(0,1fr)] gap-x-5 gap-y-3 p-4 text-[13px]`),i=[[`Status`,t.archived?`Archived`:t.enabled?`Enabled`:`Paused`],[`Trigger`,fd(t)],[`Action`,pd(t)],[`Timeout`,`${t.timeoutSeconds}s`],[`Next run`,sd(t.nextRunAt)],[`Revision`,String(t.revision)],[`Created by`,t.createdBySessionId??t.creator],[`Callback`,t.callback.type===`session`?t.callback.sessionId:t.callback.type],[`Description`,t.description||`-`]];t.action.type===`agent`&&(i.push([`Session policy`,t.action.session.mode]),t.action.session.mode===`reuse`&&i.push([`Session`,t.action.session.sessionId]),t.action.session.mode===`fresh`&&i.push([`Directory`,t.action.session.cwd]),t.action.session.mode===`fork`&&i.push([`Directory`,t.action.session.cwd??`Caller project`]),t.action.launch?.model&&i.push([`Model`,`${t.action.launch.model.provider}/${t.action.launch.model.id}`]),t.action.launch?.thinking&&i.push([`Thinking`,t.action.launch.thinking]),t.action.launch?.capabilities&&i.push([`Capabilities`,t.action.launch.capabilities]),i.push([`Prompt`,t.action.prompt])),t.action.type===`bash`&&i.push([`Directory`,t.action.cwd],[`Script`,t.action.script]),t.action.type===`task`&&i.push([`Target task`,t.action.taskId]),t.trigger.type===`watch`&&i.push([`Probe`,t.trigger.script]);for(let[e,t]of i)n.append(W(`span`,`text-[11px] font-semibold uppercase text-neutral-400`,e),W(`pre`,`whitespace-pre-wrap break-words font-mono text-[12.5px]`,t));if(t.action.type===`agent`&&t.action.session.mode===`reuse`){let{sessionId:e}=t.action.session,i=G(`Open session`);i.onclick=()=>r(e),n.append(W(`span`,``,``),i)}e.replaceChildren(n)}async function C(e){let t=await l(`/api/tasks/${e}/run`,{sourceSessionId:i()});if(!t.ok)return f((await t.json()).error??`Failed to run task`);c=e,await x(e)}async function w(e){let t=await fetch(e,{method:`POST`});if(!t.ok)return f((await t.json()).error??`Task update failed`);await d()}let T=Hn(e,e=>{e&&(c=e),d()});return Object.assign(T,{refresh(e){T.visible&&(!c||!e||c===e)&&d()}})}var hd=`modulepreload`,gd=function(e){return`/`+e},_d={},vd=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=gd(t,n),t=s(t),t in _d)return;_d[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:hd,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},yd=`pier.terminalPrefs`,bd={fontFamily:`monospace`,fontSize:14,cursorBlink:!0},xd=()=>{try{let e=JSON.parse(localStorage.getItem(yd)??`null`),t=typeof e?.fontSize==`number`?e.fontSize:bd.fontSize;return{fontFamily:typeof e?.fontFamily==`string`&&e.fontFamily.trim()?e.fontFamily.slice(0,200):bd.fontFamily,fontSize:Math.round(Math.max(10,Math.min(24,t))),cursorBlink:typeof e?.cursorBlink==`boolean`?e.cursorBlink:bd.cursorBlink}}catch{return{...bd}}},Sd=e=>localStorage.setItem(yd,JSON.stringify(e)),Cd=null,wd=()=>(Cd||=vd(()=>import(`./ghostty-web-C4N9kjtH.js`).then(async e=>(await e.init(),e)),[]).catch(e=>{throw Cd=null,e}),Cd),Td=()=>{let e=()=>void wd().catch(e=>{console.warn(`terminal: emulator warm-up failed`,e)});`requestIdleCallback`in window?requestIdleCallback(e,{timeout:1e4}):setTimeout(e,3e3)},Ed={background:`#1a1b26`,foreground:`#a9b1d6`,cursor:`#c0caf5`};function Dd(e){let t=e.renderer,n=document.createElement(`canvas`).getContext(`2d`);if(!n||typeof t?.remeasureFont!=`function`){console.warn(`terminal: could not correct cell metrics — rows will render tight`);return}t.measureFont=()=>{let{fontSize:t,fontFamily:r}=e.options;n.font=`${t}px ${r}`;let i=n.measureText(`M`),a=i.fontBoundingBoxAscent||i.actualBoundingBoxAscent||t*.8,o=i.fontBoundingBoxDescent||i.actualBoundingBoxDescent||t*.25;return{width:Math.ceil(i.width),height:Math.ceil(a+o),baseline:Math.ceil(a)}},t.remeasureFont()}var Od=`w-full rounded border border-neutral-300 px-2 py-1.5 font-mono text-[12px] outline-none focus:border-indigo-400`;function kd(e,t,n,r,i){Td();let a=``,o=null,s=null,c=null,d=!1,f=0,p=!1,m=xd(),h=W(`div`,`ml-auto flex min-w-0 flex-none items-center gap-2`),g=W(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),_=W(`div`,`min-h-0 flex-1 overflow-hidden p-1`);_.style.background=Ed.background,_.setAttribute(`data-owns-keyboard`,``),_.addEventListener(`keydown`,e=>{e.metaKey&&!e.defaultPrevented&&e.stopImmediatePropagation()},!0),_.addEventListener(`scroll`,()=>{_.scrollTop=0,_.scrollLeft=0}),_.addEventListener(`compositionend`,()=>{for(let e=_.childNodes.length-1;e>=0;e--){let t=_.childNodes[e];t&&t.nodeName!==`CANVAS`&&t.nodeName!==`TEXTAREA`&&t.remove()}}),e.append(g,_);let v=e=>{let t=W(`button`,`min-w-0 max-w-72 cursor-pointer truncate rounded-md bg-neutral-100 px-2 py-0.5 text-left font-mono text-[11.5px] text-neutral-600 hover:bg-neutral-200`,e);return t.type=`button`,t};function y(e,t){if(h.replaceChildren(),e&&h.append(W(`span`,`min-w-0 truncate text-[11.5px] text-neutral-400`,e)),t){let e=v(t.label);e.className=e.className.replace(`bg-neutral-100`,`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`),e.onclick=t.run,h.append(e)}}function b(){o&&(o.options.fontFamily=m.fontFamily,o.options.fontSize=m.fontSize,o.options.cursorBlink=m.cursorBlink,requestAnimationFrame(E))}function x(){let e=document.createElement(`input`);e.type=`text`,e.placeholder=`tmux new -As "$(basename $PWD)"`,e.spellcheck=!1,e.autocomplete=`off`,e.autocapitalize=`off`,e.disabled=!0,e.className=`${Od} disabled:bg-neutral-50`;let t=W(`span`,`block text-[11.5px] text-neutral-400`,`loading…`),n=(e,n)=>{t.isConnected?J(t,e,n):e===`failed`&&y(n)},r=``;(async()=>{try{let t=await fetch(`/api/settings`);if(!t.ok)throw Error(await u(t,`Could not load the startup command`));r=(await t.json()).terminalInitCommand??``,e.value=r,e.disabled=!1,n(`idle`,`Runs when a shell starts — Restart applies it here.`)}catch(e){n(`failed`,String(e))}})();let i=async()=>{let t=e.value.trim();if(!(e.disabled||t===r)){n(`saving`,`saving…`);try{let i=await l(`/api/settings`,{terminalInitCommand:t},`PUT`);if(!i.ok)return n(`failed`,await u(i,`Could not save the startup command`));r=(await i.json()).terminalInitCommand,e.value=r,n(`saved`,r?`Saved — the next shell runs it.`:`Cleared.`)}catch(e){n(`failed`,`Could not save the startup command: ${String(e)}`)}}};return e.onblur=()=>void i(),e.onkeydown=e=>{e.key===`Enter`&&i()},W(`div`,`space-y-1.5 border-t border-neutral-200 pt-2.5`,W(`div`,``,W(`span`,`text-[12px] font-semibold text-neutral-700`,`Startup command`),W(`span`,`block text-[11px] text-neutral-400`,`This Pier, every shell — not only this browser.`)),e,t)}function S(e){let t=document.createElement(`input`);t.type=`text`,t.value=m.fontFamily,t.setAttribute(`list`,`terminal-font-presets`),t.className=Od;let n=document.createElement(`datalist`);n.id=`terminal-font-presets`;for(let e of[`monospace`,`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,`JetBrains Mono, monospace`,`Cascadia Mono, monospace`,`Fira Code, monospace`]){let t=document.createElement(`option`);t.value=e,n.append(t)}let r=document.createElement(`input`);r.type=`number`,r.min=`10`,r.max=`24`,r.step=`1`,r.value=String(m.fontSize),r.className=`w-20 rounded border border-neutral-300 px-2 py-1.5 text-[12px] outline-none focus:border-indigo-400`;let i=document.createElement(`input`);i.type=`checkbox`,i.checked=m.cursorBlink,i.className=`h-4 w-4 accent-indigo-600`;let a=()=>{let e=t.value.trim(),n=Number(r.value);!e||!Number.isFinite(n)||(m={fontFamily:e.slice(0,200),fontSize:Math.round(Math.max(10,Math.min(24,n))),cursorBlink:i.checked},r.value=String(m.fontSize),Sd(m),b())};t.oninput=a,r.oninput=a,i.onchange=a;let o=W(`button`,`cursor-pointer text-[12px] text-neutral-500 hover:text-indigo-700`,`Reset`);o.type=`button`,o.onclick=()=>{m={...bd},t.value=m.fontFamily,r.value=String(m.fontSize),i.checked=m.cursorBlink,Sd(m),b()},qs(e,W(`div`,`w-72 space-y-3 px-3 py-2.5`,W(`div`,`flex items-center`,W(`span`,`text-[12px] font-semibold text-neutral-700`,`Terminal`),W(`span`,`ml-auto`,o)),W(`label`,`block space-y-1 text-[11.5px] text-neutral-500`,W(`span`,``,`Font family`),t,n),W(`label`,`flex items-center justify-between text-[11.5px] text-neutral-500`,W(`span`,``,`Font size`),r),W(`label`,`flex cursor-pointer items-center justify-between text-[11.5px] text-neutral-500`,W(`span`,``,`Blinking cursor`),i),x()))}function C(){let e=v(a||`Choose a folder…`);e.title=`Switch folder`,e.onclick=()=>Ys(e,[...t().map(e=>({label:e,onSelect:()=>{Q(),e!==a&&r(e)}})),{label:`Browse…`,onSelect:()=>cc(e,a||void 0,r)}]);let n=v(`Fit`);n.title=`Resize the shell to this window`,n.onclick=()=>{E(),o?.focus()};let s=v(`Restart`);s.title=`End this shell and start a new one`,s.onclick=()=>void T();let c=W(`button`,`icon-btn text-[15px]`,`⚙`);c.type=`button`,c.title=`Terminal settings`,c.setAttribute(`aria-label`,`Terminal settings`),c.onclick=()=>S(c);let l=W(`button`,`icon-btn`,`✕`);l.type=`button`,l.title=`Close Terminal`,l.setAttribute(`aria-label`,`Close Terminal`),l.onclick=i,g.replaceChildren(e,h,n,s,c,l)}let w=()=>{o&&c?.readyState===WebSocket.OPEN&&c.send(JSON.stringify({t:`resize`,cols:o.cols,rows:o.rows}))};async function T(){if(c?.readyState!==WebSocket.OPEN){await O();return}window.confirm(`Restart the shell in ${a}? Anything running in it stops.`)&&(p=!0,y(`restarting…`),c.send(JSON.stringify({t:`restart`})))}function E(){!o||_.clientHeight===0||(s?.fit(),w())}window.addEventListener(`focus`,E),document.addEventListener(`visibilitychange`,()=>{document.hidden||E()});function D(){c?.close(),c=null,s=null,o?.dispose(),o=null,_.replaceChildren()}async function O(){let e=++f;D(),d=!1,p=!1,y(`connecting…`);let t;try{t=await wd()}catch(e){y(`could not load the terminal: ${String(e)}`,{label:`Retry`,run:()=>void O()});return}if(e!==f)return;o=new t.Terminal({fontFamily:m.fontFamily,fontSize:m.fontSize,cursorBlink:m.cursorBlink,scrollback:2e3,theme:Ed}),o.open(_),Dd(o),s=new t.FitAddon,o.loadAddon(s),s.observeResize(),s.fit();let n=new WebSocket(`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/api/terminal?cwd=${encodeURIComponent(a)}`);n.binaryType=`arraybuffer`,c=n,n.onopen=()=>{e===f&&(y(``),w(),o?.focus())},n.onmessage=t=>{if(e!==f)return;if(typeof t.data!=`string`){o?.write(new Uint8Array(t.data));return}let r;try{r=JSON.parse(t.data)}catch{d=!0,y(`invalid terminal response`,{label:`Reconnect`,run:()=>void O()}),n.close();return}if(r.t===`exit`){if(p){p=!1,O();return}d=!0,y(`shell exited (${r.code??`?`})`,{label:`Restart`,run:()=>void O()})}else r.t===`error`&&(d=!0,y(r.message??`terminal error`,{label:`Retry`,run:()=>void O()}))},n.onclose=()=>{e!==f||d||y(`disconnected`,{label:`Reconnect`,run:()=>void O()})},o.onData(e=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`in`,d:e}))}),o.onResize(({cols:e,rows:t})=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`resize`,cols:e,rows:t}))})}return Hn(e,e=>{let r=e?.startsWith(`/`)?e:a||n()||t()[0]||``;if(r===a&&o){C(),!d&&c&&c.readyState>WebSocket.OPEN?O():(E(),o.focus());return}if(a=r,C(),!a){y(`No project yet — pick a folder from the chip.`);return}O()},Q)}var Ad,jd=U(`#chat-header`),Md=U(`#chat-title`),Nd=[jd,Y,U(`#composer`)],Pd=!0,Fd=()=>Pd,Id,Ld,Rd=[],zd=new Map,Bd=`activity`,Vd=[`files`,`terminal`],Hd=new Map,Ud={tasks:`Tasks`,activity:`Activity`,boards:`Boards`,settings:`Settings`,files:`Files`,terminal:`Terminal`},Wd=e=>Id.refresh(e),Gd=()=>Ld.refresh();function Kd(){let e=Rd.find(e=>e.view.visible);e?El(Ud[e.name],!1):El(Md.textContent??``,Ad.currentSession()!==void 0)}function qd(e,t){if((e===`tasks`||e===`activity`)&&(Bd=e),Vd.includes(e)){let t=af();t&&(t.kind!==`console`||t.name!==e)&&Hd.set(e,t)}sf({kind:`console`,name:e,arg:t}),Tl(),Pd=!1;for(let e of Nd)e.classList.add(`hidden`);ss();for(let n of Rd)n.name===e?n.view.show(t):n.view.hide();for(let[t,n]of zd)n.classList.toggle(`bg-indigo-50`,t===e||t===`activity`&&e===`tasks`);Kd()}var Jd=e=>qd(`tasks`,e),Yd=e=>qd(`files`,e),Xd=e=>qd(`terminal`,e),Zd=(e,t)=>{Rd.find(t=>t.name===e)?.view.visible?ef(e):qd(e,t)},Qd=e=>Zd(`files`,e),$d=e=>Zd(`terminal`,e);function ef(e){let t=Ad.currentId(),n=Hd.get(e)??(t?{kind:`session`,id:t}:null);Hd.delete(e),n?sf(n):(history.replaceState(null,``,`#/`),tf())}function tf(){if(Rd.some(({view:e})=>e.visible)){for(let{view:e}of Rd)e.hide();for(let e of zd.values())e.classList.remove(`bg-indigo-50`);Pd=!0;for(let e of Nd)e.classList.remove(`hidden`);ss(),Kd(),Ad.maybeAckRead()}}var nf=e=>e.kind===`session`?`#/session/${encodeURIComponent(e.id)}`:`#/${e.name}${e.arg?`/${encodeURIComponent(e.arg)}`:``}`,rf={config:`files`,channels:`channels`,providers:`models`};function af(){let[e=``,t]=location.hash.replace(/^#\/?/,``).split(`/`);if(rf[e])return{kind:`console`,name:`settings`,arg:rf[e]};let n=Rd.find(t=>t.name===e)?.name;return n?{kind:`console`,name:n,arg:t?decodeURIComponent(t):void 0}:e===`session`&&t?{kind:`session`,id:decodeURIComponent(t)}:null}var of=!1;function sf(e,t=!1){if(of)return;let n=nf(e);location.hash!==n&&(t?history.replaceState(null,``,n):location.hash=n)}var cf=e=>sf({kind:`session`,id:e});function lf(){let e=af(),t=Ad.sessions(),n=Ad.currentId(),r=(e?.kind===`session`?e.id:null)??n??(t.find(e=>e.pinned)??t[0])?.id??null;of=!0;try{r&&r!==n&&Ad.select(r),e?.kind===`console`?qd(e.name,e.arg):tf(),r||dl()}finally{of=!1}e?.kind!==`console`&&r&&sf({kind:`session`,id:r},!0)}function uf(e){Ad=e,Id=md(U(`#tasks-view`),()=>Ad.sessions().map(({id:e,cwd:t,title:n})=>({id:e,cwd:t,title:n})),e.loadSessions,e.select,()=>Ad.currentId(),e=>qd(`activity`,e)),Ld=au(U(`#activity-view`),e.select,Jd),Rd=[{name:`tasks`,view:Id},{name:`activity`,view:Ld},{name:`boards`,view:ou(U(`#boards-view`),e.select)},{name:`files`,view:Du(U(`#files-view`),()=>[...Sc(Ad.sessions()).keys()],()=>Ad.currentSession(),e=>qd(`files`,e),()=>ef(`files`))},{name:`terminal`,view:kd(U(`#terminal-view`),()=>[...Sc(Ad.sessions()).keys()],()=>Ad.currentSession()?.cwd,e=>qd(`terminal`,e),()=>ef(`terminal`))},{name:`settings`,view:rd(U(`#settings-view`),()=>[...Sc(Ad.sessions()).keys()],e=>qd(`settings`,e))}];let t=U(`#open-terminal`);t.onclick=()=>$d(),Io(t,`meta+;`,`Terminal`,()=>$d());for(let e of[`activity`,`boards`,`settings`]){let t=U(`#open-${e}`);zd.set(e,t),t.onclick=()=>qd(e===`activity`?Bd:e)}let n=U(`#console-section`);n.open=localStorage.getItem(`pier.consoleCollapsed`)!==`1`,n.ontoggle=()=>localStorage.setItem(`pier.consoleCollapsed`,n.open?`0`:`1`),window.onhashchange=lf}var df=[],ff=0,pf=null,mf=`idle`,hf=null,gf=0,_f=!1;async function vf(e){let t=await l(`/api/sessions`,{cwd:e});if(!t.ok){X(`error`,`session create failed: ${t.status}`);return}let{id:n}=await t.json();await xf(),await Af(n),ns()}function yf(e,t){let n=e.map(e=>({...e,title:zn(e.title)}));if(t)df=n;else{let e=new Map(n.map(e=>[e.id,e]));df=df.map(t=>e.get(t.id)??(t.pinned?{...t,pinned:!1}:t));let t=new Set(df.map(e=>e.id));df.push(...n.filter(e=>!t.has(e.id)))}df.sort((e,t)=>t.createdAt-e.createdAt),Rc(),Cf()}function bf(e){let t,n=!1;return()=>(n=!0,t??=(async()=>{for(;n;)n=!1,await e()})().finally(()=>{t=void 0}))}var xf=bf(async()=>{yf(await(await fetch(`/api/projects`)).json(),!1)}),Sf=bf(async()=>{yf(await(await fetch(`/api/sessions`)).json(),!0)});function Cf(){if(document.hidden||!document.hasFocus()||!Fd())return;let e=df.find(e=>e.id===pf);e?.unread&&(e.unread=!1,Rc(),fetch(`/api/sessions/${e.id}/read`,{method:`POST`}))}function wf(){return df.find(e=>e.id===pf)}function Tf(e,t){let n=df.find(t=>t.id===e);!n||n.title||!t.trim()||(n.title=t.trim().slice(0,80),Rc(),dl())}function Ef(e){mf=e;let t=df.find(e=>e.id===pf);t&&(t.state=e),Rc(),dl(),os(),e===`idle`&&xf()}function Df(e){if(!(e.sessionId!==pf||e.seq<=gf))switch(gf=e.seq,e.type){case`turn-start`:_f=!0;break;case`system-input`:uo(),Ja(e.text,e.origin);break;case`task-status`:oa(e.run);break;case`user-message`:if(Tf(e.sessionId,e.text),rs(e.text))break;uo(),X(`user`,e.text),Ba();break;case`text-delta`:lo(e.text);break;case`thinking-delta`:Da(e.ts,e.text);break;case`tool-start`:uo(),Ta(e.ts,e.toolCallId,e.toolName,e.args);break;case`tool-end`:Ea(e.toolCallId,e.isError,e.output);break;case`turn-end`:_f=!1,fo(e.text,e.meta),e.meta&&ul(e.meta.tokens);break;case`queue-state`:cs(e.steering,e.followUp);break;case`error`:Ca(),X(`error`,e.message);break;case`state`:e.state===`idle`&&_f&&(_f=!1,po()),e.state===`idle`&&cs([],[]),Ef(e.state)}}function Of(){let e=new EventSource(`/api/events`);e.onopen=()=>void xf(),e.onerror=()=>Oo(e,`Workspace`),e.onmessage=e=>{let t=JSON.parse(e.data);if(t.type===`sessions-changed`){xf();return}if(t.type===`tasks-changed`||t.type===`task-run-changed`||t.type===`task-message-changed`||t.type===`task-group-changed`){Wd(t.type===`task-run-changed`?t.taskId:void 0),Gd(),t.type===`task-run-changed`&&xf();return}if(Gd(),t.sessionId===pf)return;let n=df.find(e=>e.id===t.sessionId);n&&(n.state=t.state,Rc())}}function kf(e,t){hf?.close();let n=new EventSource(`/api/sessions/${e}/events?after=${t}`);n.onmessage=e=>Df(JSON.parse(e.data)),n.onerror=()=>Oo(n,`Session`),hf=n}async function Af(e){let t=++ff,n=!1;if(!df.some(t=>t.id===e)){if(await Sf(),t!==ff)return;n=!df.some(t=>t.id===e)}tf(),Tl(),cf(e),!(e===pf&&!n)&&(ms(),pf=e,mf=df.find(t=>t.id===e)?.state??`idle`,hs(e),Rc(),dl(),Cf(),await jf(e,n))}async function jf(e,t=!1){if(hf?.close(),mo(),cs([],[]),cl(),_f=!1,as(),gf=0,ho(!0),t){ho(!1),X(`error`,`session not found: ${e}`);return}let n=await fetch(`/api/sessions/${e}/history`),r=n.ok?await n.json():null;if(pf===e){if(!r){ho(!1),X(`error`,`failed to load session: ${n.status}`);return}go(r.turns,r.state,r.backgroundRuns),gf=r.lastSeq,_f=r.state===`streaming`,Ef(r.state),cs(r.queue.steering,r.queue.followUp),ll(r.model,r.context,r.thinkingLevel),kf(e,r.lastSeq)}}wo(),Do(),Ul();var Mf=async e=>{pf===e&&await jf(e)};Na({sessionId:()=>pf,sessionState:()=>mf,select:e=>void Af(e),showTasks:Jd,send:(e,t)=>void vs(e,t),ownTurn:e=>{is(e),Ef(`streaming`)},reload:Mf}),xs({sessionId:()=>pf,sessionState:()=>mf,chatVisible:Fd,setState:Ef,reload:Mf}),Fl({sessionMenu:e=>{let t=wf();t&&bl(e,t)}}),Xc({sessions:()=>df,loadSessions:Sf,currentId:()=>pf,select:e=>void Af(e),sessionMenu:bl,createSession:vf,openFiles:Yd,openTerminal:Xd,openConsole:qd,onPinsChanged:dl}),Qc({currentId:()=>pf,currentSession:wf,syncBar:Kd,openFiles:Yd,toggleFiles:Qd}),uf({sessions:()=>df,loadSessions:Sf,currentId:()=>pf,currentSession:wf,select:e=>void Af(e),maybeAckRead:Cf}),eu(`0.0.9`),Is(),document.addEventListener(`visibilitychange`,Cf),window.addEventListener(`focus`,Cf),Of(),xf().then(lf);export{vd as t};