@timqi/pier 0.0.19 → 0.0.21

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 (85) hide show
  1. package/dist/agent/config-sync.js +123 -0
  2. package/dist/agent/config.js +95 -3
  3. package/dist/agent/events.js +10 -1
  4. package/dist/agent/pi.js +50 -28
  5. package/dist/config-sync-fetch.js +84 -0
  6. package/dist/config-sync-task.js +59 -0
  7. package/dist/config-sync.js +179 -0
  8. package/dist/core/hub.js +10 -3
  9. package/dist/core/reply.js +12 -2
  10. package/dist/core/router.js +162 -37
  11. package/dist/db.js +6 -0
  12. package/dist/main.js +31 -1
  13. package/dist/tasks/agent.js +11 -22
  14. package/dist/tasks/callbacks.js +1 -1
  15. package/dist/tasks/definitions.js +25 -16
  16. package/dist/tasks/execution.js +11 -3
  17. package/dist/tasks/messages.js +57 -14
  18. package/dist/tasks/routes.js +58 -10
  19. package/dist/tasks/runs.js +0 -5
  20. package/dist/tasks/service.js +9 -4
  21. package/dist/tasks/store.js +45 -0
  22. package/dist/tasks/tool.js +8 -4
  23. package/dist/web/config-sync.js +91 -0
  24. package/dist/web/public/assets/activity-Cw0LRVNI.js +5 -0
  25. package/dist/web/public/assets/activity-Cw0LRVNI.js.br +0 -0
  26. package/dist/web/public/assets/activity-Cw0LRVNI.js.gz +0 -0
  27. package/dist/web/public/assets/{boards-DEMQ51m1.js → boards-DMVbV84c.js} +1 -1
  28. package/dist/web/public/assets/boards-DMVbV84c.js.br +0 -0
  29. package/dist/web/public/assets/boards-DMVbV84c.js.gz +0 -0
  30. package/dist/web/public/assets/{code-DjWvqL94.js → code-C86xKk2k.js} +1 -1
  31. package/dist/web/public/assets/{explorer-BTGQ6Syc.js → explorer-DTvsy5Rs.js} +1 -1
  32. package/dist/web/public/assets/explorer-DTvsy5Rs.js.br +0 -0
  33. package/dist/web/public/assets/explorer-DTvsy5Rs.js.gz +0 -0
  34. package/dist/web/public/assets/{ghostty-web-D8CLFi_l.js → ghostty-web-CvSZragH.js} +1 -1
  35. package/dist/web/public/assets/ghostty-web-CvSZragH.js.br +0 -0
  36. package/dist/web/public/assets/ghostty-web-CvSZragH.js.gz +0 -0
  37. package/dist/web/public/assets/index-DHxoYoeq.js +79 -0
  38. package/dist/web/public/assets/index-DHxoYoeq.js.br +0 -0
  39. package/dist/web/public/assets/index-DHxoYoeq.js.gz +0 -0
  40. package/dist/web/public/assets/{index-yNocr797.css → index-DuZ2vERd.css} +1 -1
  41. package/dist/web/public/assets/index-DuZ2vERd.css.br +0 -0
  42. package/dist/web/public/assets/index-DuZ2vERd.css.gz +0 -0
  43. package/dist/web/public/assets/runs-jY40JBP-.js +1 -0
  44. package/dist/web/public/assets/runs-jY40JBP-.js.br +0 -0
  45. package/dist/web/public/assets/runs-jY40JBP-.js.gz +0 -0
  46. package/dist/web/public/assets/settings-Dux7PIKF.js +6 -0
  47. package/dist/web/public/assets/settings-Dux7PIKF.js.br +0 -0
  48. package/dist/web/public/assets/settings-Dux7PIKF.js.gz +0 -0
  49. package/dist/web/public/assets/task-runs-DKvtBVxS.js +3 -0
  50. package/dist/web/public/assets/task-runs-DKvtBVxS.js.br +0 -0
  51. package/dist/web/public/assets/task-runs-DKvtBVxS.js.gz +0 -0
  52. package/dist/web/public/assets/tasks-CqfrOVIt.js +4 -0
  53. package/dist/web/public/assets/tasks-CqfrOVIt.js.br +0 -0
  54. package/dist/web/public/assets/tasks-CqfrOVIt.js.gz +0 -0
  55. package/dist/web/public/assets/{terminal-zLyOvGto.js → terminal-DL_0yEy7.js} +2 -2
  56. package/dist/web/public/assets/terminal-DL_0yEy7.js.br +0 -0
  57. package/dist/web/public/assets/terminal-DL_0yEy7.js.gz +0 -0
  58. package/dist/web/public/index.html +13 -2
  59. package/dist/web/public/index.html.br +0 -0
  60. package/dist/web/public/index.html.gz +0 -0
  61. package/dist/web/server.js +65 -60
  62. package/package.json +2 -2
  63. package/skills/pier-tasks/SKILL.md +14 -9
  64. package/dist/web/public/assets/activity-BsoWK6vt.js +0 -5
  65. package/dist/web/public/assets/activity-BsoWK6vt.js.br +0 -0
  66. package/dist/web/public/assets/activity-BsoWK6vt.js.gz +0 -0
  67. package/dist/web/public/assets/boards-DEMQ51m1.js.br +0 -0
  68. package/dist/web/public/assets/boards-DEMQ51m1.js.gz +0 -0
  69. package/dist/web/public/assets/explorer-BTGQ6Syc.js.br +0 -0
  70. package/dist/web/public/assets/explorer-BTGQ6Syc.js.gz +0 -0
  71. package/dist/web/public/assets/ghostty-web-D8CLFi_l.js.br +0 -0
  72. package/dist/web/public/assets/ghostty-web-D8CLFi_l.js.gz +0 -0
  73. package/dist/web/public/assets/index-BFzmvpGX.js +0 -78
  74. package/dist/web/public/assets/index-BFzmvpGX.js.br +0 -0
  75. package/dist/web/public/assets/index-BFzmvpGX.js.gz +0 -0
  76. package/dist/web/public/assets/index-yNocr797.css.br +0 -0
  77. package/dist/web/public/assets/index-yNocr797.css.gz +0 -0
  78. package/dist/web/public/assets/settings-DSTKXN2o.js +0 -6
  79. package/dist/web/public/assets/settings-DSTKXN2o.js.br +0 -0
  80. package/dist/web/public/assets/settings-DSTKXN2o.js.gz +0 -0
  81. package/dist/web/public/assets/tasks-Dy1SCAE_.js +0 -4
  82. package/dist/web/public/assets/tasks-Dy1SCAE_.js.br +0 -0
  83. package/dist/web/public/assets/tasks-Dy1SCAE_.js.gz +0 -0
  84. package/dist/web/public/assets/terminal-zLyOvGto.js.br +0 -0
  85. package/dist/web/public/assets/terminal-zLyOvGto.js.gz +0 -0
@@ -1,78 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/explorer-BTGQ6Syc.js","assets/code-DjWvqL94.js","assets/settings-DSTKXN2o.js"])))=>i.map(i=>d[i]);
2
- (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 e=/[\u201c\u201d"\u2018\u2019'()\uff08\uff09\u300c\u300d\u300e\u300f\u3010\u3011\u300a\u300b\u3008\u3009[\]]/;function t(t){let n=[],r=e=>`\uE010${n.push(e)-1}\uE011`,i=t.replace(/```[\s\S]*?```/g,e=>r(e)).replace(/`[^`\n]+`/g,e=>r(e));return i=i.replace(/\*\*(\S|\S[\s\S]*?\S)\*\*/g,(t,n)=>{let r=``,i=``,a=n;for(;a.length>1&&e.test(a[0]);)r+=a[0],a=a.slice(1);for(;a.length>1&&e.test(a.at(-1));)i=a.at(-1)+i,a=a.slice(0,-1);return r||i?`${r}**${a}**${i}`:t}),i.replace(/\uE010(\d+)\uE011/g,(e,t)=>n[Number(t)]??``)}var n=e=>!e.text.trim()&&e.suggestions.length===0,r=e=>e===`xhigh`?`Extra high`:e[0].toUpperCase()+e.slice(1),i=e=>{if(e<1e3)return String(e);let t=e/1e3;return t>=9.95?`${Math.round(t)}K`:`${t.toFixed(1)}K`},a=/(?:^|\n)[ \t]*-{3,}[ \t]*\r?\n((?:[ \t]*\[[^\]\r\n]+\][ \t]*(?:[||][ \t]*)?)+)\s*$/,o=/\[([^\]\r\n]+)\]/g,s=5,c=/<silent>([\s\S]*?)<\/silent>/gi;function l(e){let t=[...e.matchAll(c)].map(e=>(e[1]??``).trim()).filter(Boolean);return t.length?t.join(` · `):void 0}function u(e,n){let r=t(e.replace(c,``).trim()),i=l(e),u=a.exec(r);if(!u?.[1])return{text:r,suggestions:[],meta:n,silence:i};let d=[...u[1].matchAll(o)].map(e=>(e[1]??``).trim()).filter(Boolean).slice(0,s);return d.length?{text:r.slice(0,u.index).trimEnd(),suggestions:d,meta:n,silence:i}:{text:r,suggestions:[],meta:n,silence:i}}var d=e=>t(e.replace(c,``).trim()),ee=/^(?:\s|[-*+>]|\d+[.)])/;function f(e,t=0){let n=e.lastIndexOf(`
3
- `)+1,r=``,i=!1,a=t,o=-1,s=``;for(let c=t;c<n;){let t=e.indexOf(`
4
- `,c),n=e.slice(c,t);c=t+1;let l=/^\s*(`{3,}|~{3,})(.*)$/.exec(n);if(!r&&!i&&!n.trim()){o<0&&s&&(o=c);continue}!r&&!i&&o>=0&&!(ee.test(s)&&ee.test(n))&&(a=o);let u=l?.[1]??``;if(!r&&u&&!i?r=u:r&&u[0]===r[0]&&u.length>=r.length&&!l?.[2]?.trim()&&(r=``),!r&&(!u||i))for(let e of n.matchAll(/<(\/?)silent>/gi))i=!e[1];o=-1,s=n}return a}var p=/^\[(?:([^\n[\]<>]*)<([^\n[\]<>]+)>)? ?((?:\d{4}-\d{2}-\d{2} )?\d{1,2}:\d{2})?\]\n/;function te(e){let t=p.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)}}function ne(e){if(!e)return e;let{text:t}=te(e);return t===e?e:t.replace(/\s+/g,` `).trim()||e}function re(e){let t,n=!1;return()=>(n=!0,t??=(async()=>{for(;n;)n=!1,await e()})().finally(()=>{t=void 0}))}var m=(e,t,n=`POST`)=>fetch(e,{method:n,headers:{"content-type":`application/json`},body:JSON.stringify(t)});async function h(e,t){return(await e.json().catch(()=>({}))).error??`${t} (${e.status})`}async function g(e,t,n){let r;try{r=await fetch(e,n)}catch(e){return{ok:!1,error:`${t}: ${String(e)}`}}if(!r.ok)return{ok:!1,error:await h(r,t)};try{return{ok:!0,value:await r.json()}}catch(e){return{ok:!1,error:`${t}: ${String(e)}`}}}async function ie(e,t,n){let r=await g(e,t,n);if(!r.ok)throw Error(r.error);return r.value}async function ae(e,t,n){try{let r=await fetch(e,{method:t});return r.ok?void 0:await h(r,n)}catch(e){return`${n}: ${String(e)}`}}async function oe(e,t,n,r){let i=window.prompt(e);if(!i?.trim())return{sent:!1};try{let e=await m(t,{message:i,...n});return{sent:!0,...e.ok?{}:{error:await h(e,r)}}}catch(e){return{sent:!0,error:`${r}: ${String(e)}`}}}function _(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 se(e){if(Array.isArray(e))return e}function ce(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 le(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
5
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ue(e,t){return se(e)||ce(e,t)||de(e,t)||le()}function de(e,t){if(e){if(typeof e==`string`)return _(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)?_(e,t):void 0}}var fe=Object.entries,pe=Object.setPrototypeOf,me=Object.isFrozen,he=Object.getPrototypeOf,ge=Object.getOwnPropertyDescriptor,v=Object.freeze,y=Object.seal,_e=Object.create,ve=typeof Reflect<`u`&&Reflect,ye=ve.apply,be=ve.construct;v||=function(e){return e},y||=function(e){return e},ye||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},be||=function(e){return new e(...[...arguments].slice(1))};var xe=C(Array.prototype.forEach),Se=C(Array.prototype.lastIndexOf),Ce=C(Array.prototype.pop),we=C(Array.prototype.push),Te=C(Array.prototype.splice),Ee=Array.isArray,De=C(String.prototype.toLowerCase),Oe=C(String.prototype.toString),ke=C(String.prototype.match),Ae=C(String.prototype.replace),je=C(String.prototype.indexOf),Me=C(String.prototype.trim),Ne=C(Number.prototype.toString),Pe=C(Boolean.prototype.toString),b=typeof BigInt>`u`?null:C(BigInt.prototype.toString),Fe=typeof Symbol>`u`?null:C(Symbol.prototype.toString),x=C(Object.prototype.hasOwnProperty),Ie=C(Object.prototype.toString),S=C(RegExp.prototype.test),Le=Re(TypeError);function C(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return ye(e,t,n)}}function Re(e){return function(){return be(e,[...arguments])}}function w(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:De;if(pe&&pe(e,null),!Ee(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(me(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ze(e){for(let t=0;t<e.length;t++)x(e,t)||(e[t]=null);return e}function T(e){let t=_e(null);for(let r of fe(e)){var n=ue(r,2);let i=n[0],a=n[1];x(e,i)&&(t[i]=Ee(a)?ze(a):a&&typeof a==`object`&&a.constructor===Object?T(a):a)}return t}function Be(e){switch(typeof e){case`string`:return e;case`number`:return Ne(e);case`boolean`:return Pe(e);case`bigint`:return b?b(e):`0`;case`symbol`:return Fe?Fe(e):`Symbol()`;case`undefined`:return Ie(e);case`function`:case`object`:{if(e===null)return Ie(e);let t=e,n=Ve(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:Ie(e)}return Ie(e)}default:return Ie(e)}}function Ve(e,t){for(;e!==null;){let n=ge(e,t);if(n){if(n.get)return C(n.get);if(typeof n.value==`function`)return C(n.value)}e=he(e)}function n(){return null}return n}function He(e){try{return S(e,``),!0}catch{return!1}}var Ue=v(`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(`.`)),We=v(`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(`.`)),Ge=v([`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`]),Ke=v([`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`]),qe=v(`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(`.`)),Je=v([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Ye=v([`#text`]),Xe=v(`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(`.`)),Ze=v(`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(`.`)),Qe=v(`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(`.`)),$e=v([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),et=y(/{{[\w\W]*|^[\w\W]*}}/g),tt=y(/<%[\w\W]*|^[\w\W]*%>/g),nt=y(/\${[\w\W]*/g),rt=y(/^data-[\-\w.\u00B7-\uFFFF]+$/),it=y(/^aria-[\-\w]+$/),at=y(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ot=y(/^(?:\w+script|data):/i),st=y(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ct=y(/^html$/i),lt=y(/^[a-z][.\w]*(-[.\w]+)+$/i),ut=y(/<[/\w!]/g),dt=y(/<[/\w]/g),ft=y(/<\/no(script|embed|frames)/i),pt=y(/\/>/i),E={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},mt=[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`],ht=v(w({},mt)),gt=function(){let e={};return xe(mt,t=>{e[t]=y(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),v(e)}(),_t=function(){return typeof window>`u`?null:window},vt=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}},yt=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},bt=function(e,t,n,r){return x(e,t)&&Ee(e[t])?w(r.base?T(r.base):{},e[t],r.transform):n},xt=function(e,t,n){let r=x(e,t)?e[t]:void 0;return r&&typeof r==`object`?T(r):n()};function St(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_t(),t=e=>St(e);if(t.version=`3.4.14`,t.removed=[],!e||!e.document||e.document.nodeType!==E.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,ee=Ve(d,`cloneNode`),f=Ve(d,`remove`),p=Ve(d,`nextSibling`),te=Ve(d,`childNodes`),ne=Ve(d,`parentNode`),re=Ve(d,`shadowRoot`),m=Ve(d,`attributes`),h=o&&o.prototype?Ve(o.prototype,`nodeType`):null,g=o&&o.prototype?Ve(o.prototype,`nodeName`):null,ie=o&&o.prototype?Ve(o.prototype,`ownerDocument`):null,ae=function(e){return h?h(e):e.nodeType},oe=function(e){return g?g(e):e.nodeName};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let _,se=``,ce,le=!1,ue=0,de=function(){if(ue>0)throw Le(`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.`)},pe=function(e){de(),ue++;try{return _.createHTML(e)}finally{ue--}},me=function(e){de(),ue++;try{return _.createScriptURL(e)}finally{ue--}},he=function(){return le||=(ce=vt(u,i),!0),ce},ge=n,ve=ge.implementation,ye=ge.createNodeIterator,be=ge.createDocumentFragment,Ne=ge.getElementsByTagName,Pe=r.importNode,b=yt();t.isSupported=typeof fe==`function`&&typeof ne==`function`&&ve&&ve.createHTMLDocument!==void 0;let Fe=et,Ie=tt,C=nt,Re=rt,ze=it,mt=ot,Ct=st,wt=lt,Tt=at,D=null,Et=w({},[...Ue,...We,...Ge,...qe,...Ye]),O=null,k=w({},[...Xe,...Ze,...Qe,...$e]),Dt=Object.seal(_e(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}})),A=null,Ot=null,kt=Object.seal(_e(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),At=!0,jt=!0,Mt=!1,Nt=!0,Pt=!1,Ft=!0,It=!1,Lt=!1,Rt=null,zt=null,Bt=!1,Vt=!1,Ht=!1,Ut=!1,Wt=!0,Gt=!1,Kt=`user-content-`,qt=!0,Jt=!1,Yt={},Xt=null,Zt=w({},`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(`.`)),Qt=null,$t=w({},[`audio`,`video`,`img`,`source`,`image`,`track`]),en=null,tn=w({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),j=`http://www.w3.org/1998/Math/MathML`,nn=`http://www.w3.org/2000/svg`,M=`http://www.w3.org/1999/xhtml`,rn=M,an=!1,on=null,sn=w({},[j,nn,M],Oe),cn=v([`mi`,`mo`,`mn`,`ms`,`mtext`]),ln=w({},cn),un=v([`annotation-xml`]),dn=w({},un),fn=w({},[`title`,`style`,`font`,`a`,`script`]),pn=null,mn=[`application/xhtml+xml`,`text/html`],N=null,hn=null,gn=n.createElement(`form`),_n=function(e){return e instanceof RegExp||e instanceof Function},vn=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(hn&&hn===e)return;(!e||typeof e!=`object`)&&(e={}),e=T(e),pn=mn.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,N=pn===`application/xhtml+xml`?Oe:De,D=bt(e,`ALLOWED_TAGS`,Et,{transform:N}),O=bt(e,`ALLOWED_ATTR`,k,{transform:N}),on=bt(e,`ALLOWED_NAMESPACES`,sn,{transform:Oe}),en=bt(e,`ADD_URI_SAFE_ATTR`,tn,{transform:N,base:tn}),Qt=bt(e,`ADD_DATA_URI_TAGS`,$t,{transform:N,base:$t}),Xt=bt(e,`FORBID_CONTENTS`,Zt,{transform:N}),A=bt(e,`FORBID_TAGS`,T({}),{transform:N}),Ot=bt(e,`FORBID_ATTR`,T({}),{transform:N}),Yt=x(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?T(e.USE_PROFILES):e.USE_PROFILES:!1,At=e.ALLOW_ARIA_ATTR!==!1,jt=e.ALLOW_DATA_ATTR!==!1,Mt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Nt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Pt=e.SAFE_FOR_TEMPLATES||!1,Ft=e.SAFE_FOR_XML!==!1,It=e.WHOLE_DOCUMENT||!1,Vt=e.RETURN_DOM||!1,Ht=e.RETURN_DOM_FRAGMENT||!1,Ut=e.RETURN_TRUSTED_TYPE||!1,Bt=e.FORCE_BODY||!1,Wt=e.SANITIZE_DOM!==!1,Gt=e.SANITIZE_NAMED_PROPS||!1,qt=e.KEEP_CONTENT!==!1,Jt=e.IN_PLACE||!1,Tt=He(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:at,rn=typeof e.NAMESPACE==`string`?e.NAMESPACE:M,ln=xt(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>w({},cn)),dn=xt(e,`HTML_INTEGRATION_POINTS`,()=>w({},un));let t=xt(e,`CUSTOM_ELEMENT_HANDLING`,()=>_e(null));if(Dt=_e(null),x(t,`tagNameCheck`)&&_n(t.tagNameCheck)&&(Dt.tagNameCheck=t.tagNameCheck),x(t,`attributeNameCheck`)&&_n(t.attributeNameCheck)&&(Dt.attributeNameCheck=t.attributeNameCheck),x(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(Dt.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),y(Dt),Pt&&(jt=!1),Ht&&(Vt=!0),Yt&&(D=w({},Ye),O=_e(null),Yt.html===!0&&(w(D,Ue),w(O,Xe)),Yt.svg===!0&&(w(D,We),w(O,Ze),w(O,$e)),Yt.svgFilters===!0&&(w(D,Ge),w(O,Ze),w(O,$e)),Yt.mathMl===!0&&(w(D,qe),w(O,Qe),w(O,$e))),kt.tagCheck=null,kt.attributeCheck=null,x(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?kt.tagCheck=e.ADD_TAGS:Ee(e.ADD_TAGS)&&(D===Et&&(D=T(D)),w(D,e.ADD_TAGS,N))),x(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?kt.attributeCheck=e.ADD_ATTR:Ee(e.ADD_ATTR)&&(O===k&&(O=T(O)),w(O,e.ADD_ATTR,N))),x(e,`ADD_FORBID_CONTENTS`)&&Ee(e.ADD_FORBID_CONTENTS)&&(Xt===Zt&&(Xt=T(Xt)),w(Xt,e.ADD_FORBID_CONTENTS,N)),qt&&(D[`#text`]=!0),It&&w(D,[`html`,`head`,`body`]),D.table&&(w(D,[`tbody`]),delete A.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Le(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Le(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=_;_=e.TRUSTED_TYPES_POLICY;try{se=pe(``)}catch(e){throw _=t,e}}else e.TRUSTED_TYPES_POLICY===null?(_=void 0,se=``):(_===void 0&&(_=he()),_&&typeof se==`string`&&(se=pe(``)));v&&v(e),hn=e},yn=w({},[...We,...Ge,...Ke]),bn=w({},[...qe,...Je]),xn=function(e,t,n){return t.namespaceURI===M?e===`svg`:t.namespaceURI===j?e===`svg`&&(n===`annotation-xml`||ln[n]):!!yn[e]},Sn=function(e,t,n){return t.namespaceURI===M?e===`math`:t.namespaceURI===nn?e===`math`&&dn[n]:!!bn[e]},Cn=function(e,t,n){return t.namespaceURI===nn&&!dn[n]||t.namespaceURI===j&&!ln[n]?!1:!bn[e]&&(fn[e]||!yn[e])},wn=function(e){let t=ne(e);(!t||!t.tagName)&&(t={namespaceURI:rn,tagName:`template`});let n=De(e.tagName),r=De(t.tagName);return on[e.namespaceURI]?e.namespaceURI===nn?xn(n,t,r):e.namespaceURI===j?Sn(n,t,r):e.namespaceURI===M?Cn(n,t,r):!!(pn===`application/xhtml+xml`&&on[e.namespaceURI]):!1},Tn=function(e){we(t.removed,{element:e});try{ne(e).removeChild(e)}catch{if(f(e),!ne(e))throw Le(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},En=function(e,t,n){try{e.removeAttributeNode(t)}catch{try{e.removeAttribute(n)}catch{}}},Dn=function(e){An(e);let t=te(e);if(t){let e=[];xe(t,t=>{we(e,t)}),xe(e,e=>{try{f(e)}catch{}})}let n=m(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&En(e,r,i)}},On=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}we(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(Vt||Ht)try{Tn(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},kn=function(e){let t=m(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||O[N(i)]||En(e,r,i)}},An=function(e){let t=[e];for(;t.length>0;){let e=t.pop();ae(e)===E.element&&kn(e);let n=te(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},jn=function(e,t){return Ft?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},Mn=function(e){if(!Ft)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=ae(e);if(n===E.processingInstruction||n===E.comment&&S(dt,e.data)){try{f(e)}catch{}continue}if(n===E.element){let t=e,n=N(oe(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&jn(`for`,n)&&t.removeAttribute(`for`)}catch{}}let r=te(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},Nn=function(e){let t=null,r=null;if(Bt)e=`<remove></remove>`+e;else{let t=ke(e,/^[\r\n\t ]+/);r=t&&t[0]}pn===`application/xhtml+xml`&&rn===M&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=_?pe(e):e;if(rn===M)try{t=new l().parseFromString(i,pn)}catch{}if(!t||!t.documentElement){t=ve.createDocument(rn,`template`,null);try{t.documentElement.innerHTML=an?se:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),rn===M?Ne.call(t,It?`html`:`body`)[0]:It?t.documentElement:a},Pn=function(e){let t=ie?ie(e):e.ownerDocument;return ye.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Fn=function(e){return e=Ae(e,Fe,` `),e=Ae(e,Ie,` `),e=Ae(e,C,` `),e},In=function(e){e.normalize();let t=ie?ie(e):e.ownerDocument,n=ye.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=Fn(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&xe(i,e=>{Rn(e.content)&&In(e.content)})},Ln=function(e){let t=g?g(e):null;return typeof t!=`string`||N(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==m(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==h(e)||e.childNodes!==te(e)},Rn=function(e){if(!h||typeof e!=`object`||!e)return!1;try{return h(e)===E.documentFragment}catch{return!1}},P=function(e){if(!h||typeof e!=`object`||!e)return!1;try{return typeof h(e)==`number`}catch{return!1}};function F(e,n,r){e.length!==0&&xe(e,e=>{e.call(t,n,r,hn)})}let zn=function(e,t){return!!(Ft&&e.hasChildNodes()&&!P(e.firstElementChild)&&S(ut,e.textContent)&&S(ut,e.innerHTML)||Ft&&e.namespaceURI===M&&ht[t]&&(P(e.firstElementChild)||typeof e.textContent==`string`&&S(gt[t],e.textContent))||e.nodeType===E.processingInstruction||Ft&&e.nodeType===E.comment&&S(dt,e.data))},Bn=function(e,t){return e instanceof RegExp?S(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},Vn=function(e,t,n){if(!A[t]&&I(t)&&Bn(Dt.tagNameCheck,t))return!1;if(qt&&!Xt[t]){let t=ne(e),r=te(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,p(e))}}}return Tn(e),!0},Hn=function(e,t,n,r){return e.length===0?t:t===n||t===r?T(t):t},Un=function(e,t){return e===t||ne(e)!==null?!1:(Jt&&An(e),!0)},Wn=function(e,n){if(F(b.beforeSanitizeElements,e,null),Un(e,n))return!0;if(Ln(e))return Tn(e),!0;let r=N(oe(e));if(D=Hn(b.uponSanitizeElement,D,Et,Rt),F(b.uponSanitizeElement,e,{tagName:r,allowedTags:D}),Un(e,n))return!0;if(zn(e,r))return Tn(e),!0;if(A[r]||!(kt.tagCheck instanceof Function&&kt.tagCheck(r))&&!D[r]){let t=Vn(e,r,n);return t===!1&&F(b.afterSanitizeElements,e,null),t}if(ae(e)===E.element&&!wn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&S(ft,e.innerHTML))return Tn(e),!0;if(Pt&&e.nodeType===E.text){let n=Fn(e.textContent);e.textContent!==n&&(we(t.removed,{element:e.cloneNode()}),e.textContent=n)}return F(b.afterSanitizeElements,e,null),!1},Gn=function(e,t,r){if(Ot[t]||jn(t,e)||Wt&&(t===`id`||t===`name`)&&(r in n||r in gn))return!1;let i=O[t]||kt.attributeCheck instanceof Function&&kt.attributeCheck(t,e);return jt&&S(Re,t)||At&&S(ze,t)?!0:i?en[t]||S(Tt,Ae(r,Ct,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&je(r,`data:`)===0&&Qt[e]||Mt&&!S(mt,Ae(r,Ct,``))?!0:!r:I(e)&&Bn(Dt.tagNameCheck,e)&&Bn(Dt.attributeNameCheck,t,e)||t===`is`&&Dt.allowCustomizedBuiltInElements&&Bn(Dt.tagNameCheck,r)},Kn=w({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),I=function(e){return!Kn[De(e)]&&S(wt,e)},qn=function(e,t,n,r){if(_&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return pe(r);case`TrustedScriptURL`:return me(r)}return r},Jn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),Ln(e)?Tn(e):Ce(t.removed)}catch{On(n,e)}},L=function(e){F(b.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||Ln(e))return;O=Hn(b.uponSanitizeAttribute,O,k,zt);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:O,forceKeepAttr:void 0},r=t.length,i=N(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=N(o),u=c,d=o===`value`?u:Me(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,F(b.uponSanitizeAttribute,e,n),d=n.attrValue,Gt&&(l===`id`||l===`name`)&&je(d,Kt)!==0&&(On(o,e,a),d=Kt+d),Ft&&S(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){On(o,e,a);continue}if(l===`attributename`&&ke(d,`href`)){On(o,e,a);continue}if(!n.forceKeepAttr){if(!n.keepAttr){On(o,e,a);continue}if(!Nt&&S(pt,d)){On(o,e,a);continue}if(Pt&&(d=Fn(d)),!Gn(i,l,d)){On(o,e,a);continue}d=qn(i,l,s,d),d!==u&&Jn(e,o,s,d)}}F(b.afterSanitizeAttributes,e,null)},Yn=function(e){let t=null,n=Pn(e);for(F(b.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(F(b.uponSanitizeShadowNode,t,null),Wn(t,e),L(t),Rn(t.content)&&Yn(t.content),ae(t)===E.element){let e=re(t);Rn(e)&&(Xn(e),Yn(e))}F(b.afterSanitizeShadowDOM,e,null)},Xn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Yn(e.shadow);continue}let n=e.node,r=ae(n)===E.element,i=te(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=g?g(n):null;if(typeof e==`string`&&N(e)===`template`){let e=n.content;Rn(e)&&t.push({node:e,shadow:null})}}if(r){let e=re(n);Rn(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(an=!e,an&&(e=`<!-->`),typeof e!=`string`&&!P(e)&&(e=Be(e),typeof e!=`string`))throw Le(`dirty is not a string, aborting`);if(!t.isSupported)return e;Lt?(D=Rt,O=zt):vn(n),(b.uponSanitizeElement.length>0||b.uponSanitizeAttribute.length>0)&&(D=T(D)),b.uponSanitizeAttribute.length>0&&(O=T(O)),t.removed=[];let c=Jt&&typeof e!=`string`&&P(e);if(c){Mn(e);let t=oe(e);if(typeof t==`string`){let n=N(t);if(!D[n]||A[n])throw Dn(e),Le(`root node is forbidden and cannot be sanitized in-place`)}if(Ln(e))throw Dn(e),Le(`root node is clobbered and cannot be sanitized in-place`);try{Xn(e)}catch(t){throw Dn(e),t}}else if(P(e))i=Nn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===E.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Xn(a);else{if(!Vt&&!Pt&&!It&&e.indexOf(`<`)===-1)return _&&Ut?pe(e):e;if(i=Nn(e),!i)return Vt?null:Ut?se:``}i&&Bt&&Tn(i.firstChild);let l=c?e:i;try{let e=Pn(l);for(;o=e.nextNode();)Wn(o,l),L(o),Rn(o.content)&&Yn(o.content)}catch(n){throw c&&(Dn(e),xe(t.removed,e=>{e.element&&An(e.element)})),n}if(c)return xe(t.removed,e=>{e.element&&An(e.element)}),Pt&&In(e),e;if(Vt){if(Pt&&In(i),Ht)for(s=be.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(O.shadowroot||O.shadowrootmode)&&(s=Pe.call(r,s,!0)),s}let u=It?i.outerHTML:i.innerHTML;return It&&D[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&S(ct,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
6
- `+u),Pt&&(u=Fn(u)),_&&Ut?pe(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};vn(e),Lt=!0,Rt=D,zt=O},t.clearConfig=function(){hn=null,Lt=!1,Rt=null,zt=null,_=ce,se=``},t.isValidAttribute=function(e,t,n){hn||vn({});let r=N(e),i=N(t);return Gn(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&x(b,e)&&we(b[e],t)},t.removeHook=function(e,t){if(x(b,e)){if(t!==void 0){let n=Se(b[e],t);return n===-1?void 0:Te(b[e],n,1)[0]}return Ce(b[e])}},t.removeHooks=function(e){x(b,e)&&(b[e]=[])},t.removeAllHooks=function(){b=yt()},t}var Ct=St();function wt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Tt=wt();function D(e){Tt=e}var Et={exec:()=>null};function O(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 k(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(A.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Dt=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),A={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:O(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:O(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:O(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:O(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:O(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:O(e=>RegExp(`^ {0,${e}}>`))},Ot=/^(?:[ \t]*(?:\n|$))+/,kt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,At=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Nt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pt=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ft=k(Pt).replace(/bull/g,Nt).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(),It=k(Pt).replace(/bull/g,Nt).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(),Lt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Rt=/^[^\n]+/,zt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Bt=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,zt).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vt=k(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Nt).getRegex(),Ht=`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`,Ut=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Wt=k(`^ {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`,Ut).replace(`tag`,Ht).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Gt=e=>k(Lt).replace(`hr`,jt).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`,Ht).getRegex(),Kt=Gt(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),qt=Gt(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Jt={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,qt).getRegex(),code:kt,def:Bt,fences:At,heading:Mt,hr:jt,html:Wt,lheading:Ft,list:Vt,newline:Ot,paragraph:Kt,table:Et,text:Rt},Yt=k(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,jt).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`,Ht).getRegex(),Xt={...Jt,lheading:It,table:Yt,paragraph:k(Lt).replace(`hr`,jt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Yt).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`,Ht).getRegex()},Zt={...Jt,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Ut).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:Et,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(Lt).replace(`hr`,jt).replace(`heading`,` *#{1,6} *[^
7
- ]`).replace(`lheading`,Ft).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Qt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,en=/^( {2,}|\\)\n(?!\s*$)/,tn=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,j=/[\p{P}\p{S}]/u,nn=/[\s\p{P}\p{S}]/u,M=/[^\s\p{P}\p{S}]/u,rn=k(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,nn).getRegex(),an=/[\p{Pi}\p{Ps}"']/u,on=/(?!~)[\p{P}\p{S}]/u,sn=/(?!~)[\s\p{P}\p{S}]/u,cn=/(?:[^\s\p{P}\p{S}]|~)/u,ln=k(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Dt?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),un=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,dn=k(un,`u`).replace(/punct/g,j).getRegex(),fn=k(un,`u`).replace(/punct/g,on).getRegex(),pn=k(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,an).replace(/punct/g,j).getRegex(),mn=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,N=k(mn,`gu`).replace(/notPunctSpace/g,M).replace(/punctSpace/g,nn).replace(/punct/g,j).getRegex(),hn=k(mn,`gu`).replace(/notPunctSpace/g,cn).replace(/punctSpace/g,sn).replace(/punct/g,on).getRegex(),gn=k(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,M).replace(/punctSpace/g,nn).replace(/punct/g,j).getRegex(),_n=k(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,M).replace(/punctSpace/g,nn).replace(/punct/g,j).getRegex(),vn=k(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,M).replace(/punctSpace/g,nn).replace(/punct/g,j).getRegex(),yn=k(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,j).getRegex(),bn=k(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,M).replace(/punctSpace/g,nn).replace(/punct/g,j).getRegex(),xn=k(/\\(punct)/,`gu`).replace(/punct/g,j).getRegex(),Sn=k(/^<(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(),Cn=k(Ut).replace(`(?:-->|$)`,`-->`).getRegex(),wn=k(`^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`,Cn).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Tn=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,En=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Tn).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Dn=k(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Tn).replace(`ref`,zt).getRegex(),On=k(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,zt).getRegex(),kn=k(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Dn).replace(`nolink`,On).getRegex(),An=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,jn={_backpedal:Et,anyPunctuation:xn,autolink:Sn,blockSkip:ln,br:en,code:$t,del:Et,delLDelim:Et,delRDelim:Et,emStrongLDelim:dn,emStrongRDelimAst:N,emStrongRDelimUnd:_n,escape:Qt,link:En,nolink:On,punctuation:rn,reflink:Dn,reflinkSearch:kn,tag:wn,text:tn,url:Et},Mn={...jn,emStrongLDelim:pn,emStrongRDelimAst:gn,emStrongRDelimUnd:vn,link:k(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Tn).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Tn).getRegex()},Nn={...jn,emStrongRDelimAst:hn,emStrongLDelim:fn,delLDelim:yn,delRDelim:bn,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,An).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:k(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,An).getRegex()},Pn={...Nn,br:k(en).replace(`{2,}`,`*`).getRegex(),text:k(Nn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Fn={normal:Jt,gfm:Xt,pedantic:Zt},In={normal:jn,gfm:Nn,breaks:Pn,pedantic:Mn},Ln={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},Rn=e=>Ln[e];function P(e,t){if(t){if(A.escapeTest.test(e))return e.replace(A.escapeReplace,Rn)}else if(A.escapeTestNoEncode.test(e))return e.replace(A.escapeReplaceNoEncode,Rn);return e}function F(e){try{e=encodeURI(e).replace(A.percentDecode,`%`)}catch{return null}return e}function zn(e,t){let n=e.replace(A.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(A.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(A.slashPipe,`|`);return n}function Bn(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 Vn(e){let t=e.split(`
8
- `),n=t.length-1;for(;n>=0&&A.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
9
- `)}function Hn(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 Un(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 Wn(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 Gn(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
10
- `).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(`
11
- `)}var Kn=class{options;rules;lexer;constructor(e){this.options=e||Tt}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]:Vn(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=Gn(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=Bn(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Bn(t[0],`
12
- `),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:Bn(t[0],`
13
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Bn(t[0],`
14
- `).split(`
15
- `),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(`
16
- `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
17
- $1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
18
- ${s}`:s,r=r?`${r}
19
- ${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(`
20
- `),o=t.raw+`
21
- `+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s,n=`${n}
22
- ${a}`,r=r.substring(0,r.length-t.text.length)+s.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
23
- `+e.join(`
24
- `),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(`
25
- `);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=Un(t[2].split(`
26
- `,1)[0],t[1].length),l=e.split(`
27
- `,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+`
28
- `,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),ee=this.rules.other.blockquoteBeginRegex(d);for(;e;){let f=e.split(`
29
- `,1)[0],p;if(l=f,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),p=l):p=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||ee.test(l)||t.test(l)||n.test(l))break;if(p.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
30
- `+p.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+=`
31
- `+l}u=!l.trim(),r+=f+`
32
- `,e=e.substring(f.length+1),c=p.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=Vn(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:Bn(t[0],`
33
- `),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=zn(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
34
- `):[],a={type:`table`,raw:Bn(t[0],`
35
- `),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(zn(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:Bn(t[0],`
36
- `),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)===`
37
- `?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=Bn(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Hn(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)),Wn(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 Wn(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}}}},I=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Tt,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:A,block:Fn.normal,inline:In.normal};this.options.pedantic?(t.block=Fn.pedantic,t.inline=In.pedantic):this.options.gfm&&(t.block=Fn.gfm,t.inline=this.options.breaks?In.breaks:In.gfm),this.tokenizer.rules=t}static get rules(){return{block:Fn,inline:In}}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(A.carriageReturn,`
38
- `),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(A.tabCharGlobal,` `).replace(A.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+=`
39
- `: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(`
40
- `)?``:`
41
- `)+i.raw,n.text+=`
42
- `+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(`
43
- `)?``:`
44
- `)+i.raw,n.text+=`
45
- `+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(`
46
- `)?``:`
47
- `)+i.raw,r.text+=`
48
- `+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(`
49
- `)?``:`
50
- `)+i.raw,n.text+=`
51
- `+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)}},qn=class{options;parser;constructor(e){this.options=e||Tt}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(A.notSpaceStart)?.[0],i=e.replace(A.endingNewline,``)+`
52
- `;return r?`<pre><code class="language-`+P(r)+`">`+(n?i:P(i,!0))+`</code></pre>
53
- `:`<pre><code>`+(n?i:P(i,!0))+`</code></pre>
54
- `}blockquote({tokens:e}){return`<blockquote>
55
- ${this.parser.parse(e)}</blockquote>
56
- `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
57
- `}hr(e){return`<hr>
58
- `}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+`>
59
- `+r+`</`+i+`>
60
- `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
61
- `}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox"> `}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
62
- `}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>
63
- <thead>
64
- `+t+`</thead>
65
- `+r+`</table>
66
- `}tablerow({text:e}){return`<tr>
67
- ${e}</tr>
68
- `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
69
- `}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>${P(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=F(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+P(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=F(e);if(i===null)return P(n);e=i;let a=`<img src="${e}" alt="${P(n)}"`;return t&&(a+=` title="${P(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:P(e.text)}},Jn=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}},L=class e{options;renderer;textRenderer;constructor(e){this.options=e||Tt,this.options.renderer=this.options.renderer||new qn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Jn}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}},Yn=class{options;block;constructor(e){this.options=e||Tt}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?I.lex:I.lexInline}provideParser(e=this.block){return e?L.parse:L.parseInline}},Xn=new class{defaults=wt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=L;Renderer=qn;TextRenderer=Jn;Lexer=I;Tokenizer=Kn;Hooks=Yn;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 qn(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 Yn;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]=Yn.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Yn.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 I.lex(e,t??this.defaults)}parser(e,t){return L.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?I.lex:I.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?L.parse:L.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?I.lex:I.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?L.parse:L.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+=`
70
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+P(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function R(e,t){return Xn.parse(e,t)}R.options=R.setOptions=function(e){return Xn.setOptions(e),R.defaults=Xn.defaults,D(R.defaults),R},R.getDefaults=wt,R.defaults=Tt;function Zn(...e){return Xn.use(...e),R.defaults=Xn.defaults,D(R.defaults),R}R.use=Zn,R.walkTokens=function(e,t){return Xn.walkTokens(e,t)},R.parseInline=Xn.parseInline,R.Parser=L,R.parser=L.parse,R.Renderer=qn,R.TextRenderer=Jn,R.Lexer=I,R.lexer=I.lex,R.Tokenizer=Kn,R.Hooks=Yn,R.parse=R,R.options,R.setOptions,R.walkTokens,R.parseInline,L.parse,I.lex;var z=e=>{let t=document.querySelector(e);if(!t)throw Error(`missing element: ${e}`);return t};function Qn(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`}var $n=e=>{let t=Qn(e);return t===`now`?`just now`:`${t} ago`};function B(e,t,...n){let r=document.createElement(e);return t&&(r.className=t),r.append(...n),r}var er=e=>e.split(`/`).filter(Boolean).pop()??e,tr=e=>`New session in ${er(e)}`;function nr(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())}`}function rr(e){let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function ir(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 ar(e){let t=B(`span`,`help`);return t.innerHTML=Ct.sanitize(R.parseInline(e,{async:!1})),or(t),t}function or(e){for(let t of e.querySelectorAll(`a`))(t.getAttribute(`href`)??``).startsWith(`#`)||(t.target=`_blank`,t.rel=`noreferrer`)}async function sr(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 cr(e,t){let n=B(`button`,e,`Copy`);n.title=`Copy to clipboard`;let r;return n.onclick=async e=>{e.stopPropagation(),n.textContent=await sr(t()).then(()=>`Copied`,()=>`Failed`),clearTimeout(r),r=setTimeout(()=>n.textContent=`Copy`,1200)},n}function lr(e,t){let n=document.createElement(`details`);n.className=e;let r=B(`summary`,`flex cursor-pointer select-none items-center gap-1.5`);return r.append(B(`span`,`chev`,`▶`),...t),n.append(r),{el:n,summary:r}}var ur=`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,dr=(e,t=!1)=>fr(e,`${t?`btn btn-primary`:`btn`} text-[12.5px]`),fr=(e,t=``)=>{let n=B(`button`,t,e);return n.type=`button`,n};function pr(e,t,n){let r=dr(e);return t&&r.classList.add(`bg-neutral-200`),r.onclick=n,r}function mr(e,t,n){let r=fr(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 hr(e,t,...n){let r=B(`section`,`rounded-xl border border-neutral-200 bg-white shadow-xs`),i=B(`div`,`rounded-t-xl border-b border-neutral-200/70 bg-neutral-50/70 px-4 py-2.5`);return i.append(B(`h2`,`text-[13px] font-semibold text-neutral-700`,e)),t&&i.append(B(`p`,`mt-0.5 text-[11.5px] leading-snug text-neutral-500`,t)),r.append(i,B(`div`,`flex flex-col gap-4 px-4 py-3.5`,...n)),r}function gr(e,t,n={}){let r=B(`div`,`flex flex-col gap-1.5`),i=B(`div`,`flex items-center gap-1.5`,B(`span`,ur,e));return n.help&&i.append(n.help),r.append(i,t),n.hint&&r.append(B(`span`,`text-[11.5px] leading-snug text-neutral-400`,n.hint)),r}var _r=`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`,vr=(e,t,n,r=!1)=>{let i=document.createElement(`input`);return i.className=r?`${_r} font-mono`:_r,i.value=e,i.placeholder=t,i.oninput=()=>n(i.value),i},yr=(e=``,t=`text`)=>{let n=document.createElement(`input`);return n.type=t,n.className=_r,n.value=e,n},br=(e,t)=>{let n=document.createElement(`select`);return n.className=`${_r} select`,n.append(...e.map(([e,t])=>new Option(e,t))),n.value=t,n},xr=(e=``,t=4)=>{let n=document.createElement(`textarea`);return n.className=`${_r} resize-y font-mono`,n.value=e,n.rows=t,n.spellcheck=!1,n};function Sr(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=B(`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=B(`label`,`flex cursor-pointer gap-2.5 ${e?`items-start`:`items-center`}`);if(s.append(a,o),e){let n=B(`span`,`flex items-center gap-1.5`,B(`span`,`text-[13px] text-neutral-700`,e));i&&n.append(i);let r=B(`span`,`flex min-w-0 flex-col`,n);t&&r.append(B(`span`,`text-[11.5px] leading-snug text-neutral-400`,t)),s.append(r)}return s}var Cr={idle:`text-neutral-400`,saving:`text-neutral-400`,saved:`text-green-700`,failed:`text-red-600`};function wr(e,t,n){e.className=`text-[11.5px] ${Cr[t]}`,e.textContent=n}var Tr=(e,t)=>B(`span`,`flex-none rounded-full px-1.5 py-px text-[10px] font-medium uppercase tracking-wide ring-1 ${t}`,e),Er=e=>B(`p`,`rounded-lg border border-dashed border-neutral-200 px-3 py-4 text-center text-[12.5px] text-neutral-400`,e);function Dr(e,t,n=`left`){let r=B(`span`,`group relative inline-flex`),i=fr(`?`,`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=B(`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=B(`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(B(`span`,`text-[12.5px] font-semibold text-neutral-800`,e));let s=B(`ol`,`flex list-decimal flex-col gap-1.5 pl-4`);for(let e of t){let t=B(`li`,`marker:text-neutral-400`);t.append(typeof e==`string`?ar(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 Or=(e,t)=>B(`span`,`flex flex-col gap-1`,ar(e),t),kr=z(`#image-dialog`),Ar=z(`#image-full`),jr=z(`#image-prev`),Mr=z(`#image-next`),Nr=[],Pr=0;function Fr(e){Nr.length<2||(Pr=(Pr+e+Nr.length)%Nr.length,Ar.src=Nr[Pr])}function Ir(e){let t=e.closest(`[data-gallery]`);Nr=t?[...t.querySelectorAll(`img.thumb`)].map(e=>e.src):[e.src],Pr=Math.max(0,Nr.indexOf(e.src)),Ar.src=e.src;let n=Nr.length<2?`none`:`flex`;jr.style.display=n,Mr.style.display=n,kr.showModal()}kr.onclick=()=>kr.close();var Lr=(e,t)=>{e.onclick=e=>{e.stopPropagation(),Fr(t)}};Lr(jr,-1),Lr(Mr,1),kr.onkeydown=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),Fr(e.key===`ArrowLeft`?-1:1))};function Rr(e){let t=e.querySelector(`:scope > .thumbs`);if(t)return t;let n=B(`div`,`thumbs`);return e.append(n),n}function zr(e){let t=document.createElement(`img`);return t.src=e,t.loading=`lazy`,t.className=`thumb`,t.onclick=()=>Ir(t),t}var Br=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`]),Vr=new Set([`txt`,`md`,`log`,`json`,`csv`,`yaml`,`yml`]),Hr=524288,Ur=z(`#file-dialog`),Wr=z(`#file-name`),Gr=z(`#file-text`),Kr=z(`#file-download`);z(`#file-close`).onclick=()=>Ur.close();var qr=e=>e.split(`.`).pop()?.toLowerCase()??``,Jr=(e,t,n=!1)=>`/api/sessions/${encodeURIComponent(e)}/files?path=${encodeURIComponent(t)}${n?`&download=1`:``}`;function Yr(e,t){return e.replace(/\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)/g,(e,n)=>{let r=n;try{r=decodeURIComponent(n)}catch{}return`](${Jr(t,r)})`})}var Xr=e=>/^\/api\/sessions\/[^/]+\/files\?/.test(e);function Zr(e,t){let n=er(t)||`file`,r=Jr(e,t);return Br.has(qr(n))?ei(r,n):ti(r,n)}function Qr(e){return new URLSearchParams(e.slice(e.indexOf(`?`)+1)).get(`path`)??``}async function $r(e,t){Wr.textContent=t,Kr.href=`${e}&download=1`,Gr.textContent=`loading…`,Ur.showModal();let n;try{let t=await fetch(e);n=t.ok?await t.text():await h(t,`failed to load`)}catch(e){n=`failed to load: ${String(e)}`}Gr.textContent=n.length>Hr?`${n.slice(0,Hr)}\n…`:n}function ei(e,t){let n=zr(e);return n.alt=t,n}function ti(e,t){let n=qr(t),r=B(`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=B(`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=B(`span`,`min-w-0 truncate text-[13px] font-medium text-neutral-800`,t),o=B(`span`,`ml-1 flex flex-none items-center gap-0.5`);if(Vr.has(n)||n===`pdf`){let r=B(`button`,`icon-btn h-6 w-6 text-[13px]`,`◉`);r.title=`Preview`,r.onclick=r=>{r.preventDefault(),n===`pdf`?window.open(e,`_blank`,`noopener`):$r(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 ni(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=B(`div`,`thumbs`);r.append(...t),n.after(r)}}function ri(e){let t=[];for(let n of e.querySelectorAll(`img`)){let e=n.getAttribute(`src`)??``;if(!Xr(e))continue;let r=ei(e,er(Qr(e)));n.replaceWith(r),t.push(r)}for(let n of e.querySelectorAll(`a`)){let e=n.getAttribute(`href`)??``;if(!Xr(e))continue;let r=er(Qr(e))||n.textContent?.trim()||`file`,i=Br.has(qr(r))?ei(e,r):ti(e,r);n.replaceWith(i),t.push(i)}t.length&&ni(t)}var ii=e=>`[${e.split(`/`).pop()??`file`}](file://${encodeURI(e).replace(/\(/g,`%28`).replace(/\)/g,`%29`)})`,ai=/^\[[^\]\n]*\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)$/;function oi(e){let t=e.split(`
71
- `),n=t.length;for(;n>0&&ai.test(t[n-1].trim());)n--;let r=t.slice(n).map(e=>{let t=ai.exec(e.trim())[1];try{return decodeURIComponent(t)}catch{return t}});return{text:t.slice(0,n).join(`
72
- `).trimEnd(),paths:r}}var si=`modulepreload`,ci=function(e){return`/`+e},li={},ui=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=ci(t,n),t=s(t),t in li)return;li[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`:si,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)})},di,fi;function pi(){return fi??=ui(()=>import(`./hljs-tWqyD59G.js`).then(e=>di=e.default,e=>{console.warn(`highlighting unavailable — code stays plain text`,e)}),[]),fi}async function mi(e){let t=await pi();if(t)for(let n of e.querySelectorAll(`pre code[class]`)){let e=/(?:language|lang)-(\S+)/.exec(n.className)?.[1]?.toLowerCase();!e||!t.getLanguage(e)||(n.innerHTML=t.highlight(n.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`};async function gi(e){let t=await pi(),n=e.split(`.`).pop()?.toLowerCase()??``,r=hi[n]??n;return t?.getLanguage(r)?r:null}function _i(e,t){let n=document.createElement(`span`);return di&&t&&e.length<=500?n.innerHTML=di.highlight(e,{language:t}).value:n.textContent=e,n}var vi=null,yi=`max-w-full cursor-pointer break-words rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-left text-[12.5px] text-indigo-700 transition-colors hover:border-indigo-300 hover:bg-indigo-100`;function bi(){vi=null}function xi(e,t,n){if(vi?.remove(),vi=null,!t.length)return;let r=B(`div`,`mt-1.5 flex flex-wrap gap-1.5`);for(let e of t){let t=B(`button`,yi,e);t.type=`button`,t.onclick=()=>{vi===r&&(vi=null),r.remove(),n(e)},r.append(t)}e.append(r),vi=r}var Si=8e3,Ci=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],wi,Ti;function Ei(e,t){wi=e,Ti=t}var Di={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`},Oi=new Map;async function ki(e){let t=await e;t.sent&&t.error&&Ti.append(`error`,t.error)}async function Ai(e,t){let n=await ae(e,`POST`,t);n&&Ti.append(`error`,n)}async function ji(e){let t=wi.sessionId();t&&await ki(oe(`Reply to subagent`,`/api/task-messages/${e}/reply`,{sourceSessionId:t},`reply failed`))}function Mi(e){let t=B(`button`,`flex-none text-[11px] font-semibold normal-case text-cyan-800 hover:underline`,`Reply`);return t.onclick=()=>void ji(e),t}function Ni(e){for(let[e,t]of Oi)t.isConnected||Oi.delete(e);let t=Oi.get(e.runId);t||(t=B(`div`,`mx-5 my-1.5 border px-3 py-2 text-[13px]`),t.dataset.kind=`background-run`,Ti.el.append(t),Oi.set(e.runId,t)),t.className=`mx-5 my-1.5 border px-3 py-2 text-[13px] ${Di[e.state]}`;let n=e.state===`queued`||e.state===`running`,r=`/api/task-runs/${e.runId}`,i=n?B(`span`,`spinner`):B(`span`,`w-3 flex-none text-center`,e.state===`succeeded`?`✓`:e.state===`failed`?`✕`:`·`),a=B(`button`,`min-w-0 truncate text-left font-medium hover:underline`,e.taskName);a.onclick=()=>wi.showTasks(e.taskId);let o=B(`div`,`flex items-center gap-2`,i,B(`span`,`flex-none text-[11px] font-semibold uppercase`,e.state),a),s=B(`div`,`ml-auto flex flex-none items-center gap-2`);if(e.targetSessionId){let t=B(`button`,`font-mono text-[11px] hover:underline`,`Open`);t.title=`Open ${e.targetSessionId}`,t.onclick=()=>wi.select(e.targetSessionId),s.append(t)}if(n){let e=B(`button`,`text-[11px] font-semibold hover:underline`,`Steer`),t={mode:`steer`,sourceSessionId:wi.sessionId()};e.onclick=()=>void ki(oe(`Steer subagent`,`${r}/steer`,t,`could not steer the run`));let n=B(`button`,`text-[11px] font-semibold hover:underline`,`Stop`);n.onclick=()=>void Ai(`${r}/cancel`,`could not stop the run`),s.append(e,n)}else if(e.targetSessionId&&e.sessionMode!==null){let e=B(`button`,`text-[11px] font-semibold hover:underline`,`Continue`),t={sourceSessionId:wi.sessionId()};e.onclick=()=>void ki(oe(`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,B(`div`,`mt-1 break-words text-[11px] opacity-70`,`${e.sessionMode??`task`} · depth ${e.depth} · ${c}s · ${e.runId}`)),Ti.scroll()}var V=null,Pi=null,Fi=null,Ii=!1;function Li(){if(!Pi)return;Pi.text=Pi.text.slice(-4e3),Pi.pre.textContent=Pi.text;let e=Pi.text.split(`
73
- `).filter(Boolean).pop()??`thinking…`,t=Pi.summary.lastElementChild;t.textContent=e.length>90?`…`+e.slice(-90):e}function Ri(){if(Fi){Ii=!0;return}Ii=!1,Li(),Fi=setTimeout(()=>{Fi=null,Ii&&Ri()},80)}function zi(){Fi&&clearTimeout(Fi),Fi=null,Ii&&Li(),Ii=!1}var Bi=new WeakMap,Vi=e=>{let t=Bi.get(e)??[];return Bi.set(e,t),t};function Hi(){V&&!V.toolRows.size&&ea(`done`)}var Ui=null;function Wi(){V=null,Ui=null,Pi=null,zi(),Oi.clear()}function Gi(){let e=Ui;return!e||V?.el===e||(Ui=null,e!==Ti.el.lastElementChild)?null:(e.remove(),e.dataset.adopted=`1`,qi(e,e.dataset.status),e)}var Ki={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 qi(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 ${Ki[t]}`}var Ji={failed:`✕`,interrupted:`⏸`};function Yi(e){return e===`running`?B(`span`,`spinner`):e===`done`?B(`span`,`hidden`):B(`span`,`flex-none text-[12px] font-bold`,Ji[e])}function Xi(e){if(V)return V;let t=Yi(`running`),n=B(`span`,`min-w-0 truncate`,`working…`),{el:r}=lr(``,[t,n]);r.dataset.kind=`activity`,qi(r,`running`);let i=B(`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),Zi(r,i),Ti.el.append(r),Ui=r,Ti.scroll(),V={el:r,statusIcon:t,headline:n,rowsEl:i,toolRows:new Map,thinking:null,steps:0,failedSteps:0,startTs:e,sawError:!1},V}function Zi(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 Qi(e){Ti.bulk()||!e.el.open||!e.rowsEl.dataset.follow||(e.rowsEl.scrollTop=e.rowsEl.scrollHeight)}function $i(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}`,qi(e.el,t);let a=Yi(t);e.statusIcon.replaceWith(a),e.statusIcon=a}function ea(e){if(!V)return;zi();for(let{statusEl:e}of V.toolRows.values())e.textContent===`running…`&&(e.textContent=`interrupted`);let t=V.steps>0&&V.failedSteps===V.steps;$i(V,(V.sawError||t)&&e===`done`?`failed`:e),V=null}function ta(){V&&(V.sawError=!0)}function na(e){let t=e.slice(0,400).replace(/\s+/g,` `);return t.length>100?t.slice(0,100)+`…`:t}function ra(e,t,n,r){let i=Xi(e);i.steps+=1,zi(),i.thinking=null;let a=JSON.stringify(r,null,2)??``,o=B(`span`,`ml-auto flex-none text-neutral-400`,`running…`),s=B(`span`,`min-w-0 truncate text-neutral-500`,na(a)),{el:c}=lr(`rounded-md px-1 py-0.5 font-mono text-[12.5px] hover:bg-black/[0.03] dark:hover:bg-neutral-100`,[B(`span`,`flex-none font-semibold`,n),s,o]),l=B(`pre`,`max-h-40 overflow-y-auto whitespace-pre-wrap break-words rounded bg-black/[0.04] p-1.5 text-[12px] dark:bg-neutral-100`,a),u=B(`pre`,`hidden max-h-56 overflow-y-auto whitespace-pre-wrap break-words rounded bg-black/[0.04] p-1.5 text-[12px] dark:bg-neutral-100`);c.append(B(`div`,`mt-1 flex flex-col gap-1 pl-4`,l,u)),Vi(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),Qi(i),$i(i,`running`,n),Ti.scroll()}function ia(e,t,n){let r=V;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,Si)+`…`:n,i.outputPre.classList.remove(`hidden`)),t&&(r.failedSteps+=1)),$i(r,`running`)}function aa(e,t){let n=Xi(e);if(!n.thinking){zi();let{el:e,summary:t}=lr(`rounded-md px-1 py-0.5 text-[12.5px] italic text-neutral-500 hover:bg-black/[0.03] dark:hover:bg-neutral-100`,[B(`span`,`min-w-0 truncate`,`thinking…`)]),r=B(`div`,`mt-1 max-h-56 overflow-y-auto whitespace-pre-wrap break-words pl-4 not-italic text-neutral-500`,``);e.append(r),n.rowsEl.append(e),n.thinking={pre:r,summary:t,text:``},Pi=n.thinking,Qi(n),$i(n,`running`,`thinking…`)}n.thinking.text+=t,Ri()}var oa=0;function sa(e,t=0,n=!1,r){let i=Date.now()-t,a=Xi(i).el;for(let t of e){if(t.kind===`thinking`){aa(i,t.text??``);continue}let e=t.id??`replay-${++oa}`;ra(i,e,t.toolName??``,t.args),t.done&&ia(e,t.isError??!1,t.output??``)}r!==void 0&&e.some(e=>e.kind===`tool`&&e.args===void 0)&&ca(a,r),!n&&ea(e.some(e=>e.kind===`tool`&&!e.done)?`interrupted`:`done`)}function ca(e,t){let n=()=>{e.open&&(e.removeEventListener(`toggle`,n),la(e,t))};e.addEventListener(`toggle`,n)}async function la(e,t){let n=wi.sessionId(),r=Vi(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=await g(`/api/sessions/${n}/turns/${t}/steps`,`could not load these steps`);if(!o.ok)return a(o.error);let s=o.value.steps.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=na(r),n.output&&(t.outputPre.textContent=n.output,t.outputPre.classList.remove(`hidden`))}}var ua,H=z(`#turns`);function da(e){ua=e,Ei(e,{el:H,append:U,scroll:va,bulk:()=>fa})}var fa=!1,pa=()=>H.scrollHeight-H.scrollTop-H.clientHeight<80,ma=!0;H.addEventListener(`scroll`,()=>{fa||(ma=pa())},{passive:!0});var ha=0;function ga(){!ma||fa||ha||(ha=requestAnimationFrame(()=>{ha=0,ma&&!fa&&(H.scrollTop=H.scrollHeight)}))}new ResizeObserver(ga).observe(H),H.addEventListener(`load`,ga,!0),new MutationObserver(ga).observe(H,{childList:!0,subtree:!0,characterData:!0});function _a(){pa()&&(ma=!0)}function va(e=!1){fa||(e&&(ma=!0),ma&&(H.scrollTop=H.scrollHeight))}var ya=500,ba=0,xa=0,Sa=null;function Ca(){for(;H.childElementCount>ya;){let e=H.firstElementChild;e.remove(),e!==Sa&&(e.dataset.kind===`user`&&ba++,xa++)}xa&&(Sa||(Sa=B(`div`,`px-5 py-2 text-center text-[11.5px] italic text-neutral-400`),Sa.dataset.kind=`trim`),Sa.textContent=`${xa} earlier row${xa===1?``:`s`} not shown — still in the transcript, not on this screen`,H.firstElementChild!==Sa&&H.prepend(Sa))}var wa={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 U(e,t,n=!1,r){Hi();let i=e===`assistant`?Gi():null,a=wa[e],o=e===`user`&&r!==void 0&&Ma(r)?r:void 0,s=B(`div`,`group relative border-l-2 px-5 ${o===void 0&&H.lastElementChild?.dataset.kind===e?`pt-1 pb-2.5`:`mt-1.5 py-2.5`} ${a.row}`);s.dataset.kind=e;let c=e===`user`?oi(t):null,l=c?.text??t,u=e===`user`?te(l):null,d=u?.id||u?.when?u:null,ee=d?.id&&d.id!==`web`?d:null,f=B(`div`,`whitespace-pre-wrap break-words ${a.body}`,d?.text??l);(c?.paths.length||d)&&(f.dataset.raw=t),n&&Va(f,t),i&&(s.classList.add(`flow-root`),s.append(i)),(ee||o!==void 0)&&s.append(Ta(ee,o)),s.append(f);let p=ua.sessionId();if(c?.paths.length&&p){let e=Rr(s);for(let t of c.paths)e.append(Zr(p,t))}if(e===`user`){let e=B(`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=()=>Da(s,f),s.append(e)}return H.append(s),Ca(),va(),f}function Ta(e,t){let n=B(`div`,`mb-1 flex items-baseline gap-2 text-[11.5px] leading-tight`),r=e?.name??e?.id;if(r){let t=B(`span`,`font-semibold text-indigo-700`,r);e?.id&&(t.title=e.id),n.append(t)}return t!==void 0&&n.append(Na(t,`font-mono text-[11px] text-indigo-600`)),n}function Ea(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`;Hi();let r=B(`div`,`group relative mt-1.5 border-l-2 border-l-cyan-500 bg-cyan-50 px-5 py-2.5`);r.dataset.kind=`system`;let i=B(`div`,`mb-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] font-semibold uppercase text-cyan-800`,B(`span`,`flex-none`,n)),a=t.source;if(a&&i.append(B(`span`,`min-w-0 truncate font-medium normal-case text-cyan-700`,a.taskName)),t.sourceSessionId&&t.sourceSessionId!==`console`){let e=B(`button`,`truncate font-mono normal-case text-cyan-700 hover:underline`,t.sourceSessionId.slice(0,12));e.title=`Open source session`,e.onclick=()=>ua.select(t.sourceSessionId),i.append(B(`span`,`text-cyan-400`,`from`),e)}if(a?.model){let e=B(`span`,`flex-none rounded bg-cyan-100 px-1.5 py-px font-mono font-medium normal-case text-cyan-800`,a.model.id);e.title=`${a.model.provider} / ${a.model.id}`,i.append(e)}if(a?.thinking){let e=B(`span`,`flex-none font-mono font-normal normal-case text-cyan-600`,a.thinking);e.title=`Reasoning effort`,i.append(e)}let o=B(`button`,`ml-auto flex-none font-mono normal-case text-cyan-700 hover:underline`,`run ${t.runId.slice(0,8)}`);o.onclick=()=>ua.showTasks(t.taskId),i.append(o),t.kind===`task-message`&&t.messageKind===`decision`&&i.append(Mi(t.messageId));let s=[`max-h-[min(18rem,40dvh)]`,`overflow-hidden`],c=B(`div`,`whitespace-pre-wrap break-words text-[14px] text-neutral-800 ${s.join(` `)}`,e);r.append(i,c),H.append(r);let l=e.length>800||e.split(`
74
- `).length>12;if(c.clientHeight?c.scrollHeight>c.clientHeight+1:l){let e=B(`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=c.classList.toggle(s[0]);c.classList.toggle(s[1],t),e.textContent=t?`Show full message`:`Collapse message`,c.tabIndex=-1,c.focus({preventScroll:!0})},r.append(e)}else c.classList.remove(...s);Ca(),va()}function Da(e,t){if(ua.sessionState()!==`idle`){U(`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();Oa(e,r)}}}async function Oa(e,t){let n=ua.sessionId();if(!n)return;let r=ba+[...H.querySelectorAll(`[data-kind="user"]`)].indexOf(e);for(;e.nextElementSibling;)e.nextElementSibling.remove();e.remove(),ua.ownTurn(t),U(`user`,t,!1,Date.now()),va(!0);let i=await m(`/api/sessions/${n}/turns/${r}/edit`,{text:t});if(!i.ok){let e=await h(i,`edit failed`);await ua.reload(n),U(`error`,e)}}var ka=6e5,Aa=null,ja=(e,t)=>new Date(e).toDateString()===new Date(t).toDateString();function Ma(e){let t=Aa;return Aa=e,t===null||e-t>=ka||!ja(t,e)}function Na(e,t){let n=B(`div`,t);return n.dataset.at=String(e),Pa(n),Ia??=setInterval(La,6e4),n}function Pa(e){let t=Number(e.dataset.at);e.textContent=`${nr(t)} · ${$n(t)}`}var Fa=null,Ia;function La(){let e=H.querySelectorAll(`[data-at]`);if(!e.length){clearInterval(Ia),Ia=void 0;return}for(let t of e)Pa(t)}function Ra(e,t){t&&(Fa?.remove(),Fa=Na(t.completedAt,`mt-1 font-mono text-[11px] text-neutral-400`),(e.parentElement??e).append(Fa))}function za(e){for(let t of e.querySelectorAll(`pre`)){let e=t.querySelector(`code`);if(!e)continue;let n=B(`div`,`group/code relative`);t.replaceWith(n),n.append(t,cr(`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 Ba(e){let t=ua.sessionId(),n=B(`div`,``);return n.innerHTML=Ct.sanitize(R.parse(t?Yr(e,t):e,{async:!1})),or(n),n}function Va(e,t){e.replaceChildren(...Ba(t).childNodes),e.classList.remove(`whitespace-pre-wrap`),e.classList.add(`md`),mi(e),za(e),ri(e)}function Ha(e,t,r,i=!1){let{text:a,suggestions:o}=u(t);return n({text:a,suggestions:o})?Ua(e,l(t)):Va(e,a),i&&xi(e.parentElement??e,o,e=>ua.send(`auto`,e)),Ra(e,r),e}function Ua(e,t){e.classList.remove(`md`,`whitespace-pre-wrap`),e.replaceChildren(B(`span`,`text-[12.5px] italic text-neutral-400`,t?`Stayed silent — ${t}`:`Stayed silent.`))}var Wa=(e,t,n=!1)=>Ha(U(`assistant`,``),e,t,n),Ga=null,Ka=null,qa=!1,Ja=0,Ya=0;function Xa(e){let t=e.dataset.raw??``;for(;e.childNodes.length>Ya;)e.lastChild.remove();let n=f(t,Ja);n>Ja&&(e.append(...Ba(d(t.slice(Ja,n))).childNodes),Ja=n,Ya=e.childNodes.length),e.append(...Ba(u(t.slice(Ja)).text).childNodes),e.classList.remove(`whitespace-pre-wrap`),e.classList.add(`md`)}function Za(){if(Ka){qa=!0;return}qa=!1,Ga&&(Xa(Ga),va()),Ka=setTimeout(()=>{Ka=null,qa&&Za()},80)}function Qa(){Ka&&clearTimeout(Ka),Ka=null,qa=!1}function $a(e){Ga||(Ga=U(`assistant`,``),Ja=0,Ya=0),Ga.dataset.raw=(Ga.dataset.raw??``)+e,Za()}function eo(e=!1,t){if(!Ga)return;let n=Ga;Ga=null,Qa(),Ha(n,n.dataset.raw??``,t,e)}function to(e,t){if(ea(`done`),Ga){e&&(Ga.dataset.raw=e),eo(!0,t);return}e&&Wa(e,t,!0)}function no(){ea(`interrupted`),eo()}function ro(){H.replaceChildren(),ba=0,xa=0,Sa=null,Aa=null,Fa=null,Ga=null,Qa(),Wi(),bi()}function io(e){if(!e){H.querySelector(`[data-kind="loading"]`)?.remove();return}let t=B(`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(B(`div`,`skeleton h-3.5 ${e}`));H.append(t)}function ao(e,t,n){io(!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&&(Ni(e),r.delete(t))}},o=e.reduce((e,t,n)=>t.role===`assistant`?n:e,-1);fa=!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&&(sa(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]),Ea(r.text,r.origin);continue}r.role===`assistant`?Wa(r.text,r.meta,t===`idle`&&n===o):U(r.role,r.text,!1,r.at)}}for(let e of r.values())Ni(e)}finally{fa=!1}va(!0)}var oo=window.fetch.bind(window),so=20,co=6e4,lo=[],uo=new Map,fo=e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:void 0;function po(e,t){let n=t===void 0?e:`${e}: ${String(t)}`,r=Date.now();return r-(uo.get(n)??-6e4)<co||(uo.size>100&&uo.clear(),uo.set(n,r),lo=lo.filter(e=>r-e<6e4),lo.length>=so)?null:(lo.push(r),oo(`/api/client-log`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({message:n,stack:fo(t),view:location.hash||`/`}),keepalive:!0}).catch(()=>{}),U(`error`,n))}function mo(){window.__pierReporting=!0,window.addEventListener(`error`,e=>{po(`script error: ${e.message}`,e.error)}),window.addEventListener(`unhandledrejection`,e=>{po(`unhandled rejection`,e.reason)})}var ho=window.fetch.bind(window),go=()=>{location.assign(`/login?next=${encodeURIComponent(location.pathname+location.hash)}`)};function _o(){window.fetch=async(...e)=>{let t=await ho(...e);return t.status===401&&go(),t}}function vo(e,t){if(e.readyState!==EventSource.CLOSED)return;let n=()=>{let e=po(`${t} stream disconnected`);if(!e)return;let n=dr(`Reload`);n.classList.add(`ml-2`,`align-middle`),n.onclick=()=>location.reload(),e.append(` `,n)};ho(`/api/projects`).then(e=>e.status===401?go():n(),n)}var yo=/Mac|iP(?:hone|ad|od)/.test(navigator.userAgent),bo=yo?`⌘`:`Ctrl+`,xo=yo?`⇧`:`Shift+`,So=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 Co(e){let{key:t,shift:n,meta:r}=So(e);return`${r?`⌘`:bo}${n?xo:``}${t.toUpperCase()}`}var wo=`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 To(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=B(`div`,wo,t,B(`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 Eo(e,t,n,r,i){To(e,n,Co(t)),Ao(t,r,i)}function Do(e,t,n,r){To(e,t,`Esc`),document.addEventListener(`keydown`,e=>{e.key!==`Escape`||e.isComposing||e.defaultPrevented||document.querySelector(`dialog[open]`)||!r()||(e.preventDefault(),n())})}var Oo=`input, textarea, select, [contenteditable]`;function ko(e,t,n,r,i){To(e,n,t[0].toUpperCase()),document.addEventListener(`keydown`,e=>{e.metaKey||e.ctrlKey||e.altKey||e.isComposing||e.defaultPrevented||!e.key||!t.includes(e.key.toLowerCase())||e.target?.closest?.(Oo)||document.querySelector(`dialog[open]`)||!i()||(e.preventDefault(),r())})}function Ao(e,t,n){let{key:r,shift:i,meta:a}=So(e);document.addEventListener(`keydown`,e=>{!e.key||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 W,jo=z(`#composer`),G=z(`#input`),Mo=z(`#send`),No=z(`#send-plane`),Po=z(`#send-queue`),Fo=z(`#stop`),Io=z(`#queue-panel`),Lo=z(`#queue-rows`),Ro=z(`#queue-label`),zo=z(`#image-strip`),Bo=z(`#attach-input`),Vo=!1,Ho=[],Uo=[];function Wo(){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 Go(){G.focus()}function Ko(e){let t=Uo.indexOf(e);return t<0?!1:(Uo.splice(t,1),!0)}function qo(e){Uo.push(e)}function Jo(){Uo=[]}function Yo(){let e=W.sessionState()===`streaming`,t=W.sessionId()!==null,n=W.starting();Mo.disabled=!t,Mo.className=`flex h-7 w-7 flex-none items-center justify-center rounded-lg ${t?e?`cursor-pointer bg-amber-100 text-amber-700 hover:bg-amber-200 active:bg-amber-300`:`cursor-pointer bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-700 dark:text-neutral-50`:`cursor-default bg-neutral-100 text-neutral-400`}`,Mo.title=t?e?`Queue — delivered when the turn ends`:`Send`:n?`Starting the session…`:`No session`,G.placeholder=n?`Starting the session…`:`Message…`,No.classList.toggle(`hidden`,e),Po.classList.toggle(`hidden`,!e),Fo.classList.toggle(`hidden`,!e),Fo.classList.toggle(`flex`,e)}function Xo(){let e=W.chatVisible()&&Vo;Io.classList.toggle(`hidden`,!e),Io.classList.toggle(`flex`,e)}function Zo(e,t){let n=[...e.map(e=>({mode:`steer`,text:e})),...t.map(e=>({mode:`queued`,text:e}))];Vo=n.length>0,Ro.textContent=n.length>1?`Queued · ${n.length}`:`Queued`,Xo(),Lo.replaceChildren(...n.map(e=>{let t=B(`li`,`flex items-start gap-2 text-[13px] leading-[18px]`);return e.mode===`steer`&&t.append(B(`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(B(`span`,`min-w-0 whitespace-pre-wrap break-words text-neutral-700`,e.text)),t}))}var Qo=8;function $o(){zo.classList.toggle(`hidden`,Ho.length===0),zo.classList.toggle(`flex`,Ho.length>0),zo.replaceChildren(...Ho.map((e,t)=>{let n=e.mimeType.startsWith(`image/`)?zr(`data:${e.mimeType};base64,${e.data}`):B(`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=B(`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=()=>{Ho.splice(t,1),$o()},B(`div`,`relative`,n,r)}))}function es(e){if(Ho.length>=Qo){U(`error`,`attachment limit is ${Qo} files per message`);return}if(e.size>33554432){U(`error`,`${e.name||`file`} is too large (32MB max)`);return}let t=new FileReader;t.onload=()=>{let n=t.result;Ho.push({data:n.slice(n.indexOf(`,`)+1),mimeType:e.type||`application/octet-stream`,name:e.name||void 0}),$o()},t.readAsDataURL(e)}async function ts(e){let t=[];for(let n of e){let e=await m(`/api/inbox`,n);if(!e.ok)return null;let{path:r}=await e.json();t.push(ii(r))}return t}var ns=e=>`pier.draft.${e}`;function rs(){let e=W.sessionId();e&&(G.value.trim()?localStorage.setItem(ns(e),G.value):localStorage.removeItem(ns(e)))}function is(e){G.value=localStorage.getItem(ns(e))??``,as(),Ho=[],$o()}function as(){let e=G.style.height;G.style.height=`auto`;let t=`${Math.min(G.scrollHeight,192)}px`;G.style.height=t,t!==e&&va()}var os=!1;async function ss(e,t){let n=(t??G.value).trim(),r=t===void 0?Ho:[],i=W.sessionId();if(!(!n&&r.length===0||!i)){if(t===void 0){if(os)return;os=!0,G.value=``,as(),rs(),Ho=[],$o()}try{let t=[];if(r.length){let e=await ts(r);if(e===null){U(`error`,`attachment upload failed`),G.value=[n,G.value.trim()].filter(Boolean).join(`
75
- `),as(),rs(),Ho=r,$o();return}t=e}let a=[n,...t].filter(Boolean).join(`
76
- `),o=W.sessionState()===`idle`&&e===`auto`;o?W.setState(`streaming`):Yo(),(o||e===`steer`)&&(qo(a),U(`user`,a,!1,Date.now()),va(!0));let s=await m(`/api/sessions/${i}/messages`,{text:a,mode:e});if(!s.ok){let e=await h(s,`send failed`);await W.reload(i),U(`error`,e)}}finally{t===void 0&&(os=!1)}}}async function cs(e){let t=W.sessionId();if(!t)return;Zo([],[]);let n=await m(`/api/sessions/${t}/queue/deliver`,{mode:e});n.ok||U(`error`,`queue ${e} failed: ${n.status}`)}async function ls(){let e=W.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&&(G.value=[G.value.trim(),...n].filter(Boolean).join(`
77
- `),as(),rs(),G.focus()),Zo([],[])}function us(e){W=e,Wo();let t=()=>{let e=W.sessionId();e&&fetch(`/api/sessions/${e}/abort`,{method:`POST`})};Fo.onclick=t,Do(Fo,`Stop the running turn`,t,()=>W.sessionState()===`streaming`&&W.chatVisible()),z(`#queue-steer`).onclick=()=>void cs(`steer`),z(`#queue-restart`).onclick=()=>void cs(`restart`),z(`#queue-recall`).onclick=()=>void ls(),jo.onsubmit=e=>{e.preventDefault(),ss(`auto`)},ko(G,[`/`],`Write a message`,Go,W.chatVisible),G.onfocus=_a,G.oninput=()=>{as(),rs()};let n=!matchMedia(`(pointer: coarse)`).matches;G.onkeydown=e=>{e.isComposing||e.keyCode===229||n&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ss(`auto`))},G.onpaste=e=>{for(let t of e.clipboardData?.items??[]){let e=t.kind===`file`?t.getAsFile():null;e&&es(e)}let t=e.clipboardData?.getData(`text/plain`)??``,n=t.trim();!n||n===t||(e.preventDefault(),G.setRangeText(n,G.selectionStart??0,G.selectionEnd??0,`end`),as(),rs())},H.ondragover=e=>e.preventDefault(),H.ondrop=e=>{e.preventDefault();for(let t of e.dataTransfer?.files??[])es(t)},z(`#attach`).onclick=()=>Bo.click(),Bo.onchange=()=>{for(let e of Bo.files??[])es(e);Bo.value=``},Yo()}var ds=`pier.push`,fs=`/sw.js`,ps=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.maxTouchPoints>1&&/Macintosh/.test(navigator.userAgent),ms=()=>matchMedia(`(display-mode: standalone)`).matches||navigator.standalone===!0;function hs(){return window.isSecureContext?ps()&&!ms()?`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 gs=[[/iPhone/,`iPhone`],[/iPad/,`iPad`],[/Android/,`Android`],[/Macintosh/,`Mac`],[/Windows/,`Windows`]],_s=[[/Edg\//,`Edge`],[/Chrome\//,`Chrome`],[/Firefox\//,`Firefox`],[/Safari\//,`Safari`]];function vs(){let e=navigator.userAgent,t=(t,n)=>t.find(([t])=>t.test(e))?.[1]??n;return`${t(gs,`Linux`)} · ${t(_s,`browser`)}${ms()?` (installed)`:``}`}var ys=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},bs=null;async function xs(){return!(`serviceWorker`in navigator)||!window.isSecureContext?null:(bs??=await navigator.serviceWorker.register(fs,{scope:`/`}).catch(e=>(console.warn(`service worker registration failed`,e),null)),bs)}var Ss=(e,t)=>{let n=e?new Uint8Array(e):null;return n?.length===t.length&&n.every((e,n)=>e===t[n])};async function Cs(e){let{publicKey:t}=await ie(`/api/push`,`Could not read this instance's push key`),n=ys(t),r=await e.pushManager.getSubscription();if(r){if(Ss(r.options.applicationServerKey,n))return r;await r.unsubscribe()}return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n})}async function ws(e){return m(`/api/push/subscribe`,{...e.toJSON(),label:vs()})}async function Ts(){Os();let e=await xs();if(!(!e||localStorage.getItem(ds)!==`on`)&&!(!(`Notification`in window)||Notification.permission!==`granted`))try{await ws(await Cs(e))}catch(e){console.warn(`re-registering this browser for notifications failed`,e)}}var Es=null,Ds=null;function Os(){window.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Es=e,Ds?.()}),window.addEventListener(`appinstalled`,()=>{Es=null,Ds?.()})}function ks(e){let t=navigator;(e>0?t.setAppBadge?.(e):t.clearAppBadge?.())?.catch(()=>{})}function As(){let e=B(`span`,`text-[11.5px]`,``),t=dr(`Send a test notification`),n=B(`div`,`flex items-center gap-3`,t,e),r=B(`div`,`flex flex-col gap-4`),i=()=>localStorage.getItem(ds)===`on`;async function a(){wr(e,`saving`,`asking this browser…`);let t=await Notification.requestPermission();if(t!==`granted`)return localStorage.setItem(ds,`off`),c(),wr(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 xs();if(!n)return wr(e,`failed`,`This browser refused to register a service worker.`);try{let t=await ws(await Cs(n));if(!t.ok)return wr(e,`failed`,await h(t,`Could not register this browser`));localStorage.setItem(ds,`on`),c(),wr(e,`saved`,`This browser will be notified when a turn finishes unseen.`)}catch(t){wr(e,`failed`,`Could not subscribe: ${String(t)}`)}}async function o(){localStorage.setItem(ds,`off`),c();let t=await(await xs())?.pushManager.getSubscription();t&&(await m(`/api/push/unsubscribe`,{endpoint:t.endpoint}),await t.unsubscribe()),wr(e,`idle`,`This browser will not be notified.`)}t.onclick=()=>{wr(e,`saving`,`sending…`),(async()=>{let t=await m(`/api/push/test`,{});if(!t.ok)return wr(e,`failed`,await h(t,`Could not send`));let{sent:n,failed:r}=await t.json();wr(e,r?`failed`:`saved`,`Handed ${String(n)} device(s) to their push service${r?`, ${String(r)} refused`:``}.`)})()};function s(){if(!Es)return[];let e=dr(`Install Pier`,!0);return e.onclick=()=>{let e=Es;e&&e.prompt().then(()=>e.userChoice).finally(()=>{Es=null,c()})},[B(`div`,`flex items-center gap-3`,e,B(`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=hs();if(e){r.replaceChildren(...s(),B(`p`,`text-[12.5px] leading-snug text-neutral-500`,e));return}let c=i()&&Notification.permission===`granted`;t.disabled=!c,r.replaceChildren(...s(),Sr(`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 Ds=c,c(),hr(`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 K=null;function js(e){K&&!K.contains(e.target)&&q()}function Ms(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),q())}function Ns(e){K&&!K.contains(e.target)&&q()}function q(){K&&=(document.removeEventListener(`pointerdown`,js,!0),document.removeEventListener(`keydown`,Ms,!0),window.removeEventListener(`scroll`,Ns,!0),window.removeEventListener(`resize`,q),K.remove(),null)}var Ps=null;function Fs(e){let t=e.getBoundingClientRect(),n={top:t.bottom+4,left:t.left};return t.width||t.height?n:Ps?.anchor===e?{top:Ps.top,left:Ps.left}:n}var Is=()=>window.innerWidth<640;function Ls(e,t){q();let n=Is();if(K=B(`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]`}`),K.append(t),(e.closest(`dialog[open]`)??document.body).append(K),!n){let t=Fs(e);Ps={anchor:e,...t},K.style.top=`${Math.max(8,Math.min(t.top,window.innerHeight-K.offsetHeight-8))}px`,K.style.left=`${Math.max(8,Math.min(t.left,window.innerWidth-K.offsetWidth-8))}px`}document.addEventListener(`pointerdown`,js,!0),document.addEventListener(`keydown`,Ms,!0),window.addEventListener(`scroll`,Ns,!0),window.addEventListener(`resize`,q)}function Rs(e){let t=B(`button`,`flex w-full cursor-pointer items-center gap-2 px-3 text-left hover:bg-neutral-100 active:bg-neutral-100 ${Is()?`py-3`:`py-1.5`}`,B(`span`,`flex-none w-3 text-indigo-600`,e.checked?`✓`:``),B(`span`,`truncate`,e.label));return e.hint&&t.append(B(`span`,`ml-auto flex-none text-[11.5px] text-neutral-400`,e.hint)),t.onclick=()=>e.onSelect(),t}function zs(e,t){Ls(e,B(`div`,``,...t.map(Rs)))}var Bs=e=>`${e.provider}/${e.id}`,Vs=`pier.modelFavorites`,Hs=e=>`${Bs(e)}@${e.thinking}`,Us=null;async function Ws(){let{modelMenu:e}=await ie(`/api/settings`,`Could not read the pinned model menu`);return e}function Gs(){try{let e=JSON.parse(localStorage.getItem(Vs)??`[]`);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 Ks(e){let t=B(`button`,`flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-3 py-1.5 text-left`,B(`span`,`w-3 flex-none text-indigo-600`,e.checked?`✓`:``),B(`span`,`truncate`,e.label));e.hint&&t.append(B(`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=B(`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()},B(`div`,`group/row flex w-full items-center hover:bg-neutral-100`,t,n)}function qs({models:e,current:t,thinkingLevel:n,thinkingLevels:i,onPick:a,onThinkingPick:o}){let s=Gs(),c=n,l=B(`div`,`flex w-72 flex-col`),u=B(`div`,`flex flex-col gap-2 border-b border-neutral-200 px-2 py-2`),d=document.createElement(`input`);if(d.type=`search`,d.placeholder=`Search models`,d.setAttribute(`aria-label`,`Search models`),d.className=`w-full rounded-md border border-neutral-300 px-2 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`,u.append(d),i.length){let e=B(`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 i){let n=document.createElement(`option`);n.value=e,n.textContent=r(e),t.append(n)}t.value=n,t.onchange=()=>{c=t.value,re(d.value),o(c)},e.append(B(`span`,`font-medium`,`Reasoning`),t),u.append(e)}let ee=e=>{let t=Hs(e);s=s.some(e=>Hs(e)===t)?s.filter(e=>Hs(e)!==t):[...s,e],localStorage.setItem(Vs,JSON.stringify(s)),re(d.value)},f=(e,t)=>s.some(n=>Hs(n)===`${Bs(e)}@${t}`),p=B(`div`,`max-h-72 overflow-y-auto py-1`),te=new Map(e.map(e=>[Bs(e),e])),ne=(e,n,i)=>{let o=n.map(e=>({e,model:te.get(Bs(e))})).filter(e=>!!e.model&&(!i||Bs(e.model).toLowerCase().includes(i)));o.length&&p.append(B(`div`,`px-3 pb-0.5 pt-1 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),...o.map(({e,model:n})=>{let i=e.thinking??c;return Ks({label:n.id,hint:e.thinking?r(e.thinking):void 0,title:e.note,checked:!!t&&Bs(t)===Bs(n)&&c===i,starred:f(n,i),onSelect:()=>a(n,e.thinking),onStar:()=>ee({provider:n.provider,id:n.id,thinking:i})})}),B(`div`,`my-1 border-t border-neutral-100`))},re=n=>{p.replaceChildren();let r=n.trim().toLowerCase();ne(`Pinned`,Us??[],r),ne(`Starred`,s,r);let i=new Map;for(let t of e){if(r&&!Bs(t).toLowerCase().includes(r))continue;let e=i.get(t.provider);e?e.push(t):i.set(t.provider,[t])}if(!i.size){p.append(B(`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 i){let i=n.some(e=>!!t&&Bs(t)===Bs(e)),o=document.createElement(`details`);o.open=i||r.length>0;let s=B(`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`,B(`span`,`chev`,`▶`),B(`span`,`truncate`,e),B(`span`,`ml-auto flex-none normal-case text-neutral-300`,String(n.length)));o.append(s,...n.map(e=>Ks({label:e.id,checked:!!t&&Bs(t)===Bs(e),starred:f(e,c),onSelect:()=>a(e),onStar:()=>ee({provider:e.provider,id:e.id,thinking:c})}))),p.append(o)}};return d.oninput=()=>re(d.value),re(``),Ws().then(e=>{let t=JSON.stringify(e)!==JSON.stringify(Us);Us=e,t&&re(d.value)}).catch(e=>po(`model menu unavailable`,e)),l.append(u,p),queueMicrotask(()=>d.focus()),l}function Js(e,t,n,i){let a=fr(t.model?`${t.model.id}${t.thinking?` · ${r(t.thinking)}`:``}`:t.thinking?`Pi default · ${r(t.thinking)}`:`Pi default`,`${_r} flex cursor-pointer items-center gap-1.5 truncate text-left hover:bg-neutral-50 ${t.model?`text-neutral-700`:`text-neutral-400`}`);return a.title=t.model?`${t.model.provider}/${t.model.id}`:`Whatever the project and Pi pick`,a.onclick=()=>{let e=qs({models:n,current:t.model,thinkingLevel:t.thinking??`medium`,thinkingLevels:[...Ci],onPick:(e,n)=>{q(),i({model:e,thinking:n??t.thinking})},onThinkingPick:e=>i({...t,thinking:e})}),r=fr(`Pi default`,`w-full cursor-pointer px-3 py-1.5 text-left text-[12.5px] text-neutral-500 hover:bg-neutral-100`);r.onclick=()=>{q(),i({model:null,thinking:null})};let o=B(`div`,`flex flex-col`);o.append(e,B(`div`,`border-t border-neutral-200`),r),Ls(a,o)},gr(e,a)}var Ys=async e=>{let t=await g(`/api/fs/ls${e?.startsWith(`/`)?`?path=${encodeURIComponent(e)}`:``}`,`Could not list directories`);return t.ok?t.value:null},Xs=e=>e.entries.filter(e=>e.dir&&!e.name.startsWith(`.`)).map(e=>e.name),Zs=(e,t,n)=>{let r=fr(e,`flex w-full cursor-pointer items-center gap-1.5 px-3 py-1 text-left ${t}`);return r.onclick=n,r};function Qs(e,t){let n=B(`div`,`flex-none border-t border-neutral-200`),r=Zs(`+ 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=B(`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 m(`/api/fs/mkdir`,{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 $s(e,t,n){let r=e=>{n(e),q()};async function i(t){let n=await Ys(t);if(!n)return;let a=B(`div`,`flex max-h-80 w-80 flex-col`),o=fr(`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=document.createElement(`input`);s.className=`min-w-0 flex-1 border-0 bg-transparent font-mono text-[11.5px] text-neutral-500 focus:outline-none`,s.value=n.path,s.spellcheck=!1,s.title=`Type or paste a path, then Enter`,s.onfocus=()=>s.select();let c=B(`p`,`hidden flex-none px-3 pb-1 text-[11.5px] text-red-600`);s.onkeydown=async e=>{if(e.key!==`Enter`)return;e.preventDefault(),e.stopPropagation();let t=s.value.trim();if(!t)return;let n=await Ys(t);if(!n){c.textContent=`${t} is not a folder this can read`,c.classList.remove(`hidden`);return}r(n.path)};let l=B(`div`,`flex flex-none items-center gap-2 border-b border-neutral-200 px-3 py-1.5`,s,o),u=B(`div`,`min-h-0 flex-1 overflow-y-auto py-0.5 text-[12.5px]`);n.parent&&u.append(Zs(`../`,`font-mono text-neutral-500 hover:bg-neutral-100`,()=>void i(n.parent)));let d=Xs(n);for(let e of d)u.append(Zs(e,`truncate hover:bg-neutral-100`,()=>void i(`${n.path}/${e}`.replace(`//`,`/`))));d.length||u.append(B(`p`,`px-3 py-1.5 text-[12px] text-neutral-400`,`No sub-folders.`)),a.append(l,c,u,Qs(n.path,e=>void i(e))),Ls(e,a)}i(t)}function ec(e,t,n,r){zs(e,[...t.map(e=>({label:e.path,...e.hint?{hint:e.hint}:{},checked:e.path===n,onSelect:()=>{q(),r(e.path)}})),{label:`Browse…`,onSelect:()=>$s(e,n||void 0,r)}])}var tc=(e,t)=>n=>{e.value=n,e.dispatchEvent(new Event(`input`,{bubbles:!0})),t?.(n)};function nc(e,t){let n=fr(`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=()=>$s(n,e.value.trim()||void 0,tc(e,t)),n}function rc(e,t){let n=tc(e);e.classList.add(`select`),e.title=`Pick a project folder, or type a path`,e.onclick=()=>{let r=e.value.trim()||void 0,i=t();if(i.length)return ec(e,i,r,n);$s(e,r,n)},e.addEventListener(`input`,()=>q())}function ic(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:B(`div`,`flex items-center gap-1.5`,r,nc(r,n)),input:r}}var ac=z(`#sidebar`),oc=z(`#drawer-scrim`),sc=z(`#mobile-title`),cc=z(`#mobile-menu`);function lc(){delete ac.dataset.open,oc.classList.add(`hidden`)}function uc(e,t){sc.textContent=e,sc.classList.toggle(`cursor-pointer`,t),cc.classList.toggle(`hidden`,!t)}var dc=`pier.railClosed`;localStorage.getItem(dc)===`1`&&(document.body.dataset.rail=`closed`);function fc(e){document.body.dataset.rail=e?`closed`:``,localStorage.setItem(dc,e?`1`:`0`)}function pc(){if(ac.dataset.open!==void 0)return lc();ac.dataset.open=``,oc.classList.remove(`hidden`)}var mc=()=>window.innerWidth<768,hc=[z(`#rail-toggle`),z(`#drawer-toggle`)],gc=`attention absolute -right-0.5 -top-0.5 rounded-full bg-amber-500`,_c=e=>e===1?B(`span`,`${gc} h-2 w-2`):B(`span`,`${gc} flex h-3.5 min-w-3.5 items-center justify-center px-0.5 text-[9px] font-semibold text-white`,e>9?`9+`:String(e));function vc(e){for(let t of hc)t.querySelector(`.attention`)?.remove(),e&&t.append(_c(e))}var yc=20,bc=.35,xc=8;function Sc(){let e=-1,t=0,n=!1,r=!1,i=1,a=e=>{ac.style.transition=`none`,ac.style.transform=`translateX(${String(e-i)}px)`,oc.classList.remove(`hidden`),oc.style.opacity=String(e/i)},o=t=>{ac.style.transition=``,ac.style.transform=``,oc.style.opacity=``,t?(ac.dataset.open=``,oc.classList.remove(`hidden`)):lc(),e=-1,r=!1};window.addEventListener(`touchstart`,a=>{if(r||(e=-1,!mc()||a.touches.length!==1))return;let o=a.touches[0],s=ac.dataset.open!==void 0;if(i=ac.offsetWidth||1,s){if(o.clientX>i)return}else{if(o.clientX>yc||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)<xc)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=ac.getBoundingClientRect().right;o(n?t>i*bc:t>i*.65)};window.addEventListener(`touchend`,s),window.addEventListener(`touchcancel`,s)}function Cc(e){Sc(),z(`#drawer-toggle`).onclick=pc,oc.onclick=lc,cc.onclick=()=>e.sessionMenu(cc),sc.onclick=()=>{cc.classList.contains(`hidden`)||e.sessionInfo(sc)};let t=z(`#rail-toggle`);t.onclick=()=>fc(document.body.dataset.rail!==`closed`),Eo(t,`meta+b`,`Toggle sidebar`,()=>mc()?pc():fc(document.body.dataset.rail!==`closed`))}var J,wc=z(`#project-tree`),Tc=z(`#archive-dialog`),Ec=z(`#archive-list`),Dc=z(`#archive-search`),Oc=z(`#archive-count`),kc=z(`#new-dialog`),Ac=`pier.collapsedProjects`,jc=new Set(Mc());function Mc(){try{let e=JSON.parse(localStorage.getItem(Ac)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function Nc(e,t){t?jc.add(e):jc.delete(e),localStorage.setItem(Ac,JSON.stringify([...jc]))}function Pc(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}var Fc=e=>Pc(e,e=>e.cwd),Ic=e=>e.repo??e.cwd,Lc=e=>e.endsWith(`/.git`)?e.slice(0,-5):void 0,Rc=(e,t)=>er(Lc(e)??t[0]?.cwd??e);function zc(e,t){let n=Lc(e),r=[...new Set(t.map(e=>e.cwd))];return n&&r.includes(n)?[n,...r.filter(e=>e!==n)]:r}function Bc(e,t){return e===t?0:e===void 0?-1:t===void 0?1:e-t}function Vc(e){let t=[...Pc(e,Ic)].map(([e,t])=>[e,[...t].sort((e,t)=>(e.branch??e.cwd).localeCompare(t.branch??t.cwd)||Bc(e.sort,t.sort)||t.createdAt-e.createdAt)]),n=e=>{let t=e.map(e=>e.projectSort).filter(e=>e!==void 0);return t.length?Math.min(...t):void 0},r=e=>Math.min(...e.map(e=>e.createdAt));return t.sort(([,e],[,t])=>Bc(n(e),n(t))||r(t)-r(e))}function Hc(e,t,n,r){let i=e.filter(e=>e!==t);return i.splice(i.indexOf(n)+ +!!r,0,t),i}var Uc=()=>Vc(J.sessions().filter(e=>e.listed)),Wc=()=>Uc().flatMap(([e,t])=>zc(e,t).map(e=>{let n=t.find(t=>t.cwd===e)?.branch;return{path:e,...n?{hint:n}:{}}}));function Gc(e,t,n,r){let i=new Map(e.map((e,t)=>[e,t]));for(let e of J.sessions()){let r=i.get(t(e));r!==void 0&&n(e,r)}dl();let a=()=>void J.loadSessions();m(`/api/projects/order`,r).then(e=>{e.ok||a()},a)}function Kc(e,t,n,r){let i=Uc().find(([t])=>t===e);if(!i)return;let a=Hc(i[1].map(e=>e.id),t,n,r);Gc(a,e=>e.id,(e,t)=>e.sort=t,{sessions:a})}function qc(e,t,n){let r=Uc(),i=Hc(r.map(([e])=>e),e,t,n);Gc(i,Ic,(e,t)=>e.projectSort=t,{projects:i.flatMap(e=>{let t=r.find(([t])=>t===e);return t?zc(e,t[1]):[]})})}var Jc=null;function Yc(e,t){e.style.boxShadow=t===null?``:`inset 0 ${t?-2:2}px 0 0 #818cf8`}function Xc(e,t,n,r){e.draggable=!0,e.ondragstart=e=>{e.stopPropagation(),Jc={list:t,key:n},e.dataTransfer?.setData(`text/plain`,n)},e.ondragend=()=>{Jc=null,dl(!0)};let i=t=>{let n=e.getBoundingClientRect();return t.clientY>n.top+n.height/2},a=e=>!Jc||Jc.list!==t||Jc.key===n?!1:(e.preventDefault(),e.stopPropagation(),!0);e.ondragover=t=>{a(t)&&Yc(e,i(t))},e.ondragleave=()=>Yc(e,null),e.ondrop=t=>{let n=Jc?.key;Yc(e,null),a(t)&&n&&r(n,i(t))}}var Zc=`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`,Qc=e=>e.unread&&e.listed;function $c(e){let[t,n]=e.state===`streaming`?[`bg-green-500 animate-pulse`,`working…`]:Qc(e)?[`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=B(`span`,`h-2 w-2 flex-none rounded-full ${t}`);return r.title=n,r}async function el(e,t,n,r,i){let a=t=>{e(t),dl(),J.onPinsChanged()};a(t),(await m(r,i)).ok||a(n)}async function tl(e){let t=window.prompt(`Session name — empty resets it to the first message`,e.title??``);t!==null&&await el(t=>e.title=t,t.trim()||void 0,e.title,`/api/sessions/${e.id}/rename`,{name:t})}var nl=(e,t)=>el(t=>e.listed=t,t,!t,`/api/sessions/${e.id}/pin`,{pinned:t}),rl=(e,t)=>e.find(e=>e.cwd===t)?.branch??er(t),il=`flex-none truncate rounded bg-neutral-200/70 px-1 font-mono text-[10px] leading-[15px] text-neutral-500`,al={telegram:`tg`};function ol(e){if(!e.channel||e.channel===`web`)return[];let t=B(`span`,il,al[e.channel]??e.channel);return t.title=`answering ${e.channel}`,[t]}function sl(e){let t=B(`li`,`group flex cursor-pointer items-center gap-1.5 py-1.5 pl-6 pr-3 hover:bg-neutral-100 ${e.id===J.currentId()?`bg-indigo-50 hover:bg-indigo-50`:``}`),n=B(`button`,Zc,`⋯`);n.title=`Session actions`,n.onclick=t=>{t.stopPropagation(),J.sessionMenu(n,e)};let r=B(`button`,Zc,`✓`);r.title=`Done — remove from Projects (the session and its transcript stay)`,r.onclick=t=>{t.stopPropagation(),nl(e,!1)},t.append($c(e),B(`span`,`truncate`,e.title??`untitled`),B(`div`,`ml-auto flex flex-none items-center gap-1`,...ol(e),r,n)),t.onclick=()=>J.select(e.id),t.title=`Drag to reorder`;let i=Ic(e);return Xc(t,i,e.id,(t,n)=>Kc(i,t,e.id,n)),t}function cl(e,t){let n=zc(e,t),r=n[0]??e,i=B(`span`,`flex-none text-[11px] text-neutral-400 group-hover:hidden`,String(t.length)),a=B(`button`,Zc,`⋯`);a.title=`Project actions`,a.onclick=e=>{e.preventDefault(),e.stopPropagation(),zs(a,[...n.map(e=>({label:n.length>1?`New session in ${rl(t,e)}`:`New session here`,hint:er(e),onSelect:()=>{q(),J.createSession(e)}})),{label:`Browse files`,onSelect:()=>{q(),J.openFiles(r)}},{label:`Terminal here`,onSelect:()=>{q(),J.openTerminal(r)}},{label:`Remove ${t.length} session${t.length>1?`s`:``} from Projects`,onSelect:()=>{q();for(let e of t)nl(e,!1)}}])};let{el:o,summary:s}=lr(`border-b border-neutral-200/70`,[B(`span`,`truncate font-mono text-[11px] font-semibold uppercase tracking-wide text-neutral-500`,Rc(e,t)),B(`div`,`ml-auto flex flex-none items-center gap-1.5`,i,a)]);s.className+=` group px-3 py-1.5 hover:bg-neutral-100`,s.title=`${n.join(`
78
- `)}\nDrag to reorder`,Xc(s,``,e,(t,n)=>qc(t,e,n)),o.open=!jc.has(e),o.ontoggle=()=>Nc(e,!o.open);let c=B(`ul`,`pb-1`);return c.append(...t.map(sl)),o.append(c),o}var ll=()=>`${J.currentId()??``}\n${JSON.stringify(J.sessions())}`,ul=``;function dl(e=!1){let t=ll();if(t===ul&&!e)return;ul=t;let n=J.sessions().filter(Qc);vc(n.length),ks(n.filter(e=>e.channel===`web`).length);let r=Uc();wc.replaceChildren(...r.length?r.map(([e,t])=>cl(e,t)):[B(`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.`)]),Tc.open&&xl()}var fl=[{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`}],pl=[],ml=0,hl={ArrowDown:1,ArrowUp:-1},gl={n:1,j:1,p:-1,k:-1};function _l(e){if(pl.length){ml=(e+pl.length)%pl.length;for(let[e,{el:t}]of pl.entries())t.classList.toggle(`bg-indigo-100`,e===ml),t.classList.toggle(`border-indigo-500`,e===ml);pl[ml]?.el.scrollIntoView({block:`nearest`})}}function vl(e){let t=B(`button`,`flex-none rounded px-1.5 py-0.5 text-[11.5px] ${e.listed?`bg-indigo-50 text-indigo-600`:`text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700`}`,e.listed?`pinned`:`pin`);return t.title=e.listed?`Remove from Projects`:`Pin to Projects`,t.onclick=t=>{t.stopPropagation(),nl(e,!e.listed)},t}function yl(e){let t=B(`li`,`flex cursor-pointer items-center gap-2 border-l-2 border-transparent px-3 py-1.5 hover:bg-neutral-100`);return t.append(e.session?$c(e.session):B(`span`,`h-2 w-2 flex-none`)),t.append(B(`span`,`min-w-0 flex-1 truncate`,e.label),B(`span`,`max-w-[45%] flex-none truncate text-[11.5px] text-neutral-400`,e.detail)),e.session&&t.append(B(`span`,`flex-none text-[11px] text-neutral-400`,Qn(e.session.createdAt)),vl(e.session)),t.onclick=e.open,t}var bl=e=>B(`li`,`px-3 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-neutral-400`,e);function xl(){let e=Dc.value.trim().toLowerCase(),t=t=>!e||t.toLowerCase().includes(e),n=e=>()=>{Tc.close(),e()},r=e=>e.channel&&e.channel!==`web`?e.channel:``,i=J.sessions().filter(e=>t(`${e.title??``} ${e.cwd} ${r(e)}`)),a=(e,t)=>t.createdAt-e.createdAt,o=e=>({label:e.title??tr(e.cwd),detail:[er(e.cwd),r(e)].filter(Boolean).join(` · `),open:n(()=>J.select(e.id)),session:e}),s=i.filter(e=>e.state===`streaming`),c=i.filter(e=>e.state!==`streaming`),l=[`Console`,fl.filter(e=>t(`${e.label} ${e.detail}`)).map(({name:e,label:t,detail:r})=>({label:t,detail:r,open:n(()=>J.openConsole(e))}))],u=[[`Running`,s.sort(a).map(o)],[`Projects`,c.filter(e=>e.listed).sort(a).map(o)],[`Other sessions`,c.filter(e=>!e.listed).sort(a).map(o)]];e?u.unshift(l):u.push(l),pl=[];let d=[];for(let[e,t]of u)if(t.length){d.push(bl(e));for(let e of t){let t=yl(e);pl.push({el:t,open:e.open}),d.push(t)}}Ec.replaceChildren(...d.length?d:[B(`li`,`px-3 py-3 text-[13px] text-neutral-400`,`Nothing matches.`)]),Oc.textContent=String(pl.length),_l(ml)}function Sl(){if(Tc.open)return Tc.close();Dc.value=``,ml=0,xl(),Tc.showModal(),Dc.focus(),J.loadSessions().then(()=>{Tc.open&&xl()})}function Cl(e){J=e,rc(z(`#new-cwd`),Wc);let t=z(`#new-session`),n=()=>{let e=J.sessions().find(e=>e.id===J.currentId())?.cwd??``,t=z(`#new-cwd`);t.value=e,kc.showModal(),t.select()};t.onclick=n,Eo(t,`shift+o`,`New session`,n,()=>kc.open),z(`#new-cancel`).onclick=()=>kc.close(),z(`#new-form`).onsubmit=()=>void J.createSession(z(`#new-cwd`).value.trim());let r=z(`#open-archive`);r.onclick=Sl,Eo(r,`k`,`Search sessions and Console`,Sl,()=>Tc.open),z(`#archive-close`).onclick=()=>Tc.close(),Dc.oninput=()=>{ml=0,xl()},Dc.onkeydown=e=>{let t=e.altKey||e.metaKey||e.shiftKey||!e.key?void 0:e.ctrlKey?gl[e.key.toLowerCase()]:hl[e.key];if(t!==void 0){e.preventDefault(),_l(ml+t);return}e.key===`Enter`&&!e.ctrlKey&&(e.preventDefault(),pl[ml]?.open())}}var Y;function wl(e){Y=e,Ao(El,()=>{let e=Y.currentSession();e&&(q(),nl(e,!e.listed))},Tl),Ao(Dl,()=>{Y.currentSession()&&(q(),Y.toggleFiles())},Tl)}var Tl=()=>document.querySelector(`dialog[open]`)!==null,El=`d`,Dl=`i`,Ol=z(`#chat-title`),kl=z(`#chat-menu`),Al=z(`#session-meta`),jl=null,Ml=null,Nl=null,Pl=null;function Fl(){jl=null,Ml=null,Nl=null,Pl=null,Ul()}function Il(e,t,n,r){jl=e,Ml=t,Nl=n,Pl=r,Bl()}function Ll(e){Pl=e.completedAt,Ml&&={...Ml,tokens:e.tokens},Ul()}var Rl=null;function zl(e){Rl=e===null?null:tr(e),Bl()}function Bl(){let e=Y.currentSession();e&&(Rl=null),Ol.textContent=e?e.title??tr(e.cwd):Rl??`no session`,Ol.classList.toggle(`cursor-pointer`,!!e),Ol.title=e?`Session info`:``,Ol.onclick=e?()=>Wl(Ol,e):null,kl.classList.toggle(`hidden`,!e),e&&(kl.onclick=()=>Xl(kl,e)),Ul(),Y.syncBar()}var Vl=(e,t)=>Math.min(100,Math.round(e/t.contextWindow*100)),Hl=e=>e.tokens===null?`?/${i(e.contextWindow)}`:`${i(e.tokens)}/${i(e.contextWindow)} · ${100-Vl(e.tokens,e)}% left`;function Ul(){let e=Ml,t=e?.tokens??null,n=Y.currentId(),r=[];if(!n&&Rl&&r.push(B(`span`,`flex flex-none items-center gap-1.5 text-neutral-500`,B(`span`,`spinner`),`starting…`)),n){let e=(e,t)=>{let r=B(`button`,`flex-none cursor-pointer font-mono ${t}`,e);return r.title=`Change model or reasoning`,r.onclick=()=>void Gl(r,n),r};jl&&r.push(e(jl.id,`rounded bg-indigo-50 px-1.5 py-px font-medium text-indigo-700 hover:bg-indigo-100`)),Nl&&r.push(e(Nl,`text-neutral-500 hover:text-indigo-700`))}if(e&&t!==null){let n=Vl(t,e),a=n>=90?`text-red-700`:n>=70?`text-amber-700`:`text-neutral-500`;r.push(B(`span`,`flex-none font-mono ${a}`,i(t).toLowerCase()))}let a=r.flatMap((e,t)=>t===0?[e]:[B(`span`,`text-neutral-300`,`·`),e]);Al.replaceChildren(...a),Al.classList.toggle(`hidden`,r.length===0),Al.classList.toggle(`flex`,r.length>0)}function Wl(e,t){let n=[[`Title`,t.title??`untitled`],[`Directory`,t.cwd],[`Session`,t.id]],r=t.id===Y.currentId();if(r&&(n.push([`Model`,jl?.id??`—`]),n.push([`Reasoning`,Nl??`—`]),n.push([`Context`,Ml?Hl(Ml):`—`])),n.push([`Created`,nr(t.createdAt),$n(t.createdAt)]),r){let e=Pl;n.push(e===null?[`Last reply`,`—`]:[`Last reply`,nr(e),$n(e)])}let i=B(`div`,`flex max-w-80 flex-col gap-1.5 px-3 py-2`);for(let[e,t,r]of n){let n=B(`div`,`flex items-center gap-1.5`,B(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),cr(`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)),a=B(`span`,`break-all font-mono text-[12px] text-neutral-700`,t);r&&a.append(B(`span`,`ml-1.5 font-sans text-[11px] text-neutral-400`,r)),i.append(B(`div`,`group flex flex-col`,n,a))}Ls(e,i)}async function Gl(e,t){try{let[n,r]=await Promise.all([ie(`/api/sessions/${t}/models`,`Could not load models`),ie(`/api/sessions/${t}/thinking`,`Could not read the reasoning level`)]);Ls(e,qs({models:n,current:t===Y.currentId()?jl:null,thinkingLevel:r.level,thinkingLevels:r.levels,onPick:(e,n)=>{q(),Kl(t,e,n)},onThinkingPick:e=>void Jl(t,e)}))}catch(e){U(`error`,`model options failed: ${String(e)}`)}}async function Kl(e,t,n){await ql(e,t)&&n&&await Jl(e,n)}async function ql(e,t){let n=jl;e===Y.currentId()&&(jl=t,Bl());let r=await m(`/api/sessions/${e}/model`,t);if(!r.ok){let{error:t}=await r.json().catch(()=>({}));return e===Y.currentId()&&(jl=n,Bl()),U(`error`,`model change failed: ${t??r.status}`),!1}let{model:i}=await r.json();return e===Y.currentId()&&i&&(jl=i,Bl()),!0}async function Jl(e,t){let n=await m(`/api/sessions/${e}/thinking`,{level:t});if(!n.ok){U(`error`,`reasoning change failed: ${n.status}`);return}let{level:r}=await n.json();e===Y.currentId()&&(Nl=r,Ul())}async function Yl(e){let t=await m(`/api/sessions/${e}/compact`,{});t.ok||U(`error`,`compact failed: ${await h(t,`no reason given`)}`)}function Xl(e,t){let n=t.id===Y.currentId();zs(e,[{label:`Session info`,onSelect:()=>Wl(e,t)},{label:`Rename…`,onSelect:()=>{q(),tl(t)}},{label:t.listed?`Done — remove from Projects`:`Pin to Projects`,hint:n?Co(El):``,onSelect:()=>{q(),nl(t,!t.listed)}},{label:`Model`,hint:n?jl?.id??`…`:``,onSelect:()=>void Gl(e,t.id)},{label:`Compact context`,onSelect:()=>{q(),Yl(t.id)}},{label:`New session here`,hint:er(t.cwd),onSelect:()=>{q(),Y.createSession(t.cwd)}},{label:`Browse files`,hint:n?Co(Dl):``,onSelect:()=>{q(),Y.openFiles(n?void 0:t.cwd)}}])}var Zl=`pier.theme`,Ql=[`system`,`light`,`dark`],$l=window.matchMedia(`(prefers-color-scheme: dark)`),eu={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>`},tu=()=>{let e=null;try{e=localStorage.getItem(Zl)}catch{return`system`}return e===`light`||e===`dark`?e:`system`},nu=()=>{let e=tu();return e===`system`?$l.matches?`dark`:`light`:e};function ru(){let e=nu();document.documentElement.dataset.theme=e,z(`meta[name="theme-color"]`).setAttribute(`content`,e===`dark`?`#1c1c1c`:`#fafafa`),window.dispatchEvent(new Event(`pier:theme`))}function iu(){let e=z(`#theme-toggle`),t=()=>{let t=tu();e.title=`Theme: ${t}${t===`system`?` (${nu()})`:``}`,e.innerHTML=eu[t],ru()};e.onclick=()=>{let e=Ql[(Ql.indexOf(tu())+1)%Ql.length];try{e===`system`?localStorage.removeItem(Zl):localStorage.setItem(Zl,e)}catch{}t()},$l.addEventListener(`change`,t),t()}var au=`https://github.com/timqi/pier`,ou=[`text-neutral-400`,`hover:text-neutral-700`],su=[`rounded-full`,`bg-emerald-50`,`px-1.5`,`text-emerald-700`,`ring-1`,`ring-inset`,`ring-emerald-600/20`,`hover:bg-emerald-100`],cu=18e5,lu=null,uu=z(`#version`);function du(e){let t=lu?.available===!0&&lu.latest!==null;uu.textContent=`v${e}`,uu.title=t?`Pier ${lu?.latest} is out`:``,uu.classList.remove(...t?ou:su),uu.classList.add(...t?su:ou)}var fu=e=>B(`p`,`px-3 py-1 text-[12px] leading-snug text-neutral-500`,e);function pu(){let e=B(`div`,`flex w-72 flex-col gap-1 py-1`);if(!lu)return e.append(fu(`Checking the registry…`)),e;let{current:t,latest:n,available:r,canApply:i,problem:a}=lu;e.append(B(`p`,`px-3 py-1 text-[12.5px] font-medium text-neutral-700`,r?`Pier ${n} is out`:`Pier ${t}`)),e.append(fu(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=B(`span`,`px-3 text-[11.5px] text-neutral-400`,``),s=B(`div`,`flex items-center gap-2 px-3 py-1.5`);if(a&&e.append(B(`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=dr(`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 m(`/api/update`,{});if(!t.ok){e.disabled=!1,o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await h(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=B(`a`,`btn text-[12.5px] no-underline`,`Source`);c.href=r?`${au}/releases`:au,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(fu(`No service manager owns this Pier, so it cannot restart itself — update it with: pier update`));let l=Sr(`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.`,lu.autoUpdate,e=>{lu&&(lu.autoUpdate=e),(async()=>{let t=await m(`/api/settings`,{autoUpdate:e},`PUT`);if(t.ok)return;lu&&(lu.autoUpdate=!e);let n=l.querySelector(`input`);n&&(n.checked=!e),o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await h(t,`Could not save`)})()});if(!i){let e=l.querySelector(`input`);e&&(e.disabled=!0)}return e.append(B(`div`,`mt-1 border-t border-neutral-200 px-3 pb-1 pt-2`,l)),e}async function mu(e){let t=await g(`/api/update`,`Update check failed`);t.ok&&(lu=t.value,du(lu.current||e))}function hu(e){du(e),uu.onclick=e=>{e.preventDefault(),Ls(uu,pu())};let t=()=>void mu(e).catch(()=>{});t(),setInterval(t,cu)}var X,gu=z(`#chat-header`),_u=z(`#chat-title`),vu=[gu,H,z(`#composer`)],yu=()=>Tu===null,bu,xu,Su=new Map,Cu=new Map,wu=new Map,Tu=null,Eu=0,Du=`activity`,Ou=[`files`,`terminal`],ku=new Map,Au={tasks:`Tasks`,activity:`Activity`,boards:`Boards`,settings:`Settings`,files:`Files`,terminal:`Terminal`},ju=e=>bu?.refresh(e),Mu=()=>xu?.refresh();function Nu(){Tu?uc(Au[Tu],!1):uc(_u.textContent??``,X.currentSession()!==void 0)}function Z(e,t){if((e===`tasks`||e===`activity`)&&(Du=e),Ou.includes(e)){let t=Gu();t&&(t.kind!==`console`||t.name!==e)&&ku.set(e,t)}qu({kind:`console`,name:e,arg:t}),lc(),Tu=e;for(let e of vu)e.classList.add(`hidden`);Xo();for(let[t,n]of Su)t!==e&&n.hide();for(let[t,n]of wu)n.classList.toggle(`bg-indigo-50`,t===e||t===`activity`&&e===`tasks`);Nu(),Pu(e,t,++Eu)}async function Pu(e,t,n){let r=Su.get(e);if(!r){let t=Cu.get(e);if(!t){let n=z(`#${e}-view`);t=Xu[e](n).catch(t=>(console.warn(`${e} view failed to load`,t),ir(n,()=>n.replaceChildren(B(`p`,`p-4 text-[13px] text-red-600`,`Could not load ${Au[e]} — reload the page.`))))),Cu.set(e,t)}r=await t,Su.set(e,r),Cu.delete(e)}Tu===e&&n===Eu&&r.show(t)}var Fu=e=>Z(`tasks`,e),Iu=e=>Z(`files`,e),Lu=e=>Z(`terminal`,e),Ru=(e,t)=>{Tu===e?Vu(e):Z(e,t)},zu=e=>Ru(`files`,e),Bu=e=>Ru(`terminal`,e);function Vu(e){let t=X.currentId(),n=ku.get(e)??(t?{kind:`session`,id:t}:null);ku.delete(e),n?qu(n):(history.replaceState(null,``,`#/`),Hu())}function Hu(){if(Tu){Tu=null;for(let e of Su.values())e.hide();for(let e of wu.values())e.classList.remove(`bg-indigo-50`);for(let e of vu)e.classList.remove(`hidden`);Xo(),Nu(),X.maybeAckRead()}}var Uu=e=>e.kind===`session`?`#/session/${encodeURIComponent(e.id)}`:`#/${e.name}${e.arg?`/${encodeURIComponent(e.arg)}`:``}`,Wu={config:`files`,channels:`channels`,providers:`models`};function Gu(){let[e=``,t]=location.hash.replace(/^#\/?/,``).split(`/`);return Wu[e]?{kind:`console`,name:`settings`,arg:Wu[e]}:Object.hasOwn(Au,e)?{kind:`console`,name:e,arg:t?decodeURIComponent(t):void 0}:e===`session`&&t?{kind:`session`,id:decodeURIComponent(t)}:null}var Ku=!1;function qu(e,t=!1){if(Ku)return;let n=Uu(e);location.hash!==n&&(t?history.replaceState(null,``,n):location.hash=n)}var Ju=e=>qu({kind:`session`,id:e});function Yu(){let e=Gu(),t=X.sessions(),n=X.currentId(),r=(e?.kind===`session`?e.id:null)??n??(t.find(e=>e.listed)??t[0])?.id??null;Ku=!0;try{r&&r!==n&&X.select(r),e?.kind===`console`?Z(e.name,e.arg):Hu(),r||Bl()}finally{Ku=!1}e?.kind!==`console`&&r&&qu({kind:`session`,id:r},!0)}var Xu={tasks:async e=>bu=(await ui(async()=>{let{createTasksView:e}=await import(`./tasks-Dy1SCAE_.js`);return{createTasksView:e}},[])).createTasksView(e,()=>X.sessions().map(({id:e,cwd:t,title:n})=>({id:e,cwd:t,title:n})),X.loadSessions,X.select,()=>X.currentId(),e=>Z(`activity`,e)),activity:async e=>xu=(await ui(async()=>{let{createActivityView:e}=await import(`./activity-BsoWK6vt.js`);return{createActivityView:e}},[])).createActivityView(e,X.select,Fu),boards:async e=>(await ui(async()=>{let{createBoardsView:e}=await import(`./boards-DEMQ51m1.js`);return{createBoardsView:e}},[])).createBoardsView(e,X.select),files:async e=>(await ui(async()=>{let{createExplorerView:e}=await import(`./explorer-BTGQ6Syc.js`);return{createExplorerView:e}},__vite__mapDeps([0,1]))).createExplorerView(e,()=>X.currentSession(),e=>Z(`files`,e),e=>Z(`terminal`,e),()=>Vu(`files`)),terminal:async e=>(await ui(async()=>{let{createTerminalView:e}=await import(`./terminal-zLyOvGto.js`);return{createTerminalView:e}},[])).createTerminalView(e,()=>[...Fc(X.sessions()).keys()],()=>X.currentSession()?.cwd,e=>Z(`terminal`,e),e=>Z(`files`,e),()=>Vu(`terminal`)),settings:async e=>(await ui(async()=>{let{createSettingsView:e}=await import(`./settings-DSTKXN2o.js`);return{createSettingsView:e}},__vite__mapDeps([2,1]))).createSettingsView(e,()=>[...Fc(X.sessions()).keys()],e=>Z(`settings`,e))};function Zu(e){X=e;let t=z(`#open-terminal`);t.onclick=()=>Bu(),Eo(t,`meta+;`,`Terminal`,()=>Bu());for(let e of[`activity`,`boards`,`settings`]){let t=z(`#open-${e}`);wu.set(e,t),t.onclick=()=>Z(e===`activity`?Du:e)}let n=z(`#console-section`);n.open=localStorage.getItem(`pier.consoleCollapsed`)!==`1`,n.ontoggle=()=>localStorage.setItem(`pier.consoleCollapsed`,n.open?`0`:`1`),window.onhashchange=Yu}var Q=[],Qu=0,$=null,$u=`idle`,ed=null,td=0,nd=!1,rd=!1;async function id(e){Hu(),lc(),$=null,ed?.close(),ro(),Fl(),zl(e),io(!0),rd=!0,Yo();let t=await m(`/api/sessions`,{cwd:e});if(rd=!1,!t.ok){io(!1),zl(null),Yo(),U(`error`,`session create failed: ${t.status}`);return}let{id:n}=await t.json(),{repo:r,branch:i}=Q.find(t=>t.cwd===e)??{};Q.unshift({id:n,cwd:e,createdAt:Date.now(),state:`idle`,listed:!0,unread:!1,channel:`web`,activeRuns:0,repo:r,branch:i}),await hd(n),Go()}function ad(e,t){let n=e.map(e=>({...e,title:ne(e.title)}));if(t)Q=n;else{let e=new Map(n.map(e=>[e.id,e]));Q=Q.map(t=>e.get(t.id)??(t.listed?{...t,listed:!1}:t));let t=new Set(Q.map(e=>e.id));Q.push(...n.filter(e=>!t.has(e.id)))}Q.sort((e,t)=>t.createdAt-e.createdAt),dl(),cd()}var od=re(async()=>{ad(await ie(`/api/projects`,`Could not load projects`),!1)}),sd=re(async()=>{ad(await ie(`/api/sessions`,`Could not load sessions`),!0)});function cd(){if(document.hidden||!document.hasFocus()||!yu())return;let e=Q.find(e=>e.id===$);e?.unread&&(e.unread=!1,dl(),fetch(`/api/sessions/${e.id}/read`,{method:`POST`}))}function ld(){return Q.find(e=>e.id===$)}function ud(e,t){let n=Q.find(t=>t.id===e);!n||n.title||!t.trim()||(n.title=t.trim().slice(0,80),dl(),Bl())}function dd(e){$u=e;let t=Q.find(e=>e.id===$);t&&(t.state=e),dl(),Bl(),Yo(),e===`idle`&&od()}function fd(e){if(!(e.sessionId!==$||e.seq<=td))switch(td=e.seq,e.type){case`turn-start`:nd=!0;break;case`system-input`:eo(),Ea(e.text,e.origin);break;case`task-status`:Ni(e.run);break;case`user-message`:{let t=te(e.text).text;if(ud(e.sessionId,t),Ko(t))break;eo(),U(`user`,e.text,!1,e.ts),va();break}case`text-delta`:$a(e.text);break;case`thinking-delta`:aa(e.ts,e.text);break;case`tool-start`:eo(),ra(e.ts,e.toolCallId,e.toolName,e.args);break;case`tool-end`:ia(e.toolCallId,e.isError,e.output);break;case`turn-end`:nd=!1,to(e.text,e.meta),e.meta&&Ll(e.meta);break;case`queue-state`:Zo(e.steering,e.followUp);break;case`context-compacted`:eo(),U(`system`,`Context compacted — ${i(e.before)} → ${i(e.after)}`,!1,e.ts),va();break;case`error`:ta(),U(`error`,e.message);break;case`state`:e.state===`idle`&&nd&&(nd=!1,no()),e.state===`idle`&&Zo([],[]),dd(e.state)}}function pd(){let e=new EventSource(`/api/events`);e.onopen=()=>void od(),e.onerror=()=>vo(e,`Workspace`),e.onmessage=e=>{let t=JSON.parse(e.data);if(t.type===`sessions-changed`){od();return}if(t.type===`tasks-changed`||t.type===`task-run-changed`||t.type===`task-message-changed`||t.type===`task-group-changed`){ju(t.type===`task-run-changed`?t.taskId:void 0),Mu(),t.type===`task-run-changed`&&od();return}if(Mu(),t.sessionId===$)return;let n=Q.find(e=>e.id===t.sessionId);n&&(n.state=t.state,dl())}}function md(e,t){ed?.close();let n=new EventSource(`/api/sessions/${e}/events?after=${t}`);n.onmessage=e=>fd(JSON.parse(e.data)),n.onerror=()=>vo(n,`Session`),ed=n}async function hd(e){let t=++Qu;Hu(),lc(),Ju(e);let n=Q.some(t=>t.id===e);if(!(e===$&&n)){if(rs(),$=e,$u=Q.find(t=>t.id===e)?.state??`idle`,is(e),dl(),Bl(),cd(),n)return await gd(e);ed?.close(),ro(),io(!0),await sd(),t===Qu&&$===e&&await gd(e,!Q.some(t=>t.id===e))}}async function gd(e,t=!1){if(ed?.close(),ro(),Zo([],[]),Fl(),nd=!1,Jo(),td=0,io(!0),t){io(!1),U(`error`,`session not found: ${e}`);return}let n=await g(`/api/sessions/${e}/history`,`failed to load session`);if($!==e)return;if(!n.ok){io(!1),U(`error`,n.error);return}let r=n.value;ao(r.turns,r.state,r.backgroundRuns),td=r.lastSeq,nd=r.state===`streaming`,dd(r.state),Zo(r.queue.steering,r.queue.followUp);let i=r.turns.reduce((e,t)=>t.meta?.completedAt??e,null);Il(r.model,r.context,r.thinkingLevel,i),md(e,r.lastSeq)}mo(),_o(),iu();var _d=async e=>{$===e&&await gd(e)};da({sessionId:()=>$,sessionState:()=>$u,select:e=>void hd(e),showTasks:Fu,send:(e,t)=>void ss(e,t),ownTurn:e=>{qo(e),dd(`streaming`)},reload:_d}),us({sessionId:()=>$,starting:()=>rd,sessionState:()=>$u,chatVisible:yu,setState:dd,reload:_d}),Cc({sessionMenu:e=>{let t=ld();t&&Xl(e,t)},sessionInfo:e=>{let t=ld();t&&Wl(e,t)}}),Cl({sessions:()=>Q,loadSessions:sd,currentId:()=>$,select:e=>void hd(e),sessionMenu:Xl,createSession:id,openFiles:Iu,openTerminal:Lu,openConsole:Z,onPinsChanged:Bl}),wl({currentId:()=>$,currentSession:ld,createSession:e=>void id(e),syncBar:Nu,openFiles:Iu,toggleFiles:zu}),Zu({sessions:()=>Q,loadSessions:sd,currentId:()=>$,currentSession:ld,select:e=>void hd(e),maybeAckRead:cd}),hu(`0.0.19`),Ts(),document.addEventListener(`visibilitychange`,cd),window.addEventListener(`focus`,cd),pd(),od().then(Yu);export{$n as A,h as B,br as C,xr as D,vr as E,rr as F,m as G,ie as H,B as I,ne as K,Qn as L,ir as M,cr as N,Sr as O,lr as P,tr as R,mr as S,pr as T,oe as U,g as V,ae as W,hr as _,Ls as a,Dr as b,Ci as c,ui as d,_r as f,dr as g,fr as h,q as i,er as j,Or as k,gi as l,Tr as m,ec as n,As as o,Cr as p,r as q,Js as r,ko as s,ic as t,_i as u,Er as v,wr as w,yr as x,gr as y,re as z};
@@ -1,6 +0,0 @@
1
- import{A as e,B as t,C as n,D as r,E as i,G as a,I as o,M as s,N as c,O as l,S as u,V as d,_ as f,b as p,c as m,f as h,g,h as _,j as v,k as y,l as b,m as x,o as S,p as C,q as w,r as T,t as E,v as D,w as O,x as k,y as A}from"./index-BFzmvpGX.js";import{n as j,t as M}from"./code-DjWvqL94.js";var N={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`,`files:write`]}},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}},P=()=>`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(N))}`,F=()=>p(`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."]),I=(e=`left`)=>p(`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 ee(){let e=g(`Create Slack app ↗`,!0);e.classList.add(`mt-1`,`w-fit`),e.onclick=()=>window.open(P(),`_blank`,`noreferrer`);let t=c(`btn w-fit text-[12.5px]`,()=>JSON.stringify(N,null,2));return p(`Creating a Slack app`,[y(`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.",y(`Prefer to paste it yourself? Create the app from a manifest and use this:`,t)])}var L=()=>p(`What agent access allows`,["Gives agent sessions a `slack` tool: read a channel's history for a time range, read one thread, and post, edit or delete a message.",`Editing and deleting reach only what Pier's own bot posted — Slack refuses either on anyone else's 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.`,`The tool is only given to sessions opened while Slack is connected and this is on, so an unused tool costs no context. A session opened earlier keeps it, and a call made after you switch it off is refused with the reason.`]),R=(e=`left`)=>p(`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),z=()=>p(`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` (attachments, both directions), `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.`]),B=(e=`left`)=>p(`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),V=[[`telegram`,`Telegram`],[`slack`,`Slack`],[`lark`,`Lark`]],H=(e,t)=>o(`span`,`flex items-center gap-1.5 text-[13px] text-neutral-400`,o(`span`,``,e),t),te={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`},U=`pier.channelsPlatform`;function ne(e){let t=localStorage.getItem(U),n=V.some(([e])=>e===t)?t:`telegram`,r=null,c=[],p=o(`div`,`ml-auto flex items-center gap-1.5 text-[11.5px]`),m=o(`div`,`sticky top-0 z-30 flex items-center gap-1 border-b border-neutral-200 bg-white px-4 py-2`,p),h=o(`div`,`px-4 py-5`);e.append(o(`div`,`min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,m,h));function v(){m.replaceChildren(...V.map(([e,t])=>u(t,e===n,()=>{y&&M(),n=e,localStorage.setItem(U,e),N()})),p)}let y,b=!1,S=null;function w(e){if(p.replaceChildren(),e!==`clean`){if(p.className=`ml-auto flex items-center gap-1.5 text-[11.5px] ${C[e]}`,e===`saving`)p.append(o(`span`,`spinner`),o(`span`,``,`Saving…`));else if(e===`saved`)p.append(o(`span`,``,`✓`),o(`span`,``,`Saved`)),setTimeout(()=>{p.textContent?.includes(`Saved`)&&w(`clean`)},2e3);else{let e=_(`Retry`,`cursor-pointer underline`);e.onclick=M,p.append(o(`span`,``,`⚠`),o(`span`,``,`Save failed`),e)}}}function O(){w(`saving`),clearTimeout(y),y=setTimeout(M,500)}let k=e=>t=>{e(t),O()};async function j(e){b=!0,w(`saving`);try{w((await a(`/api/channels/${e.platform}`,e.config,`PUT`)).ok?`saved`:`failed`)}catch{w(`failed`)}finally{b=!1;let e=S;S=null,e&&j(e)}}function M(){if(clearTimeout(y),y=void 0,!r)return;let e={platform:n,config:r};b?S=e:j(e)}async function N(){if(!c.length){let e=await d(`/api/models`,`Could not load the model catalog`);e.ok&&(c=e.value)}let e=await d(`/api/channels/${n}`,`Failed to load`);if(!e.ok){r=null,v(),h.replaceChildren(D(e.error));return}r=e.value,w(`clean`),K()}function P(e){let t=n===`slack`,r=n===`lark`,a=i(e.token,t?`xoxb-…`:r?`cli_…`:`123456789:AA…`,k(t=>e.token=t),!0),o=i(e.appToken,r?``:`xapp-…`,k(t=>e.appToken=t),!0),s=E(e.cwd,`(pier process cwd)`,k(t=>e.cwd=t));return f(`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.`,l(`Enabled`,`Start the adapter when Pier boots.`,e.enabled,k(t=>{e.enabled=t,v()})),A(r?`App ID`:`Bot token`,a,{hint:`Stored locally, shown masked once saved.`,help:n===`telegram`?F():t?ee():z()}),...t?[A(`App-level token`,o,{hint:`Opens the Socket Mode connection. Needs connections:write.`}),l(`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,k(t=>e.agentTool=t),L())]:[],...r?[A(`App Secret`,o,{hint:`From Credentials & Basic Info, beside the App ID.`})]:[],A(`Default working directory`,s.el,{hint:`Where sessions this channel opens start.`}))}function ne(e){return f(`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.`,l(`Require mention in groups`,`Ignore group messages that do not @mention or reply to the bot.`,e.requireMention,k(t=>e.requireMention=t)),l(`Require bound user`,`Only users bound with a code below can drive the agent.`,e.requireBind,k(t=>e.requireBind=t)),...n===`slack`?[H(`Thread mode: always on`,R())]:n===`lark`?[H(`Thread mode: always on`,B())]:[l(`Topic mode`,`In a forum group, each new request opens its own topic and its own session.`,e.topicMode,k(t=>e.topicMode=t),I())],T(`Model & reasoning`,e,c,k(t=>{e.model=t.model,e.thinking=t.thinking,K()})))}function W(e){let t=o(`span`,`font-mono text-[15px] font-semibold tracking-widest`),r=o(`div`,`hidden items-center gap-2 rounded-lg bg-indigo-50 px-3 py-2 text-[12.5px] text-indigo-800`,t,o(`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=o(`div`,`flex flex-col`);e.users.length||a.append(D(`No bound users yet.`));for(let t of e.users){let e=_(`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 N()},a.append(o(`div`,`group flex items-center gap-2.5 border-b border-neutral-100 py-2 last:border-0`,o(`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()),o(`span`,`min-w-0 flex-1 truncate text-[13px] text-neutral-700`,t.name),o(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,t.id),e))}return f(`Bound users`,`A code is single-use and expires; redeeming it in a DM binds that account.`,a,o(`div`,`flex flex-col gap-2`,i,r))}function re(e,t){let r=o(`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`}`),i=o(`div`,`flex items-center gap-2`,o(`span`,`min-w-0 flex-1 truncate text-[13px] font-medium ${t.enabled?`text-neutral-800`:`text-neutral-400`}`,t.name||t.id),x(t.kind,te[t.kind]),o(`span`,`flex-none font-mono text-[11px] text-neutral-400`,t.id)),a=l(``,``,t.enabled,k(e=>{t.enabled=e,K()}));a.classList.add(`flex-none`,`items-center`),i.append(a);let s=o(`div`,`mt-3 flex flex-wrap items-center gap-x-6 gap-y-2`);t.kind===`dm`?s.append(o(`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(l(`Require mention`,``,t.requireMention,k(e=>t.requireMention=e)),l(`Require bind`,``,t.requireBind,k(e=>t.requireBind=e)),n===`slack`?H(`Thread mode: always on`,R(`right`)):n===`lark`?H(`Thread mode: always on`,B(`right`)):t.kind===`forum`?l(`Topic mode`,``,t.topicMode,k(e=>t.topicMode=e),I(`right`)):H(`Topic mode: forum groups only`,I(`right`)));let u=E(t.cwd,``,k(e=>t.cwd=e)),d=o(`div`,`mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2`,A(`Working directory`,u.el),T(`Model & reasoning`,t,c,k(e=>{t.model=e.model,t.thinking=e.thinking,K()})));return r.append(i,s,d),r}function G(e){let t=o(`div`,`flex flex-col gap-2.5`);return e.chats.length?t.append(...e.chats.map(t=>re(e,t))):t.append(D(`None yet. Chats appear here after the bot sees a message in them.`)),f(n===`slack`?`Channels`:`Chats`,`Discovered from inbound traffic — no platform reliably lists every chat a bot is in.`,t)}function K(){if(!r)return;v();let e=o(`div`,`mx-auto flex max-w-3xl flex-col gap-4`);e.append(P(r),ne(r),W(r),G(r)),h.replaceChildren(e)}return s(e,()=>void N(),()=>{y&&M()})}async function W(e,n){let r;try{r=await a(`/api/settings`,e,`PUT`)}catch(e){return{outcome:{state:`failed`,text:`Could not save: ${String(e)}`}}}if(!r.ok)return{outcome:{state:`failed`,text:await t(r,`could not save`)}};let i;try{i=await r.json()}catch(e){return{outcome:{state:`failed`,text:`Saved, but the answer could not be read: ${String(e)}`}}}return i.toolsSync?.state===`refused`?{outcome:{state:`failed`,text:`Saved, but nothing will install it: ${i.toolsSync.reason}`},answer:i}:i.toolsSync?.state===`waiting`?{outcome:{state:`saved`,text:`Saved — a sync is already running; this change goes in the run right after it.`},answer:i}:{outcome:{state:`saved`,text:n},answer:i}}function re(e,t){return e.enabled?{body:{tool:{name:e.name,on:!1}},saved:`Switched ${e.name} off — the next run uninstalls it. Remove it again once its binary is gone.`}:{body:{customTools:t.filter(t=>t.name!==e.name)},saved:`Removed ${e.name}.`}}function G(e,n){let r=`global`,c=null,u=0,f=0,p=``,m=null,g=[],_=``,y=null,S=[],C=()=>g.filter(e=>e.kind===`extension`),w=e=>e.source===`binary`&&e.custom===!0,T=()=>g.filter(e=>e.kind===`tool`),E=document.createElement(`select`);E.className=`select w-full rounded-md border border-neutral-300 px-2 py-1 text-[12.5px] focus:border-indigo-400 focus:outline-none`,E.onchange=()=>{r=E.value,c=null,G.clear(),B()};let D=o(`div`,`flex flex-none flex-col gap-1 border-b border-neutral-200 px-3 pb-2.5 pt-2`);D.append(o(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,`Scope`),E);let k=o(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),N=o(`nav`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[13px]`);N.append(D,k);let P=o(`div`,`flex min-w-0 flex-1 flex-col`),F=o(`div`,`flex min-h-0 flex-1`);F.append(N,P),e.append(F);let I=(e=``)=>`?scope=${encodeURIComponent(r)}${e}`;async function ee(){if(r!==`global`){g=[],_=``;return}let e=await d(`/api/settings`,`could not be loaded`,{cache:`no-store`});if(!e.ok){g=[],_=e.error;return}L(e.value),_=``}function L(e){g=e.catalog,S=e.customTools,y=e.toolsTaskId}async function R(e,t){let{outcome:n,answer:r}=await W(e,t);return r&&(L(r),q(m)),n}function z(e,t){let n={name:e,on:t};return g.find(t=>t.name===e)?.source===`binary`?{tool:n}:{extension:n}}async function B(){let e=++u;f++;let[t]=await Promise.all([d(`/api/config${I()}`,`failed to load config`,{cache:`no-store`}),ee()]);if(e!==u)return;if(!t.ok){q(null),J(t.error);return}let n=t.value;r===`global`&&n.dir&&(p=n.dir,le()),m=n,q(n),c||ie()}function V(e){return o(`div`,`px-3 pb-0.5 pt-2.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e)}let H=()=>{let e=o(`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},te=()=>o(`span`,`flex-none rounded bg-emerald-50 px-1 text-[10px] font-semibold uppercase tracking-wide text-emerald-700`,`on`);function U(e,t,n,r,i=0,a){let s=o(`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 s.append(o(`span`,`truncate`,e)),a&&s.append(a),s.style.paddingLeft=`${20+i*14}px`,s.title=e,s.onclick=r,s}function ne(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 G=new Set;function K(e,t,n,r,i,a){let s=[];for(let[c,l]of t.dirs){let t=n?`${n}/${c}`:c,u=`${e}:${t}`,d=document.createElement(`details`);d.open=G.has(u),d.ontoggle=()=>d.open?G.add(u):G.delete(u);let f=o(`summary`,`flex cursor-pointer select-none items-center gap-1 truncate py-1 pr-3 hover:bg-neutral-100`);f.style.paddingLeft=`${20+r*14}px`,f.title=t,f.append(o(`span`,`chev`,`▶`),o(`span`,`truncate text-neutral-600`,c)),l.link&&f.append(H()),d.append(f,...K(e,l,t,r+1,i,a)),s.push(d)}for(let o of t.files){let t={type:`resource`,kind:e,name:n?`${n}/${o.name}`:o.name};s.push(U(o.name,i(t),!1,()=>a(t),r,o.link?H():void 0))}return s}function q(e){if(!e){k.replaceChildren();return}let t=e=>JSON.stringify(e)===JSON.stringify(c),n=t=>{c=t,q(e),t.type===`file`?X(t.name):t.type===`bundled`?Q(t.name):t.type===`tools`?$():ce(t.kind,t.name)},i=[];i.push(V(`Files`));for(let r of e.files){let e={type:`file`,name:r.name};i.push(U(r.name,t(e),!r.exists,()=>n(e)))}if(r===`global`){i.push(V(`bundled with Pier`)),_?i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-red-600`,_)):C().length||i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`));for(let e of C()){let r={type:`bundled`,name:e.name};i.push(U(e.name,t(r),!1,()=>n(r),0,e.enabled?te():void 0))}if(!_){let e={type:`tools`},r=T().filter(e=>e.enabled).length;i.push(U(`command-line tools`,t(e),!1,()=>n(e),0,r?te():void 0))}}for(let r of[`extensions`,`skills`]){i.push(V(`${r} (read-only)`));let a=e.resources[r];a.length||i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`)),i.push(...K(r,ne(a),``,0,t,n))}k.replaceChildren(...i)}function ie(){P.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Select a file to edit, or browse extensions and skills.`))}function J(e){P.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-red-600`,e))}let Y=(e,...t)=>o(`div`,`flex flex-none items-center gap-3 border-b border-neutral-200 px-4 py-2`,o(`span`,`font-mono text-[12.5px] text-neutral-500`,e),...t);async function X(e){let n=++f,r=await d(`/api/config/files/${encodeURIComponent(e)}${I()}`,`failed to load ${e}`,{cache:`no-store`});if(!r.ok){n===f&&J(r.error);return}if(n!==f)return;let{content:i}=r.value,s=i,c=o(`span`,`text-[11.5px] text-neutral-400`,``),l=o(`button`,`btn btn-primary ml-auto text-[12.5px]`,`Save`),u=document.createElement(`textarea`);u.className=`block min-h-0 flex-1 resize-none bg-white p-4 font-mono text-[13px] leading-relaxed focus:outline-none`,u.spellcheck=!1,u.value=i;let p=async()=>{if(l.disabled)return;let n=u.value;l.disabled=!0,O(c,`saving`,`saving…`);try{let r=await a(`/api/config/files/${encodeURIComponent(e)}${I()}`,{content:n,expected:s},`PUT`);if(!r.ok)return O(c,`failed`,await t(r,`save failed`));let i=await r.json();s=i.content,u.value===n?(u.value=i.content,O(c,`saved`,`saved — applies to new sessions`)):O(c,`idle`,`saved; newer changes are unsaved`)}catch(e){O(c,`failed`,`save failed: ${String(e)}`)}finally{l.disabled=!1}};l.onclick=()=>void p(),u.onkeydown=e=>{(e.metaKey||e.ctrlKey)&&e.key===`s`&&(e.preventDefault(),p())},u.oninput=()=>{O(c,`idle`,`unsaved changes`)},P.replaceChildren(Y(e,c,l),u),u.focus()}function ae(e){if(!y)return null;let t=o(`a`,`text-indigo-600 hover:underline`,e);return t.href=`#/tasks/${encodeURIComponent(y)}`,t}let Z=()=>{let e=o(`a`,`text-indigo-600 hover:underline`,`ubix`);return e.href=`https://github.com/timqi/ubix`,e.target=`_blank`,e.rel=`noreferrer`,e};function oe(e){if(e.source!==`binary`)return``;let{spec:t,error:n,installed:r,version:i,path:a}=e.binary;return n?`${t} — ${n}`:r?`${t} — ${i??`unknown version`} at ${a??`an unknown path`}`:`${t} — not installed`}function Q(e,t){f++;let n=g.find(t=>t.name===e&&t.kind===`extension`);if(!n)return J(`unknown extension: ${e}`);let r=o(`span`,`text-[11.5px] text-neutral-400`,``);t&&O(r,t.state,t.text);let i=ae(`every run of the update task`);P.replaceChildren(Y(n.name,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,n.source===`binary`?`installed by Pier`:`ships with Pier`)),o(`div`,`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,o(`p`,`max-w-2xl text-[13px] leading-relaxed text-neutral-600`,n.summary),o(`dl`,`flex max-w-2xl flex-col gap-1.5`,...(n.source===`bundled`?n.adds:[]).flatMap(e=>[o(`dt`,`font-mono text-[12px] text-neutral-700`,e.name),o(`dd`,`text-[12px] leading-snug text-neutral-500`,`needs ${e.needs}`)]),...n.source===`binary`?[o(`dt`,`font-mono text-[12px] text-neutral-700`,`binary`),o(`dd`,`font-mono text-[12px] leading-snug ${n.binary.error?`text-red-600`:`text-neutral-500`}`,oe(n))]:[]),l(`Enabled`,n.source===`binary`?`Installed into Pier's own bin directory, first on the PATH every session, task and terminal inherits; it registers its own Pi extension. Switching it off uninstalls both.`:`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,t=>void se(n.name,t,t=>Q(e,t))),o(`p`,`max-w-2xl text-[12px] leading-snug text-neutral-400`,...n.source===`binary`?i?[`A daily task installs and updates it — its history is `,i,`.`]:[`Its installs run as the daily update task.`]:[`An extension of your own that registers the same tool wins: this copy stands down and says so in the log.`]),r))}function $(e,t={name:``,toml:``}){f++;let n=o(`span`,`text-[11.5px] text-neutral-400`,``);e&&O(n,e.state,e.text);let r=T(),a=ae(`the update task`),s=e=>{let t=o(`div`,`flex min-w-0 flex-1 flex-col gap-0.5`,o(`span`,`flex items-center gap-2 text-[13px] text-neutral-700`,o(`span`,`font-mono`,e.name),...w(e)?[x(`yours`,`bg-neutral-50 text-neutral-500 ring-neutral-200`)]:[]),o(`span`,`text-[11.5px] leading-snug text-neutral-400`,e.summary||oe(e)),...e.summary?[o(`span`,`font-mono text-[11px] leading-snug ${e.source===`binary`&&e.binary.error?`text-red-600`:`text-neutral-400`}`,oe(e))]:[]),n=l(``,``,e.enabled,t=>void se(e.name,t,e=>$(e))),r=o(`button`,`btn text-[12px] text-neutral-500 hover:text-red-600`,`Remove`);return r.onclick=()=>{r.disabled=!0;let t=re(e,S);R(t.body,t.saved).then(e=>$(e))},o(`div`,`flex max-w-2xl items-start gap-3 border-b border-neutral-100 py-2.5 last:border-0`,t,...w(e)?[r]:[],n)},c={...t},u=o(`span`,`font-mono text-[12px] text-neutral-500`,`[tools.<name>]`),d=i(c.name,`claude`,e=>{c.name=e,u.textContent=`[tools.${e.trim()||`<name>`}]`},!0),p=document.createElement(`textarea`);p.className=`${h} h-24 resize-y font-mono leading-snug`,p.spellcheck=!1,p.value=c.toml,p.placeholder=`spec = "github:owner/repo"
2
- exe = "tool"`,p.oninput=()=>c.toml=p.value;let m=o(`button`,`btn btn-primary text-[12.5px]`,`Add`);m.onclick=()=>{let e={name:c.name.trim(),toml:c.toml.trim()};if(!e.name||!e.toml)return O(n,`failed`,`A custom tool needs a name and a block with a spec line.`);m.disabled=!0,R({customTools:[...S,e],tool:{name:e.name,on:!0}},`Added ${e.name} — installing now.`).then(e=>$(e,e.state===`failed`?c:void 0))},P.replaceChildren(Y(`command-line tools`,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`installed by Pier`)),o(`div`,`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,o(`p`,`max-w-2xl text-[12.5px] leading-relaxed text-neutral-500`,`Pier writes no downloader: `,Z(),` does the work — a declarative installer that resolves a spec like `,o(`span`,`font-mono text-[11.5px]`,`github:owner/repo`),` to the right release asset for this machine, verifies it, and upgrades in place. Pier bootstraps it, generates its config from the switches below, and keeps its files under Pier's own directory — your own ubix setup is untouched.`),_?o(`p`,`max-w-2xl text-[12.5px] text-red-600`,_):o(`div`,`flex max-w-2xl flex-col`,...r.map(s)),o(`div`,`flex max-w-2xl flex-col gap-2 border-t border-neutral-200 pt-4`,o(`span`,`text-[12.5px] font-medium text-neutral-600`,`Add one of your own`),A(`Name`,d),A(`The block Pier writes under the header`,p,{hint:`A line that opens a section of its own is refused, because it could rewrite the rest of the file.`}),o(`div`,`flex items-center gap-3`,u,m)),o(`p`,`max-w-2xl text-[12px] leading-snug text-neutral-400`,...a?[`Installs and daily updates run as `,a,` — output, failures and all.`]:[`Switching one on creates the daily task that installs it and keeps it current.`]),n))}async function se(e,t,n){let r=g.find(t=>t.name===e);n(await R(z(e,t),r?.source===`binary`?t?`Saved — installing now; watch the run.`:`Saved — uninstalling in the next run.`:`Saved — sessions take it on their next message.`))}async function ce(e,t){let n=++f,r=await d(`/api/config/resource${I(`&kind=${e}&name=${encodeURIComponent(t)}`)}`,`failed to load ${t}`,{cache:`no-store`});if(!r.ok){n===f&&J(r.error);return}if(n!==f)return;let{content:i}=r.value,a=i.split(`
3
- `);a.at(-1)===``&&a.pop();let s=await b(t);n===f&&P.replaceChildren(Y(t,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`read-only`)),o(`div`,`min-h-0 flex-1 overflow-auto`,M(j(a),s)))}function le(){E.replaceChildren(new Option(p?`Global (${p})`:`Global`,`global`),...n().map(e=>new Option(`${v(e)} — ${e}`,e))),[...E.options].some(e=>e.value===r)||(r=`global`),E.value=r}return s(e,()=>{le(),B()})}var K=e=>`${e.provider}/${e.id}`,q=[`hardest reasoning — architecture, gnarly debugging`,`long autonomous implementation runs`,`balanced default — implementation, review`,`cheap & fast — listings, extraction, simple checks`,`cross-vendor second opinion`];function ie(){let e=[],r=[],i=!1,s=o(`span`,`text-[11.5px]`,``),c=g(`Save menu`,!0),l=o(`div`,`flex min-w-0 flex-col gap-2`),u=o(`div`,`flex items-center gap-2`),p=o(`div`,`mx-auto flex w-full max-w-3xl min-w-0 flex-col gap-6`);function h(){i=!0,O(s,`idle`,`unsaved changes`)}function _(t){let r=k(t.note??``);r.classList.remove(`w-full`),r.classList.add(`min-w-0`,`flex-1`),r.placeholder=`why this one — pick a preset or write your own`,r.setAttribute(`list`,`model-menu-notes`),r.oninput=()=>{t.note=r.value,h()};let i=n([[`thinking: model default`,``],...m.map(e=>[`thinking: ${w(e)}`,e])],t.thinking??``);i.classList.replace(`w-full`,`w-44`),i.classList.add(`flex-none`),i.onchange=()=>{i.value?t.thinking=i.value:delete t.thinking,h()};let a=g(`Remove`);a.classList.add(`flex-none`),a.onclick=()=>{e=e.filter(e=>e!==t),h(),y()};let s=o(`span`,`w-52 flex-none truncate font-mono text-[12px] text-neutral-700`,K(t));return s.title=K(t),o(`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`,s,i,r,a)}function v(){let t=r.filter(t=>!e.some(e=>K(e)===K(t))),i=n(t.map(e=>[K(e),K(e)]),t[0]?K(t[0]):``);i.classList.replace(`w-full`,`flex-1`),i.classList.add(`min-w-0`);let a=g(`+ Pin model`);a.classList.add(`flex-none`,`whitespace-nowrap`),a.disabled=t.length===0,a.onclick=()=>{let n=t.find(e=>K(e)===i.value);n&&(e.push({...n}),h(),y())},u.replaceChildren(i,a)}function y(){l.replaceChildren(...e.length?e.map(_):[D(`Nothing pinned — every picker shows the curated catalog as is.`)]),v()}async function b(){O(s,`saving`,`saving…`);let n=e.map(({provider:e,id:t,thinking:n,note:r})=>({provider:e,id:t,...n?{thinking:n}:{},...r?.trim()?{note:r.trim()}:{}})),r=await a(`/api/settings`,{modelMenu:n},`PUT`);if(!r.ok)return O(s,`failed`,await t(r,`Could not save`));e=(await r.json()).modelMenu,i=!1,O(s,`saved`,`Saved — agents see it on their next models call.`),y()}c.onclick=()=>void b();function x(){i||(async()=>{let[t,n]=await Promise.all([d(`/api/settings`,`Could not load the menu`),d(`/api/models`,`Could not load the model catalog`)]);if(!t.ok)return O(s,`failed`,t.error);e=t.value.modelMenu,r=n.ok?n.value:[],s.textContent=``,y()})()}let S=o(`datalist`,``);return S.id=`model-menu-notes`,S.append(...q.map(e=>new Option(e))),p.append(f(`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.`,A(`Pinned models`,l,{hint:`The note is what an agent matches a task against — say when to reach for it, not what it is.`}),A(`Add`,u,{hint:`The list is the live catalog — only models that exist right now can be pinned.`}),o(`div`,`flex items-center gap-3`,c,s),S)),{el:p,load:x}}var J=(e,t)=>{let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`http:`&&n.protocol!==`https:`)return null;let r=o(`a`,`text-indigo-600 hover:underline`,t);return r.href=n.href,r.target=`_blank`,r.rel=`noreferrer`,r};function Y(e,n,r,i){let s=document.createElement(`dialog`);s.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let l=o(`div`,`flex flex-col gap-2`),u=o(`div`,`flex flex-col gap-2`),d=o(`p`,`text-[12.5px] text-neutral-400`,`Starting…`),f=g(`Cancel`),p=(e,t)=>{d.className=`text-[12.5px] ${C[e]}`,d.textContent=t};s.append(o(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,n),o(`div`,`flex max-h-[65vh] flex-col gap-3 overflow-y-auto px-4 py-3`,l,u,d),o(`div`,`flex justify-end border-t border-neutral-200 px-4 py-2.5`,f)),document.body.append(s),s.showModal();let m=e.id,h=e.state,_,v,y=new Set,b=!1,x=!1,S=async e=>{if(!x){if(e&&h===`running`){x=!0,f.disabled=!0;try{let e=await a(`/api/providers/flows/${m}/cancel`,{});if(!e.ok&&e.status!==404){p(`failed`,await t(e,`Could not cancel authentication flow`));return}}catch(e){p(`failed`,`Could not cancel authentication flow: ${String(e)}`);return}finally{x=!1,f.disabled=!1}}clearTimeout(_),s.close()}};f.onclick=()=>void S(!0),s.oncancel=e=>{e.preventDefault(),S(!0)},s.onclose=()=>{b=!0,clearTimeout(_),s.remove()};let w=e=>{if(e.type===`auth_url`){let t=o(`div`,`flex flex-col gap-1 text-[12.5px] text-neutral-600`);return e.instructions&&t.append(o(`p`,``,e.instructions)),t.append(J(e.url,`Open authorization page`)??o(`span`,`text-red-600`,`Invalid authorization URL`)),t}if(e.type===`device_code`){let t=o(`div`,`flex flex-col gap-2 text-[12.5px] text-neutral-600`);return t.append(o(`div`,`flex items-center gap-2`,o(`code`,`font-mono text-[17px] font-semibold text-neutral-800`,e.userCode),c(`btn text-[11px]`,()=>e.userCode))),t.append(J(e.verificationUri,`Open verification page`)??o(`span`,`text-red-600`,`Invalid verification URL`)),t}let t=o(`div`,`text-[12.5px] text-neutral-600`,e.message);if(e.type===`info`)for(let n of e.links??[]){let e=J(n.url,n.label??n.url);e&&t.append(` `,e)}return t},T=(e,n)=>{v=n.id;let r;if(n.type===`select`){let e=document.createElement(`select`);e.append(...n.options.map(e=>new Option(e.description?`${e.label} — ${e.description}`:e.label,e.id))),r=e}else{let e=k(``,n.type===`secret`?`password`:`text`);e.placeholder=n.placeholder??``,e.autocomplete=`off`,r=e}r.className=`${r.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 i=g(`Continue`,!0);i.type=`submit`;let s=o(`form`,`flex flex-col gap-2`,o(`label`,`text-[12.5px] font-medium text-neutral-700`,n.message),r,o(`div`,`flex justify-end`,i));s.onsubmit=o=>{o.preventDefault(),i.disabled=!0,(async()=>{try{let i=await a(`/api/providers/flows/${e.id}/respond`,{promptId:n.id,value:r.value});if(b)return;if(!i.ok){p(`failed`,await t(i,`Could not submit response`));return}y.add(n.id),v=void 0,u.replaceChildren(),p(`saving`,`Waiting for provider…`)}catch(e){b||p(`failed`,`Could not submit response: ${String(e)}`)}finally{i.disabled=!1}})()},u.replaceChildren(s),r.focus()},E=e=>{h=e.state,l.replaceChildren(...e.events.map(w));let t=e.prompt&&!y.has(e.prompt.id)?e.prompt:void 0;if(t?.id!==v&&(t?T(e,t):(v=void 0,u.replaceChildren())),e.state===`running`){p(`saving`,t?`Waiting for your response.`:`Waiting for provider…`);return}clearTimeout(_),u.replaceChildren(),e.state===`succeeded`?p(`saved`,`${r} configured.`):p(`failed`,e.state===`cancelled`?`Cancelled.`:e.error??`Authentication failed.`),f.textContent=`Close`,f.onclick=()=>void S(!1),e.state===`succeeded`&&i()},D=async()=>{if(!(b||h!==`running`))try{let e=await fetch(`/api/providers/flows/${m}`,{cache:`no-store`});if(b)return;if(!e.ok){p(`failed`,await t(e,`Authentication status unavailable`)),e.status===404?h=`failed`:_=setTimeout(()=>void D(),1e3);return}E(await e.json()),h===`running`&&(_=setTimeout(()=>void D(),500))}catch(e){if(b)return;p(`failed`,`Authentication status unavailable: ${String(e)}`),_=setTimeout(()=>void D(),1e3)}};E(e),h===`running`&&(_=setTimeout(()=>void D(),500))}var X=[`anthropic`,`openai`,`openai-codex`,`google`,`openrouter`,`deepseek`],ae=[[`OpenAI Chat Completions`,`openai-completions`],[`OpenAI Responses`,`openai-responses`],[`Anthropic Messages`,`anthropic-messages`],[`Google Generative AI`,`google-generative-ai`]],Z=`__custom__`;async function oe(e){let r=g(`Add provider`,!0);r.classList.add(`ml-auto`);let i=o(`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`,o(`h2`,`text-[13px] font-semibold text-neutral-700`,`Providers`),r),s=o(`div`,`min-h-0 flex-1 overflow-y-auto`);e.replaceChildren(i,s);let c=[],l=``,u=async()=>{s.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Loading…`));try{let[e,t]=await Promise.all([d(`/api/providers`,`Could not load providers`,{cache:`no-store`}),d(`/api/models`,`the model catalog could not be read`,{cache:`no-store`})]);if(c=t.ok?t.value:[],l=t.ok?``:t.error,!e.ok){s.replaceChildren(D(e.error));return}let n=e.value;r.onclick=()=>$(n,void 0,u),_(n)}catch(e){s.replaceChildren(D(`Could not load providers: ${String(e)}`))}},f=async e=>{if(window.confirm(`Remove the stored credential for ${e.name}?`))try{let n=await a(`/api/providers/${encodeURIComponent(e.id)}/logout`,{});if(!n.ok){window.alert(await t(n,`Could not remove credential`));return}await u()}catch(e){window.alert(`Could not remove credential: ${String(e)}`)}},p=e=>[...new Set([...(e.models??[]).map(e=>e.id),...c.filter(t=>t.provider===e.id).map(e=>e.id)])],m=(e,t)=>o(`div`,`flex flex-col gap-1`,o(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),o(`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)),h=async(e,n)=>{try{let r=await a(`/api/providers/${encodeURIComponent(e)}/check`,{model:n});return r.ok?await r.json():await t(r,`Could not test`)}catch(e){return`Could not test: ${String(e)}`}},_=e=>{let t=e.filter(e=>e.configured);if(!t.length){s.replaceChildren(D(`No providers configured.`));return}s.replaceChildren(...t.map(t=>{let r=o(`div`,`min-w-0 flex-1`,o(`div`,`truncate text-[13px] font-medium text-neutral-700`,t.name),o(`div`,`truncate font-mono text-[11px] text-neutral-400`,t.id)),i=t.stored===`api_key`?`API key`:t.stored===`oauth`?`OAuth`:t.source??`configured`,a=t.endpoint??`Default endpoint`,s=o(`div`,`flex min-w-32 flex-col items-start gap-1`,x(`configured`,`bg-emerald-50 text-emerald-700 ring-emerald-200`),o(`span`,`max-w-48 truncate text-[11px] text-neutral-500`,i),o(`span`,`max-w-48 truncate text-[11px] text-neutral-400`,a));s.title=a;let c=o(`span`,`text-[11.5px]`,``),d=o(`div`,`hidden flex-col gap-2 px-4 pb-3`,c),_=o(`div`,`flex flex-wrap justify-end gap-1.5`),v=p(t);if(!v.length)O(c,`idle`,l||`No models to test: none are configured here.`),d.classList.replace(`hidden`,`flex`);else{let e=n([[`Model to test…`,``],...v.map(e=>[e,e])],``);e.classList.add(`max-w-52`,`text-[12px]`);let r=g(`Test`);r.disabled=!0,e.onchange=()=>r.disabled=!e.value,r.onclick=()=>{let n=e.value;r.disabled=!0,d.replaceChildren(c),d.classList.replace(`hidden`,`flex`),O(c,`saving`,`asking ${n}…`),h(t.id,n).then(e=>{if(r.disabled=!1,typeof e==`string`)return O(c,`failed`,e);O(c,e.ok?`saved`:`failed`,`${e.model} ${e.ok?`answered`:`did not answer`} in ${e.ms} ms`),d.append(m(`sent`,e.request||`(the request was never made)`),m(e.ok?`answered`:`replied`,e.response))})},_.append(e,r)}if(t.builtin||t.api&&t.models){let n=g(`Edit`);n.onclick=()=>$(e,t,u),_.append(n)}if(t.stored){let e=g(`Remove credential`);e.onclick=()=>void f(t),_.append(e)}return o(`div`,`border-b border-neutral-100`,o(`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]`,r,s,_),d)}))};await u()}function Q(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`,X.flatMap(e=>n.filter(t=>t.id===e))),r(`More providers`,n.filter(e=>e.builtin&&!X.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…`,Z))}function $(e,n,i){let s=document.createElement(`dialog`);s.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let c=document.createElement(`select`);c.className=`${h} select`,n||Q(c,e);let l=k(),u=k(),d=k(),f=document.createElement(`select`);f.className=`${h} select`,f.append(...ae.map(([e,t])=>new Option(e,t)));let p=r(``,4);p.placeholder=`model-id
4
- another-model-id`;let m=document.createElement(`input`);m.type=`checkbox`;let _=document.createElement(`select`);_.className=`${h} select`;let v=o(`div`,`flex flex-col gap-4`),y=o(`span`,`text-[11.5px] text-red-600`,``),b=g(`Cancel`),x=g(n?`Save`:`Add`,!0);x.type=`submit`;let S=()=>n??e.find(e=>e.id===c.value),C=()=>{let e=S(),t=e?!e.builtin:c.value===Z;l.value=e?.id??``,l.disabled=n!==void 0,u.value=e?.name??``,d.value=e?.endpoint??``,f.value=e?.api??`openai-completions`,p.value=e?.models?.map(e=>e.id).join(`
5
- `)??``;let r=e?.models?.map(e=>e.reasoning)??[];m.checked=r.length?r.every(Boolean):!e,m.indeterminate=r.some(Boolean)&&!r.every(Boolean);let i=[];e?.configured&&i.push(new Option(`Keep current authentication`,``));let a=e?.methods??[{type:`api_key`,name:`API key`}];for(let t of a.filter(t=>e?.builtin!==!1||t.type===`api_key`))i.push(new Option(t.name,t.type));_.replaceChildren(...i);let s=[];n||s.push(A(`Provider`,c)),t?s.push(A(`Provider ID`,l),A(`Display name`,u),A(`Endpoint`,d),A(`API format`,f),A(`Models`,p),A(`Model capabilities`,o(`label`,`flex items-center gap-2 text-[12.5px] text-neutral-600`,m,o(`span`,``,`Reasoning`)))):(d.placeholder=`Provider default`,s.push(A(`Endpoint`,d))),s.push(A(`Authentication`,_)),v.replaceChildren(...s)};c.onchange=C,C();let w=o(`form`,`flex flex-col gap-4 px-4 py-3`,v,o(`div`,`flex items-center justify-end gap-2`,y,b,x)),T=!1;b.onclick=()=>{T||s.close()},s.oncancel=e=>{T&&e.preventDefault()},w.onsubmit=e=>{if(e.preventDefault(),T)return;y.textContent=``;let n=S(),r=(n?!n.builtin:c.value===Z)?{kind:`custom`,id:l.value.trim(),...u.value.trim()?{name:u.value.trim()}:{},endpoint:d.value.trim(),api:f.value,models:[...new Set(p.value.split(`
6
- `).map(e=>e.trim()).filter(Boolean))].map(e=>({id:e,reasoning:m.indeterminate?n?.models?.find(t=>t.id===e)?.reasoning??m.checked:m.checked}))}:{kind:`builtin`,id:n.id,...d.value.trim()?{endpoint:d.value.trim()}:{}},o=_.value||null;T=!0,x.disabled=!0,b.disabled=!0,(async()=>{try{let e=await a(`/api/providers/setup`,{setup:r,authType:o});if(!e.ok){y.textContent=await t(e,`Could not configure provider`);return}if(s.close(),e.status===202){let t=_.selectedOptions[0]?.textContent??`Authentication`;Y(await e.json(),r.id,t,()=>void i())}else await i()}catch(e){y.textContent=`Could not configure provider: ${String(e)}`}finally{T=!1,x.disabled=!1,b.disabled=!1}})()},s.append(o(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,n?`Edit ${n.name}`:`Add provider`),w),s.onclose=()=>s.remove(),document.body.append(s),s.showModal(),(n?d:c).focus()}var se=[[`models`,`Models`],[`files`,`Agent`],[`channels`,`Channels`],[`instance`,`Instance`],[`security`,`Security`]],ce=e=>se.some(([t])=>t===e),le=`pier.settingsTopic`;function ue(e){return[/\bEdg\//.test(e)?`Edge`:/\b(Firefox|Chrome|Safari)\/[\d.]+/.exec(e)?.[1],/\(([^;)]+)/.exec(e)?.[1]?.trim()].filter(Boolean).join(` · `)||e||`unknown client`}function de(n,r,i){let c=localStorage.getItem(le)??void 0,l=ce(c)?c:`models`,p=o(`header`,`flex h-10 flex-none items-center gap-3 border-b border-neutral-200 bg-white px-4 max-md:hidden`,o(`span`,`font-medium`,`Settings`)),m=o(`div`,`tabstrip bg-white`);function h(){m.replaceChildren(...se.map(([e,t])=>u(t,e===l,()=>i(e))))}let _=k();_.placeholder=`https://pier.example.com`,_.autocomplete=`off`;let v=o(`span`,`text-[11.5px]`,``),y=g(`Save`,!0);async function b(){O(v,`saving`,`saving…`);let e=await a(`/api/settings`,{publicUrl:_.value},`PUT`);if(!e.ok)return O(v,`failed`,await t(e,`Could not save`));let{publicUrl:n}=await e.json();_.value=n,O(v,`saved`,n?`Saved — boards link as ${n}/p/<slug>-<token>/`:`Cleared.`)}y.onclick=()=>void b(),_.onkeydown=e=>{e.key===`Enter`&&b()};let C=f(`Public URL`,`Where this Pier is reached from outside — the proxy's address, not the port it listens on.`,A(`Base URL`,_,{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.`}),o(`div`,`flex items-center gap-3`,y,v)),w=k(``,`password`),T=k(``,`password`),E=k(``,`password`);for(let e of[w,T,E])e.autocomplete=`off`;let j=o(`span`,`text-[11.5px]`,``),M=g(`Change password`,!0);async function N(){if(T.value!==E.value)return O(j,`failed`,`The two new passwords differ.`);O(j,`saving`,`changing…`);let e=await a(`/api/password`,{current:w.value,next:T.value});if(!e.ok)return O(j,`failed`,await t(e,`Could not change the password`));for(let e of[w,T,E])e.value=``;O(j,`saved`,`Changed. Sign in again with the new password.`),location.href=`/login`}M.onclick=()=>void N(),E.onkeydown=e=>{e.key===`Enter`&&N()};let P=f(`Password`,`One shared password guards every page and API route. Changing it signs out every signed-in browser, this one included.`,A(`Current password`,w),A(`New password`,T,{hint:`At least 10 characters.`}),A(`Repeat new password`,E),o(`div`,`flex items-center gap-3`,M,j)),F=g(`Reload`,!0),I=o(`span`,`text-[11.5px]`,``);F.onclick=()=>{F.disabled=!0,O(I,`saving`,`reloading…`),(async()=>{let e=await a(`/api/reload`,{});if(F.disabled=!1,!e.ok)return O(I,`failed`,await t(e,`Could not reload`));let{recycled:n,busy:r}=await e.json(),i=n?`Recycled ${n} session(s).`:`No idle session needed it.`,o=r?` ${r} still mid-turn — they take it when the turn ends.`:``;O(I,r?`idle`:`saved`,i+o)})()};let ee=f(`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.`,o(`div`,`flex items-center gap-3`,F,I)),L=o(`div`,`flex flex-col gap-2`),R=o(`span`,`text-[11.5px]`,``);async function z(e,n){O(R,`saving`,`signing out…`);try{let r=await a(e,{});if(r.ok)return!0;O(R,`failed`,await t(r,n))}catch(e){O(R,`failed`,`${n}: ${String(e)}`)}return!1}let B=g(`Sign out`);B.onclick=()=>{B.disabled=!0,z(`/logout`,`Could not sign out`).then(e=>{e?location.href=`/login`:B.disabled=!1})};function V(t){L.replaceChildren(...t.map(t=>{let n=g(t.current?`This browser`:`Sign out`);n.disabled=t.current,n.onclick=()=>{n.disabled=!0,z(`/api/devices/${encodeURIComponent(t.id)}/signout`,`Could not sign it out`).then(e=>{if(!e)return void(n.disabled=!1);O(R,`saved`,`Signed out.`),H()})};let r=o(`div`,`flex min-w-0 flex-col`,o(`span`,`truncate text-[12.5px] text-neutral-700`,ue(t.agent)));return r.title=t.agent,r.append(o(`span`,`truncate text-[11.5px] text-neutral-400`,`${t.ip} · seen ${e(t.seenAt)} · signed in ${e(t.createdAt)}`)),o(`div`,`flex items-center justify-between gap-3 rounded-lg border border-neutral-200 px-3 py-2`,r,n)}))}async function H(){let e=await d(`/api/devices`,`Could not load signed-in devices`);if(!e.ok){L.replaceChildren(D(e.error));return}V(e.value)}let te=f(`Signed-in devices`,`One row per browser holding a session. Signing one out invalidates its cookie immediately; sessions expire on their own 7 days after last use.`,L,o(`div`,`flex items-center gap-3`,B,R)),U=o(`div`,`mx-auto flex max-w-2xl flex-col gap-6`,C,S(),ee),W=e=>o(`div`,`hidden min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,o(`div`,`px-4 py-5`,e)),re=ie(),K=o(`div`,`mx-auto flex w-full min-w-0 max-w-3xl flex-col rounded-xl border border-neutral-200 bg-white shadow-xs`),q=o(`section`,`hidden min-h-0 flex-1 flex-col`),J=ne(q),Y=o(`section`,`hidden min-h-0 flex-1 flex-col`),X=G(Y,r);function ae(){(async()=>{let e=await d(`/api/settings`,`Could not load settings`);if(!e.ok)return O(v,`failed`,e.error);_.value=e.value.publicUrl,v.textContent=``})()}let Z=o(`div`,`mx-auto flex max-w-2xl flex-col gap-6`),Q=e=>Z.replaceChildren(e,P,te);async function $(){j.textContent=``,R.textContent=``,H();let e=await d(`/api/secrets`,`Could not load key status`);if(!e.ok){Q(D(e.error));return}de(e.value)}function de(e,n){let r=e.state===`locked`,i=o(`span`,`text-[11.5px]`,``);n&&O(i,`saved`,n);let s=o(`div`,`flex items-center gap-2`,x(e.state,r?`bg-red-50 text-red-700 ring-red-200`:`bg-emerald-50 text-emerald-700 ring-emerald-200`),o(`span`,`text-[12.5px] text-neutral-600`,r?`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.`)),c=o(`a`,`text-indigo-600 hover:underline`,`vt`);c.href=`https://github.com/timqi/vt`,c.target=`_blank`,c.rel=`noreferrer`;let l=[s,o(`p`,`text-[12px] leading-snug text-neutral-500`,c,` 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(r){l.push(o(`p`,`text-[12.5px] leading-snug text-red-600`,e.reason??`No reason reported.`));let n=g(`Unlock`,!0);n.onclick=()=>{O(i,`saving`,`unlocking… (vt mode waits on your approval)`),(async()=>{let e=await a(`/api/secrets/unlock`,{});if(!e.ok)return O(i,`failed`,await t(e,`Could not unlock`));de(await e.json(),`Unlocked — channels are starting.`)})()},l.push(o(`div`,`flex items-center gap-3`,n,i))}else{let n=async(e,n,r)=>{if(!window.confirm(n))return;O(i,`saving`,e===`vt`?`rotating… (vt asks for an approval)`:`rotating…`);let o=await a(`/api/secrets/rotate`,{mode:e});if(!o.ok)return O(i,`failed`,await t(o,`Could not rotate`));de(await o.json(),r)},r=e.mode??`file`,s=g(`Rotate key`,!0);s.onclick=()=>void n(r,`Generate a new master key? Stored credentials stay valid; the old key stops working.`,`Rotated.`);let c=r===`vt`?`file`:`vt`,u=g(c===`vt`?`Switch to vt://`:`Switch to file`);u.onclick=()=>void n(c,c===`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.`,c===`vt`?`Switched to vt:// mode.`:`Switched to file mode.`),l.push(o(`div`,`flex items-center gap-3`,s,u,i))}if(r||e.mode===`vt`){let e=o(`pre`,`hidden overflow-x-auto rounded-lg bg-neutral-50 p-3 text-[11.5px] leading-snug text-neutral-700`),t=g(`vt doctor`);t.onclick=()=>{t.disabled=!0,e.classList.remove(`hidden`),e.textContent=`running vt doctor…`,(async()=>{let n=await d(`/api/secrets/doctor`,`Could not run vt doctor`);e.textContent=n.ok?n.value.report:n.error,t.disabled=!1})()},l.push(o(`div`,`flex items-center gap-3`,t),e)}Q(f(`Master key`,`Seals every credential Pier stores (channel tokens, API keys). Rotating rewraps the key file; no stored data is rewritten.`,...l))}let fe=W(U),pe=W(o(`div`,`flex flex-col gap-6`,K,re.el)),me=W(Z),he=[[`instance`,fe,ae],[`models`,pe,()=>{oe(K),re.load()}],[`security`,me,()=>void $()]];n.append(p,m,fe,pe,q,Y,me);function ge(e){ce(e)&&(l=e),localStorage.setItem(le,l),h();for(let[e,t,n]of he){let r=e===l;t.classList.toggle(`hidden`,!r),r&&n()}l===`channels`?J.show():J.hide(),l===`files`?X.show():X.hide()}return s(n,ge)}export{de as createSettingsView};