@jmfederico/pi-web 1.202605.1

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -0
  3. package/dist/cli.js +256 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/client/assets/CodeViewer-DsXI9VCn.js +4 -0
  6. package/dist/client/assets/TerminalPanel-CpzJEFv1.js +47 -0
  7. package/dist/client/assets/index-Cbr8EG8h.js +687 -0
  8. package/dist/client/assets/vendor-editor-core-hulUn3GY.js +12 -0
  9. package/dist/client/assets/vendor-editor-languages-Cjllm-a8.js +26 -0
  10. package/dist/client/assets/vendor-editor-legacy-B4QLsWF8.js +1 -0
  11. package/dist/client/assets/vendor-terminal-DDGTF8rc.css +1 -0
  12. package/dist/client/assets/vendor-terminal-DjQ08hXu.js +16 -0
  13. package/dist/client/index.html +16 -0
  14. package/dist/config.js +92 -0
  15. package/dist/config.js.map +1 -0
  16. package/dist/server/app.js +80 -0
  17. package/dist/server/app.js.map +1 -0
  18. package/dist/server/git/gitService.js +118 -0
  19. package/dist/server/git/gitService.js.map +1 -0
  20. package/dist/server/gitRoutes.js +23 -0
  21. package/dist/server/gitRoutes.js.map +1 -0
  22. package/dist/server/index.js +7 -0
  23. package/dist/server/index.js.map +1 -0
  24. package/dist/server/projects/directorySuggestions.js +37 -0
  25. package/dist/server/projects/directorySuggestions.js.map +1 -0
  26. package/dist/server/projects/projectService.js +31 -0
  27. package/dist/server/projects/projectService.js.map +1 -0
  28. package/dist/server/realtime/sessionEventHub.js +36 -0
  29. package/dist/server/realtime/sessionEventHub.js.map +1 -0
  30. package/dist/server/sessiond/config.js +9 -0
  31. package/dist/server/sessiond/config.js.map +1 -0
  32. package/dist/server/sessiond/sessionDaemonClient.js +65 -0
  33. package/dist/server/sessiond/sessionDaemonClient.js.map +1 -0
  34. package/dist/server/sessiond/sessionProxyRoutes.js +63 -0
  35. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -0
  36. package/dist/server/sessiond.js +45 -0
  37. package/dist/server/sessiond.js.map +1 -0
  38. package/dist/server/sessions/builtinCommands.js +27 -0
  39. package/dist/server/sessions/builtinCommands.js.map +1 -0
  40. package/dist/server/sessions/piSessionService.js +517 -0
  41. package/dist/server/sessions/piSessionService.js.map +1 -0
  42. package/dist/server/sessions/sessionArchiveStore.js +68 -0
  43. package/dist/server/sessions/sessionArchiveStore.js.map +1 -0
  44. package/dist/server/sessions/sessionCommandService.js +134 -0
  45. package/dist/server/sessions/sessionCommandService.js.map +1 -0
  46. package/dist/server/sessions/sessionNameGenerator.js +68 -0
  47. package/dist/server/sessions/sessionNameGenerator.js.map +1 -0
  48. package/dist/server/sessions/sessionRoutes.js +116 -0
  49. package/dist/server/sessions/sessionRoutes.js.map +1 -0
  50. package/dist/server/sessions/sessionRuntimeStore.js +2 -0
  51. package/dist/server/sessions/sessionRuntimeStore.js.map +1 -0
  52. package/dist/server/storage/projectStore.js +88 -0
  53. package/dist/server/storage/projectStore.js.map +1 -0
  54. package/dist/server/terminalProxyRoutes.js +70 -0
  55. package/dist/server/terminalProxyRoutes.js.map +1 -0
  56. package/dist/server/terminals/terminalRoutes.js +70 -0
  57. package/dist/server/terminals/terminalRoutes.js.map +1 -0
  58. package/dist/server/terminals/terminalService.js +115 -0
  59. package/dist/server/terminals/terminalService.js.map +1 -0
  60. package/dist/server/types.js +2 -0
  61. package/dist/server/types.js.map +1 -0
  62. package/dist/server/workspaceExplorerRoutes.js +24 -0
  63. package/dist/server/workspaceExplorerRoutes.js.map +1 -0
  64. package/dist/server/workspaces/fileContentService.js +50 -0
  65. package/dist/server/workspaces/fileContentService.js.map +1 -0
  66. package/dist/server/workspaces/fileSuggestions.js +84 -0
  67. package/dist/server/workspaces/fileSuggestions.js.map +1 -0
  68. package/dist/server/workspaces/fileTreeService.js +26 -0
  69. package/dist/server/workspaces/fileTreeService.js.map +1 -0
  70. package/dist/server/workspaces/gitWorktreeDiscovery.js +33 -0
  71. package/dist/server/workspaces/gitWorktreeDiscovery.js.map +1 -0
  72. package/dist/server/workspaces/pathSafety.js +38 -0
  73. package/dist/server/workspaces/pathSafety.js.map +1 -0
  74. package/dist/server/workspaces/workspaceContext.js +8 -0
  75. package/dist/server/workspaces/workspaceContext.js.map +1 -0
  76. package/dist/server/workspaces/workspaceService.js +39 -0
  77. package/dist/server/workspaces/workspaceService.js.map +1 -0
  78. package/dist/shared/apiTypes.js +2 -0
  79. package/dist/shared/apiTypes.js.map +1 -0
  80. package/extensions/pi-web.ts +144 -0
  81. package/install.sh +5 -0
  82. package/package.json +107 -0
@@ -0,0 +1,687 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-DsXI9VCn.js","assets/vendor-editor-core-hulUn3GY.js","assets/vendor-editor-languages-Cjllm-a8.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-CpzJEFv1.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ (function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&i(n)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();const ze=globalThis,ht=ze.ShadowRoot&&(ze.ShadyCSS===void 0||ze.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ut=Symbol(),Dt=new WeakMap;let ms=class{constructor(e,s,i){if(this._$cssResult$=!0,i!==ut)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=s}get styleSheet(){let e=this.o;const s=this.t;if(ht&&e===void 0){const i=s!==void 0&&s.length===1;i&&(e=Dt.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Dt.set(s,e))}return e}toString(){return this.cssText}};const Qs=t=>new ms(typeof t=="string"?t:t+"",void 0,ut),B=(t,...e)=>{const s=t.length===1?t[0]:e.reduce((i,r,o)=>i+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+t[o+1],t[0]);return new ms(s,t,ut)},Js=(t,e)=>{if(ht)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const i=document.createElement("style"),r=ze.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=s.cssText,t.appendChild(i)}},jt=ht?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const i of e.cssRules)s+=i.cssText;return Qs(s)})(t):t;const{is:Xs,defineProperty:Ys,getOwnPropertyDescriptor:ei,getOwnPropertyNames:ti,getOwnPropertySymbols:si,getPrototypeOf:ii}=Object,Ve=globalThis,Ot=Ve.trustedTypes,ri=Ot?Ot.emptyScript:"",oi=Ve.reactiveElementPolyfillSupport,$e=(t,e)=>t,Ue={toAttribute(t,e){switch(e){case Boolean:t=t?ri:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let s=t;switch(e){case Boolean:s=t!==null;break;case Number:s=t===null?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch{s=null}}return s}},ft=(t,e)=>!Xs(t,e),zt={attribute:!0,type:String,converter:Ue,reflect:!1,useDefault:!1,hasChanged:ft};Symbol.metadata??=Symbol("metadata"),Ve.litPropertyMetadata??=new WeakMap;let pe=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=zt){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(e,s),!s.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,s);r!==void 0&&Ys(this.prototype,e,r)}}static getPropertyDescriptor(e,s,i){const{get:r,set:o}=ei(this.prototype,e)??{get(){return this[s]},set(n){this[s]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(e,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??zt}static _$Ei(){if(this.hasOwnProperty($e("elementProperties")))return;const e=ii(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty($e("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty($e("properties"))){const s=this.properties,i=[...ti(s),...si(s)];for(const r of i)this.createProperty(r,s[r])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[i,r]of s)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[s,i]of this.elementProperties){const r=this._$Eu(s,i);r!==void 0&&this._$Eh.set(r,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)s.unshift(jt(r))}else e!==void 0&&s.push(jt(e));return s}static _$Eu(e,s){const i=s.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Js(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,s,i){this._$AK(e,i)}_$ET(e,s){const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const o=(i.converter?.toAttribute!==void 0?i.converter:Ue).toAttribute(s,i.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,s){const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ue;this._$Em=r;const a=n.fromAttribute(s,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,s,i,r=!1,o){if(e!==void 0){const n=this.constructor;if(r===!1&&(o=this[e]),i??=n.getPropertyOptions(e),!((i.hasChanged??ft)(o,s)||i.useDefault&&i.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,s,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:i,reflect:r,wrapped:o},n){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,n??s??this[e]),o!==!0||n!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[r,o]of i){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(s)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(s)}willUpdate(e){}_$AE(e){this._$EO?.forEach(s=>s.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(s=>this._$ET(s,this[s])),this._$EM()}updated(e){}firstUpdated(e){}};pe.elementStyles=[],pe.shadowRootOptions={mode:"open"},pe[$e("elementProperties")]=new Map,pe[$e("finalized")]=new Map,oi?.({ReactiveElement:pe}),(Ve.reactiveElementVersions??=[]).push("2.1.2");const gt=globalThis,Lt=t=>t,Ne=gt.trustedTypes,Ut=Ne?Ne.createPolicy("lit-html",{createHTML:t=>t}):void 0,bs="$lit$",Y=`lit$${Math.random().toFixed(9).slice(2)}$`,xs="?"+Y,ni=`<${xs}>`,re=document,Pe=()=>re.createComment(""),Te=t=>t===null||typeof t!="object"&&typeof t!="function",mt=Array.isArray,ai=t=>mt(t)||typeof t?.[Symbol.iterator]=="function",st=`[
3
+ \f\r]`,we=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nt=/-->/g,qt=/>/g,te=RegExp(`>|${st}(?:([^\\s"'>=/]+)(${st}*=${st}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Wt=/'/g,Ft=/"/g,ys=/^(?:script|style|textarea|title)$/i,li=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),p=li(1),oe=Symbol.for("lit-noChange"),C=Symbol.for("lit-nothing"),Bt=new WeakMap,ie=re.createTreeWalker(re,129);function ws(t,e){if(!mt(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ut!==void 0?Ut.createHTML(e):e}const ci=(t,e)=>{const s=t.length-1,i=[];let r,o=e===2?"<svg>":e===3?"<math>":"",n=we;for(let a=0;a<s;a++){const c=t[a];let l,h,d=-1,f=0;for(;f<c.length&&(n.lastIndex=f,h=n.exec(c),h!==null);)f=n.lastIndex,n===we?h[1]==="!--"?n=Nt:h[1]!==void 0?n=qt:h[2]!==void 0?(ys.test(h[2])&&(r=RegExp("</"+h[2],"g")),n=te):h[3]!==void 0&&(n=te):n===te?h[0]===">"?(n=r??we,d=-1):h[1]===void 0?d=-2:(d=n.lastIndex-h[2].length,l=h[1],n=h[3]===void 0?te:h[3]==='"'?Ft:Wt):n===Ft||n===Wt?n=te:n===Nt||n===qt?n=we:(n=te,r=void 0);const m=n===te&&t[a+1].startsWith("/>")?" ":"";o+=n===we?c+ni:d>=0?(i.push(l),c.slice(0,d)+bs+c.slice(d)+Y+m):c+Y+(d===-2?a:m)}return[ws(t,o+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Ce{constructor({strings:e,_$litType$:s},i){let r;this.parts=[];let o=0,n=0;const a=e.length-1,c=this.parts,[l,h]=ci(e,s);if(this.el=Ce.createElement(l,i),ie.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ie.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(bs)){const f=h[n++],m=r.getAttribute(d).split(Y),x=/([.?@])?(.*)/.exec(f);c.push({type:1,index:o,name:x[2],strings:m,ctor:x[1]==="."?pi:x[1]==="?"?hi:x[1]==="@"?ui:Ze}),r.removeAttribute(d)}else d.startsWith(Y)&&(c.push({type:6,index:o}),r.removeAttribute(d));if(ys.test(r.tagName)){const d=r.textContent.split(Y),f=d.length-1;if(f>0){r.textContent=Ne?Ne.emptyScript:"";for(let m=0;m<f;m++)r.append(d[m],Pe()),ie.nextNode(),c.push({type:2,index:++o});r.append(d[f],Pe())}}}else if(r.nodeType===8)if(r.data===xs)c.push({type:2,index:o});else{let d=-1;for(;(d=r.data.indexOf(Y,d+1))!==-1;)c.push({type:7,index:o}),d+=Y.length-1}o++}}static createElement(e,s){const i=re.createElement("template");return i.innerHTML=e,i}}function he(t,e,s=t,i){if(e===oe)return e;let r=i!==void 0?s._$Co?.[i]:s._$Cl;const o=Te(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(t),r._$AT(t,s,i)),i!==void 0?(s._$Co??=[])[i]=r:s._$Cl=r),r!==void 0&&(e=he(t,r._$AS(t,e.values),r,i)),e}class di{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:i}=this._$AD,r=(e?.creationScope??re).importNode(s,!0);ie.currentNode=r;let o=ie.nextNode(),n=0,a=0,c=i[0];for(;c!==void 0;){if(n===c.index){let l;c.type===2?l=new Ee(o,o.nextSibling,this,e):c.type===1?l=new c.ctor(o,c.name,c.strings,this,e):c.type===6&&(l=new fi(o,this,e)),this._$AV.push(l),c=i[++a]}n!==c?.index&&(o=ie.nextNode(),n++)}return ie.currentNode=re,r}p(e){let s=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,s),s+=i.strings.length-2):i._$AI(e[s])),s++}}class Ee{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,i,r){this.type=2,this._$AH=C,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=i,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=he(this,e,s),Te(e)?e===C||e==null||e===""?(this._$AH!==C&&this._$AR(),this._$AH=C):e!==this._$AH&&e!==oe&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):ai(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==C&&Te(this._$AH)?this._$AA.nextSibling.data=e:this.T(re.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=Ce.createElement(ws(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(s);else{const o=new di(r,this),n=o.u(this.options);o.p(s),this.T(n),this._$AH=o}}_$AC(e){let s=Bt.get(e.strings);return s===void 0&&Bt.set(e.strings,s=new Ce(e)),s}k(e){mt(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let i,r=0;for(const o of e)r===s.length?s.push(i=new Ee(this.O(Pe()),this.O(Pe()),this,this.options)):i=s[r],i._$AI(o),r++;r<s.length&&(this._$AR(i&&i._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const i=Lt(e).nextSibling;Lt(e).remove(),e=i}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}let Ze=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,i,r,o){this.type=1,this._$AH=C,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=C}_$AI(e,s=this,i,r){const o=this.strings;let n=!1;if(o===void 0)e=he(this,e,s,0),n=!Te(e)||e!==this._$AH&&e!==oe,n&&(this._$AH=e);else{const a=e;let c,l;for(e=o[0],c=0;c<o.length-1;c++)l=he(this,a[i+c],s,c),l===oe&&(l=this._$AH[c]),n||=!Te(l)||l!==this._$AH[c],l===C?e=C:e!==C&&(e+=(l??"")+o[c+1]),this._$AH[c]=l}n&&!r&&this.j(e)}j(e){e===C?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},pi=class extends Ze{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===C?void 0:e}},hi=class extends Ze{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==C)}},ui=class extends Ze{constructor(e,s,i,r,o){super(e,s,i,r,o),this.type=5}_$AI(e,s=this){if((e=he(this,e,s,0)??C)===oe)return;const i=this._$AH,r=e===C&&i!==C||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,o=e!==C&&(i===C||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}};class fi{constructor(e,s,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){he(this,e)}}const gi=gt.litHtmlPolyfillSupport;gi?.(Ce,Ee),(gt.litHtmlVersions??=[]).push("3.3.2");const mi=(t,e,s)=>{const i=s?.renderBefore??e;let r=i._$litPart$;if(r===void 0){const o=s?.renderBefore??null;i._$litPart$=r=new Ee(e.insertBefore(Pe(),o),o,void 0,s??{})}return r._$AI(t),r};const bt=globalThis;let I=class extends pe{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=mi(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return oe}};I._$litElement$=!0,I.finalized=!0,bt.litElementHydrateSupport?.({LitElement:I});const bi=bt.litElementPolyfillSupport;bi?.({LitElement:I});(bt.litElementVersions??=[]).push("4.2.2");const z=t=>(e,s)=>{s!==void 0?s.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};const xi={attribute:!0,type:String,converter:Ue,reflect:!1,hasChanged:ft},yi=(t=xi,e,s)=>{const{kind:i,metadata:r}=s;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),i==="setter"&&((t=Object.create(t)).wrapped=!0),o.set(s.name,t),i==="accessor"){const{name:n}=s;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(n,c,t,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,t,a),a}}}if(i==="setter"){const{name:n}=s;return function(a){const c=this[n];e.call(this,a),this.requestUpdate(n,c,t,!0,a)}}throw Error("Unsupported decorator location: "+i)};function u(t){return(e,s)=>typeof s=="object"?yi(t,e,s):((i,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,i),n?Object.getOwnPropertyDescriptor(r,o):void 0})(t,e,s)}function $(t){return u({...t,state:!0,attribute:!1})}const wi=(t,e,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(t,e,s),s);function me(t,e){return(s,i,r)=>{const o=n=>n.renderRoot?.querySelector(t)??null;return wi(s,i,{get(){return o(this)}})}}function ki(){return{projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},commandDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""}}async function k(t,e,s){const i=new Headers(s?.headers);s?.body!==void 0&&i.set("content-type","application/json");const r=await fetch(t,{...s,headers:i});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Si(n)??r.statusText)}const o=await r.json();return e(o)}function Si(t){if(vi(t))return typeof t.error=="string"?t.error:void 0}function vi(t){return typeof t=="object"&&t!==null}function $i(t){return typeof t=="object"&&t!==null}function S(t){if(!$i(t))throw new Error("Expected object response");return t}function g(t,e){const s=t[e];if(typeof s!="string")throw new Error(`Expected string field: ${e}`);return s}function M(t,e){const s=t[e];if(s!==void 0){if(typeof s!="string")throw new Error(`Expected optional string field: ${e}`);return s}}function N(t,e){const s=t[e];if(typeof s!="number")throw new Error(`Expected number field: ${e}`);return s}function O(t,e){const s=t[e];if(typeof s!="boolean")throw new Error(`Expected boolean field: ${e}`);return s}function K(t){return e=>{if(!Array.isArray(e))throw new Error("Expected array response");return e.map(t)}}function Pi(t){if(!Array.isArray(t))throw new Error("Expected array response");return t}function Ti(t){if(Array.isArray(t))return{messages:t,start:0,total:t.length};const e=S(t);return{messages:Pi(e.messages),start:N(e,"start"),total:N(e,"total")}}function Ht(t){const e=S(t);return{id:g(e,"id"),name:g(e,"name"),path:g(e,"path"),createdAt:g(e,"createdAt")}}function Ci(t){const e=S(t),s=M(e,"branch");return{id:g(e,"id"),projectId:g(e,"projectId"),path:g(e,"path"),label:g(e,"label"),...s===void 0?{}:{branch:s},isMain:O(e,"isMain"),isGitRepo:O(e,"isGitRepo"),isGitWorktree:O(e,"isGitWorktree")}}function ot(t){const e=S(t),s=M(e,"name"),i=M(e,"archivedAt");return{id:g(e,"id"),path:g(e,"path"),cwd:g(e,"cwd"),...s===void 0?{}:{name:s},created:g(e,"created"),modified:g(e,"modified"),messageCount:N(e,"messageCount"),firstMessage:g(e,"firstMessage"),...e.archived===!0?{archived:!0}:{},...i===void 0?{}:{archivedAt:i}}}function Ai(t){const e=S(t);return{sessionId:g(e,"sessionId"),isStreaming:O(e,"isStreaming"),isCompacting:O(e,"isCompacting"),isBashRunning:O(e,"isBashRunning"),pendingMessageCount:N(e,"pendingMessageCount"),tokens:_i(e.tokens),cost:N(e,"cost"),...Ei(e.model),...Ii(e.contextUsage),...A("thinkingLevel",M(e,"thinkingLevel"))}}function _i(t){const e=S(t);return{input:N(e,"input"),output:N(e,"output"),cacheRead:N(e,"cacheRead"),cacheWrite:N(e,"cacheWrite"),total:N(e,"total")}}function Ei(t){if(t===void 0)return{};const e=S(t);return{model:{...A("provider",M(e,"provider")),...A("id",M(e,"id")),...A("name",M(e,"name")),...A("contextWindow",Ae(e,"contextWindow")),...A("reasoning",e.reasoning)}}}function Ii(t){if(t===void 0)return{};const e=S(t);return{contextUsage:{tokens:Qt(e,"tokens"),contextWindow:N(e,"contextWindow"),percent:Qt(e,"percent")}}}function Ri(t){const e=S(t),s=g(e,"source");if(s!=="extension"&&s!=="prompt"&&s!=="skill"&&s!=="builtin")throw new Error("Invalid command source");return{name:g(e,"name"),source:s,...A("description",M(e,"description"))}}function ks(t){const e=S(t),s=g(e,"kind");if(s!=="tracked"&&s!=="untracked"&&s!=="other")throw new Error("Invalid file kind");return{path:g(e,"path"),kind:s}}function Mi(t){const e=S(t);return{path:g(e,"path"),entries:K(Di)(e.entries),scannedAt:g(e,"scannedAt"),truncated:O(e,"truncated")}}function Di(t){const e=S(t),s=g(e,"type");if(s!=="file"&&s!=="directory"&&s!=="symlink")throw new Error("Invalid file tree entry type");return{name:g(e,"name"),path:g(e,"path"),type:s,...A("size",Ae(e,"size")),...A("modifiedAt",M(e,"modifiedAt"))}}function ji(t){const e=S(t),s=g(e,"encoding");if(s!=="utf8")throw new Error("Invalid file encoding");return{path:g(e,"path"),...A("language",M(e,"language")),encoding:s,size:N(e,"size"),modifiedAt:g(e,"modifiedAt"),content:g(e,"content"),truncated:O(e,"truncated"),binary:O(e,"binary")}}function Oi(t){const e=S(t);return{isGitRepo:O(e,"isGitRepo"),hash:g(e,"hash"),...A("branch",M(e,"branch")),...A("upstream",M(e,"upstream")),...A("ahead",Ae(e,"ahead")),...A("behind",Ae(e,"behind")),files:K(zi)(e.files)}}function zi(t){const e=S(t);return{path:g(e,"path"),...A("oldPath",M(e,"oldPath")),index:Gt(e.index),workingTree:Gt(e.workingTree)}}function Gt(t){switch(t){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return t;default:throw new Error("Invalid git file state")}}function Li(t){const e=S(t);return{...A("path",M(e,"path")),staged:O(e,"staged"),hash:g(e,"hash"),diff:g(e,"diff"),truncated:O(e,"truncated")}}function Kt(t){const e=S(t);return{id:g(e,"id"),cwd:g(e,"cwd"),name:g(e,"name"),createdAt:g(e,"createdAt"),exited:O(e,"exited"),...A("exitCode",Ae(e,"exitCode"))}}function Vt(t){const e=S(t),s=g(e,"type");if(s==="unsupported")return{type:s,message:g(e,"message")};if(s==="select")return{type:s,requestId:g(e,"requestId"),title:g(e,"title"),options:K(Ui)(e.options)};if(s==="done")return{type:s,...A("message",M(e,"message")),...Ni(e.session)};throw new Error("Invalid command result type")}function Ui(t){const e=S(t);return{value:g(e,"value"),label:g(e,"label"),...A("description",M(e,"description"))}}function Ni(t){return t===void 0?{}:{session:ot(t)}}function Zt(t){if(S(t).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Ss(t){if(S(t).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function qi(t){if(S(t).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Wi(t){if(S(t).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Fi(t){if(S(t).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function Bi(t){if(S(t).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Ae(t,e){const s=t[e];if(s!==void 0){if(typeof s!="number")throw new Error(`Expected optional number field: ${e}`);return s}}function Qt(t,e){const s=t[e];if(s===null)return null;if(typeof s!="number")throw new Error(`Expected number|null field: ${e}`);return s}function A(t,e){return e===void 0?{}:{[t]:e}}function Hi(t,e,s){const i=new URLSearchParams;s?.path!==void 0&&i.set("path",s.path),s?.staged===!0&&i.set("staged","true");const r=i.toString();return`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/diff${r?`?${r}`:""}`}function Gi(t,e){const s=new URLSearchParams;e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.before!==void 0&&s.set("before",String(e.before));const i=s.toString();return`/api/sessions/${t}/messages${i?`?${i}`:""}`}const Ki={projects:()=>k("/api/projects",K(Ht)),addProject:(t,e,s)=>k("/api/projects",Ht,{method:"POST",body:JSON.stringify({path:t,name:e,create:s})}),closeProject:t=>k(`/api/projects/${encodeURIComponent(t)}`,Ss,{method:"DELETE"}),projectDirectories:t=>k(`/api/project-directories?q=${encodeURIComponent(t)}`,K(ks))},Vi={workspaces:t=>k(`/api/projects/${t}/workspaces`,K(Ci)),workspaceTree:(t,e,s="")=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/tree?path=${encodeURIComponent(s)}`,Mi),workspaceFile:(t,e,s)=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/file?path=${encodeURIComponent(s)}`,ji)},Zi={sessions:t=>k(`/api/sessions?cwd=${encodeURIComponent(t)}`,K(ot)),startSession:t=>k("/api/sessions",ot,{method:"POST",body:JSON.stringify({cwd:t})}),messages:(t,e)=>k(Gi(t,e),Ti),status:t=>k(`/api/sessions/${t}/status`,Ai),commands:t=>k(`/api/sessions/${t}/commands`,K(Ri)),prompt:(t,e,s)=>k(`/api/sessions/${t}/prompt`,Zt,{method:"POST",body:JSON.stringify(s===void 0?{text:e}:{text:e,streamingBehavior:s})}),shell:(t,e)=>k(`/api/sessions/${t}/shell`,Zt,{method:"POST",body:JSON.stringify({text:e})}),runCommand:(t,e)=>k(`/api/sessions/${t}/commands/run`,Vt,{method:"POST",body:JSON.stringify({text:e})}),respondToCommand:(t,e,s)=>k(`/api/sessions/${t}/commands/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),abort:t=>k(`/api/sessions/${t}/abort`,qi,{method:"POST"}),stop:t=>k(`/api/sessions/${t}/stop`,Wi,{method:"POST"}),archive:t=>k(`/api/sessions/${t}/archive`,Fi,{method:"POST"}),restore:t=>k(`/api/sessions/${t}/restore`,Bi,{method:"POST"})},Qi={terminals:(t,e)=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,K(Kt)),startTerminal:(t,e,s)=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,Kt,{method:"POST",body:JSON.stringify(s??{})}),closeTerminal:(t,e,s)=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}`,Ss,{method:"DELETE"})},Ji={files:(t,e,s,i)=>k(`/api/files?cwd=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}${s!==void 0?`&kind=${encodeURIComponent(s)}`:""}${i!==void 0?`&mode=${encodeURIComponent(i)}`:""}`,K(ks))},Xi={gitStatus:(t,e)=>k(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/status`,Oi),gitDiff:(t,e,s)=>k(Hi(t,e,s),Li)},w={...Ki,...Vi,...Zi,...Qi,...Ji,...Xi};function Yi(t){return new WebSocket(`${xt()}/api/sessions/${t}/events`)}function er(){return new WebSocket(`${xt()}/api/sessions/events`)}function xa(t,e,s){return new WebSocket(`${xt()}/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}/socket`)}function xt(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function qe(t){return t.replaceAll(":",".")}function tr(t){const e=new URLSearchParams(window.location.search),s=`${t}--`,i={};for(const[r,o]of e.entries()){if(!r.startsWith(s))continue;const n=r.slice(s.length),a=i[n];a===void 0?i[n]=o:Array.isArray(a)?a.push(o):i[n]=[a,o]}return i}function Jt(t,e){const s=tr(t)[e];return Array.isArray(s)?s[0]:s===""?void 0:s}function nt(t,e,s,i){const r=new URL(window.location.href),o=`${t}--${e}`;if(r.searchParams.delete(o),s!=null&&s!=="")if(Array.isArray(s))for(const n of s)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(s));sr(r,i)}function sr(t,e){const s=`${t.pathname}${t.search}${t.hash}`,i=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==i&&(e?.replace===!0?window.history.replaceState({},"",t):window.history.pushState({},"",t))}const ir=qe("core:workspace.files");class rr{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}async refreshFiles(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await w.workspaceTree(e.id,s.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await w.workspaceTree(e.id,s.id,o)).entries})),this.setState({fileTree:i.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(i){this.setState({error:String(i)})}}async expandDir(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:or(this.getState().expandedDirs,e)});return}try{const r=await w.workspaceTree(s.id,i.id,e);this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),nt(ir,"file",e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{this.setState({selectedFileContent:await w.workspaceFile(s.id,i.id,e),error:""})}catch(r){this.setState({error:String(r)})}}}}function or(t,e){return Object.fromEntries(Object.entries(t).filter(([s])=>s!==e))}const Xt=qe("core:workspace.git");class nr{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await w.gitStatus(e.id,s.id);this.setState({gitStatus:i,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(i.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),nt(Xt,"diff",void 0,{replace:!0})))}catch(i){this.setState({error:String(i)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),nt(Xt,"diff",e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0))try{const[r,o]=await Promise.all([w.gitDiff(s.id,i.id,{path:e}),w.gitDiff(s.id,i.id,{path:e,staged:!0})]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const e=this.getState();(e.workspaceTool==="core:workspace.git"||e.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class ar{constructor(e,s,i){this.getState=e,this.setState=s,this.workspaces=i}async loadProjects(){this.setState({error:""});try{this.setState({projects:await w.projects()})}catch(e){this.setState({error:String(e)})}}async addProject(e,s){if(e.trim()!=="")try{const i=await w.addProject(e.trim(),void 0,s),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i)}catch(i){this.setState({error:String(i)})}}async closeProject(e){try{await w.closeProject(e);const s=this.getState();this.setState({projects:s.projects.filter(i=>i.id!==e)}),s.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(s){this.setState({error:String(s)})}}}function ke(t){return t.flatMap(yt).filter(e=>e.parts.length>0)}function G(t,e){return{role:t,parts:[{type:"text",text:e}]}}function Re(t,e){const s=ur(e);return s===void 0?t:{...t,meta:s}}function lr(t,e,s){if(s==="")return t;const i=t.at(-1),r=i?.parts.at(-1);return i?.role===e&&r?.type==="text"?[...t.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...r,text:r.text+s}]}]:i?.role===e?[...t.slice(0,-1),{...i,parts:[...i.parts,{type:"text",text:s}]}]:[...t,G(e,s)]}function cr(t,e){if(e==="")return t;const s=t.at(-1),i=s?.parts.at(-1);return s?.role==="assistant"&&i?.type==="thinking"?[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:i.text+e}]}]:s?.role==="assistant"?[...t.slice(0,-1),{...s,parts:[...s.parts,{type:"thinking",text:e}]}]:[...t,{role:"assistant",parts:[{type:"thinking",text:e}]}]}function yt(t){if(E(t,"role")==="bashExecution")return[Re(mr(t),t)];const e=br(E(t,"role")),s=xr(ne(t,"content"),t),i=e==="user"?dr(s):void 0;if(i!==void 0)return i.map(n=>Re(n,t));const r=hr(t);if(e==="tool")return[Re({role:e,parts:s,...r===void 0?{}:{source:r}},t)];const o=s.filter(n=>n.type!=="empty");return o.length>0?[Re({role:e,parts:o,...r===void 0?{}:{source:r}},t)]:[]}function dr(t){if(t.length!==1||t[0]?.type!=="text")return;const e=pr(t[0].text);if(e!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:e.name,location:e.location,content:e.content}]},...e.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:e.userMessage}]}]]}function pr(t){const e=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(t);if(e===null)return;const s=e[4]?.trim();return{name:e[1]??"skill",location:e[2]??"",content:e[3]??"",...s===void 0||s===""?{}:{userMessage:s}}}function hr(t){const e=E(t,"source");if(e==="compaction"||e==="branch_summary")return e}function ur(t){const e=fr(ne(t,"timestamp")),s=gr(t);if(!(e===void 0&&s===void 0))return{...e===void 0?{}:{timestamp:e},...s===void 0?{}:{model:s}}}function fr(t){if(typeof t=="number"&&Number.isFinite(t))return new Date(t).toISOString();if(typeof t!="string"||t==="")return;const e=Date.parse(t);return Number.isFinite(e)?new Date(e).toISOString():void 0}function gr(t){if(E(t,"role")!=="assistant")return;const e=E(t,"provider"),s=E(t,"model"),i=E(t,"responseModel");if(!((e===void 0||e==="")&&(s===void 0||s==="")&&(i===void 0||i==="")))return{...e===void 0||e===""?{}:{provider:e},...s===void 0||s===""?{}:{id:s},...i===void 0||i===""?{}:{responseId:i}}}function mr(t){const e=E(t,"command")??"",s=Le(t,"excludeFromContext")===!0?["excluded from context","",`$ ${e}`]:[`$ ${e}`],i=ne(t,"output");i!=null&&s.push("",We(i));const r=ne(t,"exitCode");r!=null&&s.push("",`exit ${We(r)}`),Le(t,"cancelled")===!0&&s.push("","cancelled"),Le(t,"truncated")===!0&&s.push("","output truncated");const o=E(t,"fullOutputPath");return o!==void 0&&o!==""&&s.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:s.join(`
5
+ `)}]}}function br(t){return t==="assistant"?"assistant":t==="user"?"user":t==="toolResult"?"tool":"system"}function xr(t,e){return typeof t=="string"?t!==""?[{type:"text",text:t}]:[]:Array.isArray(t)?t.flatMap(s=>{const i=E(s,"type"),r=E(s,"text");if(i==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(i==="thinking"){const o=E(s,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}return i==="toolCall"?[{type:"toolCall",toolName:E(s,"name")??"tool",summary:vs(ne(s,"arguments"))}]:i==="image"?[{type:"text",text:"[image]"}]:Yt(s)}).map(s=>s.type==="text"&&E(e,"role")==="toolResult"?{type:"toolResult",toolName:E(e,"toolName")??"tool",text:s.text,isError:Le(e,"isError")===!0}:s):Yt(t)}function Yt(t){return t==null?[]:typeof t=="object"?[{type:"text",text:vs(t)}]:[{type:"text",text:We(t)}]}function vs(t){if(!$s(t))return We(t);const e=E(t,"command");if(e!==void 0)return e;const s=E(t,"path");if(s!==void 0)return s;if(typeof t.oldText=="string"&&typeof t.newText=="string")return"edit text replacement";const i=t.edits;return Array.isArray(i)?`${String(i.length)} edit${i.length===1?"":"s"}`:Object.entries(t).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${yr(n)}`).join(" · ")}function yr(t){return typeof t=="string"?t.length>80?`${t.slice(0,77)}…`:t:typeof t=="number"||typeof t=="boolean"?String(t):Array.isArray(t)?`${String(t.length)} item${t.length===1?"":"s"}`:typeof t=="object"&&t!==null?"object":""}function $s(t){return typeof t=="object"&&t!==null}function ne(t,e){return $s(t)?t[e]:void 0}function E(t,e){const s=ne(t,e);return typeof s=="string"?s:void 0}function Le(t,e){const s=ne(t,e);return typeof s=="boolean"?s:void 0}function We(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):""}const wr="pi-web:chat-history:",kr=1800*1e3;function es(t){try{const e=sessionStorage.getItem(at(t));if(e===null||e==="")return;const s=JSON.parse(e);if(!Pr(s))return;if(Date.now()-s.savedAt>kr){sessionStorage.removeItem(at(t));return}return{messages:s.messages,start:s.start,total:s.total}}catch{return}}function Sr(t,e){try{sessionStorage.setItem(at(t),JSON.stringify({...e,savedAt:Date.now()}))}catch{}}function vr(t,e){if(t===void 0||t.total>e.total)return e;const s=Math.min(t.start,e.start),i=Math.max(t.start+t.messages.length,e.start+e.messages.length),r=new Array(i-s);return ts(r,s,t),ts(r,s,e),$r(r)?e:{start:s,total:e.total,messages:r}}function $r(t){for(let e=0;e<t.length;e+=1)if(!(e in t)||t[e]===void 0)return!0;return!1}function ts(t,e,s){s.messages.forEach((i,r)=>{t[s.start-e+r]=i})}function at(t){return`${wr}${t}`}function Pr(t){return typeof t=="object"&&t!==null&&"messages"in t&&"start"in t&&"total"in t&&"savedAt"in t&&Array.isArray(t.messages)&&typeof t.start=="number"&&typeof t.total=="number"&&typeof t.savedAt=="number"}function Tr(t,e){return G("bash",`${e===!0?`excluded from context
6
+
7
+ `:""}$ ${t}`)}function Cr(t,e){const s=t.at(-1),i=s?.parts.at(-1);if(s?.role!=="bash"||i?.type!=="text")return[...t,G("bash",e)];const r=_r(i.text)?"":`
8
+
9
+ `;return[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:i.text+r+e}]}]}function Ar(t,e){const s=t.at(-1),i=s?.parts.at(-1);if(s?.role!=="bash"||i?.type!=="text")return t;const r=[];return!i.text.includes(`
10
+
11
+ `)&&(e.output===void 0||e.output==="")&&r.push("(no output)"),e.isError===!0&&r.push(e.output??"Bash command failed"),e.exitCode!=null&&r.push(`exit ${String(e.exitCode)}`),e.cancelled===!0&&r.push("cancelled"),e.truncated===!0&&r.push("output truncated"),e.fullOutputPath!==void 0&&e.fullOutputPath!==""&&r.push(`full output: ${e.fullOutputPath}`),r.length===0?t:[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:`${i.text}
12
+
13
+ ${r.join(`
14
+ `)}`}]}]}function _r(t){const e=t.lastIndexOf(`
15
+
16
+ `),s=t.lastIndexOf("$ ");return e>s}function Er(t,e){if(e.type==="message.append")return it(t,e.message);if(e.type==="assistant.delta")return lr(t,"assistant",e.text);if(e.type==="assistant.thinking.delta")return cr(t,e.text);if(e.type==="tool.start")return it(t,{role:"assistant",content:[{type:"toolCall",name:e.toolName,arguments:e.args}]});if(e.type==="tool.end")return it(t,{role:"toolResult",toolName:e.toolName,content:e.content??[{type:"text",text:e.text}],isError:e.isError});if(e.type==="shell.start")return[...t,Tr(e.command,e.excludeFromContext)];if(e.type==="shell.chunk")return Cr(t,e.chunk);if(e.type==="shell.end")return Ar(t,e);if(e.type==="command.output")return[...t,G(e.level==="error"?"system":"tool",e.message)];if(e.type==="session.error")return[...t,G("system",e.message)];if(e.type==="message.end")return e.message===void 0?void 0:Ir(t,e.message)}function Ir(t,e){const s=yt(e)[0];return s===void 0?void 0:t.at(-1)?.role!==s.role?[...t,s]:[...t.slice(0,-1),s]}function it(t,e){return yt(e).reduce(Rr,t)}function Rr(t,e){const s=t.at(-1);return s?.role===e.role?[...t.slice(0,-1),{...s,parts:[...s.parts,...e.parts]}]:[...t,e]}function Ps(t){const e=t.trimStart();return e.startsWith("!")?{kind:"shell",excludeFromContext:e.startsWith("!!")}:Ts(t).startsWith("/")?{kind:"command"}:Dr(t)?{kind:"file"}:{kind:"normal"}}function Mr(t){return Ps(t).kind==="shell"}function Ts(t){const e=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
17
+ `))+1;return t.slice(e)}function Dr(t){const e=Ts(t);if(e.startsWith("@"))return!0;const s=t.length-e.length;if(t.slice(0,s).endsWith("@ "))return!0;const i=t.lastIndexOf('"');if(i===-1)return!1;const r=t.slice(0,i);return r.endsWith("@")||r.endsWith("@ ")}class jr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(e,s){this.close(),this.sessionId=e,this.onEvent=s,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),_s(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const e=Yi(this.sessionId);this.socket=e,e.onopen=()=>{this.reconnectDelay=500},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await As(e);zr(s)&&this.onEvent?.(s)}}class Or{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(e){this.close(),this.onEvent=e,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),_s(this.socket),this.socket=void 0,this.onEvent=void 0}open(){if(!this.shouldReconnect)return;const e=er();this.socket=e,e.onopen=()=>{this.reconnectDelay=500},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await As(e);Lr(s)&&this.onEvent?.(s)}}function zr(t){const e=Cs(t);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(e)}function Lr(t){const e=Cs(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function Cs(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function As(t){try{return typeof t=="string"?JSON.parse(t):t instanceof Blob?JSON.parse(await t.text()):t instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(t)):void 0}catch{return}}function _s(t){if(t!==void 0){if(t.onmessage=null,t.onerror=null,t.onclose=null,t.readyState===WebSocket.CONNECTING){t.onopen=()=>{t.close()};return}t.close()}}function Ur(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function Nr(t,e,s){if(e!==s)return{type:"unchanged"};const i=t.find(r=>r.id!==s&&r.archived!==!0);return i===void 0?{type:"clear"}:{type:"select",session:i}}const Me=100;class qr{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i,this.socket=new jr,this.globalSocket=new Or,this.selectionSeq=0}connectStatusUpdates(){this.globalSocket.connect(e=>{e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):this.applySessionName(e.sessionId,e.name)})}dispose(){this.socket.close(),this.globalSocket.close()}clearActiveSession(){this.socket.close(),this.catchupStreamSessionId=void 0,this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}async startSession(){const e=this.getState().selectedWorkspace;if(e)try{const s=await w.startSession(e.path);this.setState({sessions:[s,...this.getState().sessions]}),await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}async selectSession(e,s){const i=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0;const r=es(e.id);this.setState({selectedSession:e,messages:ke(r?.messages??[]),messagePageStart:r?.start??0,messagePageTotal:r?.total??0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id]});try{if(e.archived===!0){const h=await w.messages(e.id,{limit:Me});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const d=this.mergeAndCacheHistory(e.id,h);this.setState({messages:ke(d.messages),messagePageStart:d.start,messagePageTotal:d.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),s?.updateUrl!==!1&&this.updateUrl();return}const o=[];this.socket.connect(e.id,h=>o.push(h));const[n,a]=await Promise.all([w.messages(e.id,{limit:Me}),w.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const c=this.mergeAndCacheHistory(e.id,n),l=a.isStreaming;this.catchupStreamSessionId=l?e.id:void 0,this.setState({messages:ke(c.messages),messagePageStart:c.start,messagePageTotal:c.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:l,status:a,activity:this.getState().sessionActivities[e.id]}),this.applyStatus(a);for(const h of o)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),s?.updateUrl!==!1&&this.updateUrl()}catch(o){i===this.selectionSeq&&this.setState({error:String(o)})}}async loadEarlierMessages(){const e=this.getState(),s=e.selectedSession;if(!(!s||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const i=await w.messages(s.id,{before:e.messagePageStart,limit:Me});if(this.getState().selectedSession?.id!==s.id)return;const r=this.mergeAndCacheHistory(s.id,i);this.setState({messages:ke(r.messages),messagePageStart:r.start,messagePageTotal:r.total})}catch(i){this.setState({error:String(i)})}finally{this.getState().selectedSession?.id===s.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,s){if(e.trim().startsWith("/"))return this.runCommand(e);if(Mr(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await w.prompt(r.id,e,s)}catch(o){this.setState({error:String(o)})}}async runShell(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,G("user",e)]});try{await w.shell(s.id,e)}catch(i){this.setState({messages:[...this.getState().messages,G("system",String(i))],error:String(i)})}}}async runCommand(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,G("user",e)]});try{this.applyCommandResult(await w.runCommand(s.id,e))}catch(i){this.setState({messages:[...this.getState().messages,G("system",String(i))],error:String(i)})}}}async respondToCommand(e,s){const i=this.getState().selectedSession;if(i){this.setState({commandDialog:void 0});try{this.applyCommandResult(await w.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async archiveSession(e=this.getState().selectedSession){if(e)try{await w.archive(e.id);const s=this.getState(),i=Ur(s.sessions,e.id,new Date().toISOString()),r=Nr(i,s.selectedSession?.id,e.id);this.setState({sessions:i}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&(this.clearActiveSession(),this.updateUrl())}catch(s){this.setState({error:String(s)})}}async restoreSession(e=this.getState().selectedSession){if(e)try{await w.restore(e.id);const s={...e};delete s.archived,delete s.archivedAt,this.replaceSession(s),this.getState().selectedSession?.id===s.id&&await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await w.abort(e.id)}catch(s){this.setState({error:String(s)})}}replaceSession(e){const s=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i=>i.id===e.id?e:i),selectedSession:s?.id===e.id?e:s})}mergeAndCacheHistory(e,s){const i=vr(es(e),s);return Sr(e,i),i}applyCommandResult(e){if(e.type==="select"){this.setState({commandDialog:e});return}const s=(e.type==="unsupported",e.message);if(s!==void 0&&s!==""&&this.setState({messages:[...this.getState().messages,G(e.type==="unsupported"?"system":"tool",s)]}),e.type==="done"&&e.session){const i=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(o=>o.id!==e.session?.id)];this.setState({sessions:r,selectedSession:i?.id===e.session.id?e.session:i}),i?.id!==e.session.id&&this.selectSession(e.session)}}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){this.setState({sessionStatuses:{...this.getState().sessionStatuses,[e.sessionId]:e},status:this.getState().selectedSession?.id===e.sessionId?e:this.getState().status}),this.catchupStreamSessionId===e.sessionId&&!e.isStreaming&&this.finishStreamCatchup(e.sessionId)}applySessionName(e,s){const i=o=>{if(o.id!==e)return o;const n={...o};return s===void 0||s===""?delete n.name:n.name=s,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i),selectedSession:r===void 0?void 0:i(r)})}applyEvent(e){const s=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===s){if(e.type==="message.end"||e.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Wr(e))return}const i=Er(this.getState().messages,e);i?this.setState({messages:i}):e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):e.type==="session.name"&&this.applySessionName(e.sessionId,e.name)}finishStreamCatchup(e){this.catchupStreamSessionId===e&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===e&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(e))}async refreshMessages(e){try{const s=await w.messages(e,{limit:Me});if(this.getState().selectedSession?.id!==e)return;const i=this.mergeAndCacheHistory(e,s);this.setState({messages:ke(i.messages),messagePageStart:i.start,messagePageTotal:i.total})}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function Wr(t){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(t.type)}class Fr{constructor(e,s,i,r){this.getState=e,this.setState=s,this.updateUrl=i,this.sessions=r}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""}),e?.updateUrl!==!1&&this.updateUrl()}async selectProject(e,s){this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await w.workspaces(e.id);this.setState({workspaces:i});const r=s?.workspaceId!==void 0&&s.workspaceId!==""?i.find(o=>o.id===s.workspaceId):i[0];r?await this.selectWorkspace(r,{sessionId:s?.sessionId,updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}async selectWorkspace(e,s){this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await w.sessions(e.path);this.setState({sessions:i});const r=s?.sessionId,o=r!==void 0&&r!==""?i.find(n=>n.id===r||n.id.startsWith(r)):i.find(n=>n.archived!==!0);o?await this.sessions.selectSession(o,{updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}}const Br=1200;class Hr{constructor(){this.pendingTokens=[]}handle(e,s){const i=Kr(e);if(i===void 0||!ss(i))return!1;const r=s.filter(c=>c.shortcut!==void 0&&c.enabled!==!1).map(c=>({action:c,tokens:Es(c.shortcut??"")})).filter(c=>c.tokens.length>0),o=this.pendingTokens.length>0&&!ss(i)?[...this.pendingTokens,i]:[i],n=r.find(c=>Zr(c.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(c=>Is(c.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Br)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Gr(t){return Es(t).map(e=>e.split("+").map(s=>s==="mod"?is()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?is()?"⌥":"Alt":s==="ctrl"?"Ctrl":s==="enter"?"Enter":s==="escape"?"Esc":s==="."?".":s.length===1?s.toUpperCase():`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join("+")).join(" ")}function Kr(t){if(t.isComposing)return;const e=Vr(t.key);if(e===void 0)return;const s=[];return(t.metaKey||t.ctrlKey)&&s.push("mod"),t.altKey&&s.push("alt"),t.shiftKey&&s.push("shift"),s.push(e),s.join("+")}function Es(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function Vr(t){if(t===" ")return"space";if(t.length===1)return t.toLowerCase();const e=t.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(e))return e}function Zr(t,e){return t.length===e.length&&Is(t,e)}function Is(t,e){return e.every((s,i)=>t[i]===s)}function ss(t){return t.includes("+")}function is(){return navigator.userAgent.toLowerCase().includes("mac")}function Qr(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:t=>{t.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",group:"General",enabled:t=>t.state.selectedSession!==void 0,run:t=>{t.focusPrompt()}},{id:"project.add",title:"Add Project",group:"Project",run:t=>t.addProject()},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:t=>{t.selectMainView("chat")}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:De,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:rs,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:De,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:rs,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:De,run:t=>t.state.workspaceTool==="core:workspace.git"&&t.state.selectedWorkspace?.isGitRepo===!0?t.refreshGit():t.refreshFiles()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:De,run:t=>t.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&t.state.selectedSession.archived!==!0,run:t=>t.archiveSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&Jr(t.state.status),run:t=>t.stopActiveWork()}]}function De(t){return t.state.selectedWorkspace!==void 0}function rs(t){return t.state.selectedWorkspace?.isGitRepo===!0}function Jr(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const Xr="modulepreload",Yr=function(t){return"/"+t},os={},Rs=function(e,s,i){let r=Promise.resolve();if(s&&s.length>0){let c=function(l){return Promise.all(l.map(h=>Promise.resolve(h).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=c(s.map(l=>{if(l=Yr(l),l in os)return;os[l]=!0;const h=l.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${d}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":Xr,h||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),h)return new Promise((m,x)=>{f.addEventListener("load",m),f.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function eo(){return[{id:"workspace.files",title:"Files",order:10,render:to},{id:"workspace.git",title:"Git",order:20,visible:t=>t.isGitRepo,render:oo},{id:"workspace.terminal",title:"Terminal",order:30,render:ro}]}function to(t){return p`
18
+ <section class="toolbar">
19
+ <strong>Files</strong>
20
+ ${t.fileTreeStale?p`<span class="stale">stale</span>`:null}
21
+ <button @click=${t.onRefreshFiles}>Refresh</button>
22
+ </section>
23
+ <section class="split">
24
+ <div class="list tree">
25
+ ${t.fileTree.length===0?p`<p class="muted">No files loaded.</p>`:t.fileTree.map(e=>Ms(t,e,0))}
26
+ </div>
27
+ <div class="viewer">
28
+ ${io(t)}
29
+ </div>
30
+ </section>
31
+ `}function Ms(t,e,s){const i=t.expandedDirs[e.path],r=i!==void 0;return p`
32
+ <button class="row" style=${`--depth:${String(s)}`} @click=${()=>{so(t,e)}}>
33
+ <span>${e.type==="directory"?r?"▾":"▸":"·"}</span>
34
+ <span>${e.name}</span>
35
+ </button>
36
+ ${r?i.map(o=>Ms(t,o,s+1)):null}
37
+ `}function so(t,e){e.type==="directory"?t.onExpandDir(e.path):t.onSelectFile(e.path)}function io(t){const e=t.selectedFileContent;return t.selectedFilePath===void 0||t.selectedFilePath===""?p`<p class="muted">Select a file.</p>`:e===void 0?p`<p class="muted">Loading ${t.selectedFilePath}…</p>`:e.binary?p`<p class="muted">Binary file: ${e.path}</p>`:(Ds(),p`
38
+ <div class="viewer-header"><strong>${e.path}</strong><small>${e.language??"text"}${e.truncated?" · truncated":""}</small></div>
39
+ <code-viewer .content=${e.content} .language=${e.language}></code-viewer>
40
+ `)}function ro(t){return lo(),p`<terminal-panel .workspace=${t.workspace}></terminal-panel>`}function oo(t){const e=t.gitStatus;return p`
41
+ <section class="toolbar">
42
+ <strong>Git</strong>
43
+ ${t.gitStale?p`<span class="stale">stale</span>`:null}
44
+ <button @click=${t.onRefreshGit}>Refresh</button>
45
+ </section>
46
+ <section class="split">
47
+ <div class="list">
48
+ ${e===void 0?p`<p class="muted">No status loaded.</p>`:e.isGitRepo?p`
49
+ <p class="summary">${co(e)}</p>
50
+ ${e.files.length===0?p`<p class="muted">No changes.</p>`:e.files.map(s=>p`
51
+ <button class="row ${t.selectedDiffPath===s.path?"selected":""}" @click=${()=>{t.onSelectDiff(s.path)}}>
52
+ <span>${po(s.index,s.workingTree)}</span>
53
+ <span>${s.path}</span>
54
+ </button>
55
+ `)}
56
+ `:p`<p class="muted">Not a git repository.</p>`}
57
+ </div>
58
+ <div class="viewer">
59
+ ${no(t)}
60
+ </div>
61
+ </section>
62
+ `}function no(t){if(t.selectedDiffPath===void 0||t.selectedDiffPath==="")return p`<p class="muted">Select a changed file.</p>`;const e=t.selectedDiff,s=t.selectedStagedDiff;if(e===void 0||s===void 0)return p`<p class="muted">Loading diff…</p>`;const i=[s,e].filter(r=>r.diff!=="");return i.length===0?p`<p class="muted">No staged or unstaged diff.</p>`:p`
63
+ <div class=${i.length===1?"diffs single":"diffs"}>
64
+ ${i.map(r=>ao(r))}
65
+ </div>
66
+ `}function ao(t){return Ds(),p`
67
+ <section class="diff-section">
68
+ <div class="viewer-header"><strong>${t.path??"diff"}</strong><small>${t.staged?"staged":"unstaged"}${t.truncated?" · truncated":""}</small></div>
69
+ <code-viewer .content=${t.diff} .language=${"diff"}></code-viewer>
70
+ </section>
71
+ `}function Ds(){Rs(()=>import("./CodeViewer-DsXI9VCn.js"),__vite__mapDeps([0,1,2,3]))}function lo(){Rs(()=>import("./TerminalPanel-CpzJEFv1.js"),__vite__mapDeps([4,5,6]))}function co(t){const e=t.branch??"detached",s=t.ahead??0,i=t.behind??0;return s===0&&i===0?e:`${e} · ↑${String(s)} ↓${String(i)}`}function po(t,e){return(e!=="unmodified"?e:t).slice(0,1).toUpperCase()}const ho={id:"core",name:"Pi Web Core",activate:()=>({actions:Qr(),workspacePanels:eo()})},uo={id:"example",name:"Example Plugin",activate:()=>({actions:[{id:"workspace.show-path",title:"Show Current Workspace Path",group:"Example",enabled:t=>t.state.selectedWorkspace!==void 0,run:t=>{const e=t.state.selectedWorkspace?.path??"No workspace selected";window.alert(e)}}],workspacePanels:[{id:"workspace.info",title:"Info",order:100,render:t=>p`
72
+ <section class="toolbar"><strong>Info</strong></section>
73
+ <section class="viewer">
74
+ <p><strong>Workspace</strong></p>
75
+ <p class="muted">${t.workspace.label}</p>
76
+ <p class="muted">${t.workspace.path}</p>
77
+ </section>
78
+ `}]})},fo=/^[a-z][a-z0-9.-]*$/u,go=/^[a-z][a-z0-9.-]*$/u;class mo{constructor(){this.actions=[],this.workspacePanels=[],this.pluginIds=new Set,this.contributionIds=new Set}register(e){if(this.validatePluginId(e.id),this.pluginIds.has(e.id))throw new Error(`Duplicate plugin id: ${e.id}`);this.pluginIds.add(e.id);const s=e.activate({apiVersion:1});for(const i of s.actions??[])this.actions.push(this.qualifyAction(e.id,i));for(const i of s.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(e.id,i))}getActions(e){return this.actions.map(s=>{const i=typeof s.enabled=="function"?s.enabled(e):s.enabled,r={id:s.id,pluginId:s.pluginId,localId:s.localId,title:s.title,run:()=>s.run(e)};return s.description!==void 0&&(r.description=s.description),s.shortcut!==void 0&&(r.shortcut=s.shortcut),s.group!==void 0&&(r.group=s.group),i!==void 0&&(r.enabled=i),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,s)=>(e.order??1e3)-(s.order??1e3)||e.title.localeCompare(s.title))}qualifyAction(e,s){const i=this.qualify(e,s.id);return{...s,id:i,pluginId:e,localId:s.id}}qualifyWorkspacePanel(e,s){const i=this.qualify(e,s.id);return{...s,id:i,pluginId:e,localId:s.id}}qualify(e,s){this.validateLocalId(s);const i=`${e}:${s}`;if(this.contributionIds.has(i))throw new Error(`Duplicate contribution id: ${i}`);return this.contributionIds.add(i),i}validatePluginId(e){if(!fo.test(e))throw new Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!go.test(e))throw new Error(`Invalid contribution id: ${e}`)}}function bo(){const t=new URLSearchParams(window.location.search);return{projectId:t.get("project")??void 0,workspaceId:t.get("workspace")??void 0,sessionId:t.get("session")??void 0,tool:yo(t.get("tool")),view:wo(t.get("view"))}}function xo(t,e){const s=new URL(window.location.href);s.searchParams.delete("project"),s.searchParams.delete("workspace"),s.searchParams.delete("session"),s.searchParams.delete("tool"),s.searchParams.delete("view"),t.projectId!==void 0&&t.projectId!==""&&s.searchParams.set("project",t.projectId),t.workspaceId!==void 0&&t.workspaceId!==""&&s.searchParams.set("workspace",t.workspaceId),t.sessionId!==void 0&&t.sessionId!==""&&s.searchParams.set("session",t.sessionId),t.tool!==void 0&&s.searchParams.set("tool",t.tool),t.view!==void 0&&s.searchParams.set("view",t.view);const i=`${s.pathname}${s.search}${s.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==r&&(e?.replace===!0?window.history.replaceState({},"",s):window.history.pushState({},"",s))}function yo(t){return t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":js(t)?t:void 0}function wo(t){return t==="chat"?"chat":t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":js(t)?t:void 0}function js(t){return t!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(t)}const ko=B`
79
+ :host { display: block; height: 100dvh; box-sizing: border-box; padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); color: #e6edf3; background: #0d1117; font: 14px system-ui, sans-serif; }
80
+ .shell { display: grid; grid-template-columns: 340px minmax(420px, 1fr) minmax(360px, 42vw); height: 100%; min-height: 0; }
81
+ aside { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid #30363d; overflow: hidden; }
82
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid #30363d; }
83
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; overflow: auto; border-bottom: 1px solid #21262d; }
84
+ session-list { flex: 1 1 auto; min-height: 0; overflow: auto; }
85
+ main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
86
+ .mobile-tabs { display: none; flex: 0 0 auto; gap: 6px; padding: 8px; border-bottom: 1px solid #30363d; overflow-x: auto; }
87
+ .mobile-navigation-tab, .mobile-navigation-panel, .mobile-panel { display: none; }
88
+ .mobile-tabs button.selected { border-color: #58a6ff; background: #0d2847; }
89
+ workspace-panel { min-width: 0; min-height: 0; border-left: 1px solid #30363d; overflow: hidden; }
90
+ @media (max-width: 1180px) {
91
+ .shell { grid-template-columns: 340px minmax(0, 1fr); }
92
+ .shell > workspace-panel { display: none; }
93
+ .mobile-tabs { display: flex; }
94
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
95
+ main.workspace-view .empty { display: none; }
96
+ main.chat-view .mobile-panel, main.navigation-view .mobile-panel { display: none; }
97
+ .mobile-panel { flex: 1 1 auto; min-height: 0; display: flex; }
98
+ .mobile-panel workspace-panel { flex: 1 1 auto; border-left: 0; }
99
+ }
100
+ @media (max-width: 760px) {
101
+ .shell { grid-template-columns: minmax(0, 1fr); }
102
+ aside { display: none; }
103
+ .mobile-navigation-tab { display: block; }
104
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
105
+ main.navigation-view .empty { display: none; }
106
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
107
+ }
108
+ status-bar { flex: 0 0 auto; }
109
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
110
+ prompt-editor, chat-composer { flex: 0 0 auto; }
111
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
112
+ .empty { margin: auto; color: #8b949e; }
113
+ .error { padding: 10px 16px; border-bottom: 1px solid #30363d; color: #ff7b72; }
114
+ `,So=B`
115
+ :host { display: flex; flex-direction: column; min-height: 0; color: #e6edf3; background: #0d1117; font: 13px system-ui, sans-serif; }
116
+ header { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid #30363d; }
117
+ .tabs { display: flex; gap: 6px; }
118
+ button { border: 1px solid #30363d; border-radius: 7px; background: #161b22; color: #e6edf3; padding: 5px 7px; cursor: pointer; }
119
+ button.selected { border-color: #58a6ff; background: #0d2847; }
120
+ small, .muted { color: #8b949e; }
121
+ header small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
122
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid #21262d; }
123
+ .toolbar button { margin-left: auto; }
124
+ .stale { border: 1px solid #6e5200; border-radius: 999px; color: #d29922; padding: 1px 6px; font-size: 12px; }
125
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
126
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid #30363d; padding: 6px; }
127
+ .row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
128
+ .row:hover, .row.selected { background: #0d2847; }
129
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
130
+ .summary { margin: 4px 6px 8px; color: #8b949e; }
131
+ .viewer { min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
132
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
133
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
134
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid #30363d; }
135
+ .diff-section:last-child { border-bottom: 0; }
136
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid #21262d; background: #0d1117; }
137
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
138
+ code-viewer { flex: 1 1 auto; min-height: 0; }
139
+ pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
140
+ p { margin: 10px; }
141
+ `,wt=B`
142
+ :host { display: block; color: #e6edf3; font: 14px system-ui, sans-serif; }
143
+ section { padding: 10px; }
144
+ h2 { display: flex; justify-content: space-between; align-items: center; margin: 0 0 8px; color: #8b949e; font-size: 12px; text-transform: uppercase; }
145
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
146
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
147
+ .subheading { margin-top: 14px; }
148
+ .section-toggle { display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-transform: inherit; }
149
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
150
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; }
151
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: #58a6ff; background: #0d2847; }
152
+ .action-row.archived .action-main { color: #8b949e; }
153
+ .action-main { min-width: 0; text-align: left; border-top-right-radius: 0; border-bottom-right-radius: 0; }
154
+ .action-menu { position: relative; align-self: stretch; }
155
+ .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: #8b949e; border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
156
+ .action-menu-toggle:hover { color: #e6edf3; background: #21262d; }
157
+ .action-menu-panel { position: fixed; z-index: 50; min-width: 120px; padding: 4px; border: 1px solid #30363d; border-radius: 8px; background: #161b22; box-shadow: 0 8px 24px #0008; }
158
+ .action-menu-panel button { display: block; width: 100%; text-align: left; border: 0; background: transparent; color: #e6edf3; }
159
+ .action-menu-panel button:hover { background: #0d2847; }
160
+ button.selected { border-color: #58a6ff; background: #0d2847; }
161
+ button:disabled { opacity: .5; cursor: not-allowed; }
162
+ small { display: block; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
163
+ `,vo=B`
164
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: #e6edf3; font: 14px system-ui, sans-serif; }
165
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
166
+ .chat { height: 100%; min-height: 0; overflow: auto; padding: 16px 16px 64px; box-sizing: border-box; }
167
+ .history-indicator { position: absolute; top: 10px; right: 18px; z-index: 2; display: grid; gap: 2px; max-width: min(320px, calc(100% - 36px)); border: 1px solid #30363d; border-radius: 8px; background: #0d1117dd; color: #8b949e; padding: 6px 8px; font-size: 12px; text-align: right; pointer-events: none; box-shadow: 0 8px 24px #0006; }
168
+ .activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 3; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid #30363d; border-radius: 999px; background: #0d1117e6; color: #8b949e; padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px #0008; backdrop-filter: blur(6px); }
169
+ .activity-dock.active { border-color: #238636; color: #3fb950; background: #0f1b12ee; }
170
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
171
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
172
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
173
+ .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid #30363d; border-radius: 10px; background: #161b22; overflow: hidden; }
174
+ .msg.user { border-color: #2f81f7; background: #0d2847; }
175
+ .msg.tool { border-color: #6e5200; background: #1f1a10; color: #d29922; }
176
+ .msg.system { color: #ff7b72; }
177
+ .msg.bash { border-color: #3fb950; background: #0f1b12; }
178
+ .msg.event-group { padding: 0; border-color: #30363d; background: #0d1117; color: #8b949e; }
179
+ .msg.event-group > summary { display: flex; align-items: center; gap: 8px; padding: 8px 12px; color: #8b949e; }
180
+ .msg.event-group > summary .label { margin: 0; }
181
+ .group-body { padding: 0 12px 12px; }
182
+ .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid #21262d; color: #e6edf3; overflow: hidden; }
183
+ .group-msg.tool { color: #d29922; }
184
+ .group-msg.system { color: #ff7b72; }
185
+ .group-msg.bash { color: #3fb950; }
186
+ .history-boundary { display: grid; gap: 3px; margin: 0 0 14px; color: #8b949e; font-size: 12px; text-align: center; }
187
+ .session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid #30363d; border-radius: 10px; background: #161b22; color: #e6edf3; overflow: auto; -webkit-overflow-scrolling: touch; }
188
+ .session-activity.compacting { border-color: #a371f7; background: #21132f; }
189
+ .session-activity.receiving { border-color: #238636; background: #0f1b12; }
190
+ .session-activity strong { color: #d2a8ff; }
191
+ .session-activity.receiving strong { color: #3fb950; }
192
+ .session-activity span, .session-activity small { color: #8b949e; }
193
+ .history-boundary small { color: #6e7681; }
194
+ .msg-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
195
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
196
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
197
+ .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid #30363d; border-radius: 6px; background: #161b22; color: #8b949e; padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
198
+ .msg-action:hover, .msg-action:focus { color: #e6edf3; border-color: #58a6ff; }
199
+ .msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
200
+ .label { display: block; color: #8b949e; font-size: 12px; text-transform: uppercase; }
201
+ .msg-header .label { margin: 0; }
202
+ .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: #6e7681; padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
203
+ .msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
204
+ .msg-meta:focus { outline: 1px solid #30363d; outline-offset: 3px; border-radius: 4px; }
205
+ @media (hover: none) {
206
+ .msg-actions { opacity: 1; }
207
+ .msg-meta { opacity: .75; max-width: 26px; }
208
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
209
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
210
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
211
+ }
212
+ formatted-text.part { display: block; }
213
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: auto; -webkit-overflow-scrolling: touch; }
214
+ .part + .part { margin-top: 10px; }
215
+ .tool-line { color: #d29922; }
216
+ .summary { color: #8b949e; margin-left: 6px; }
217
+ .part:is(details) { border-top: 1px solid #30363d; padding-top: 8px; }
218
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: auto; -webkit-overflow-scrolling: touch; }
219
+ .skill-invocation { border: 1px solid #30363d; border-radius: 8px; background: #161b22; padding: 8px 10px; }
220
+ .skill-invocation > summary { color: #d2a8ff; }
221
+ .skill-invocation > small { display: block; margin: 6px 0 8px; color: #8b949e; }
222
+ summary { cursor: pointer; color: #8b949e; }
223
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
224
+ .shell-output { color: #e6edf3; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
225
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
226
+ `,$o=B`
227
+ :host { display: block; }
228
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
229
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
230
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
231
+ ul, ol { padding-left: 22px; }
232
+ li + li { margin-top: 3px; }
233
+ code { border: 1px solid #30363d; border-radius: 4px; background: #0d1117; padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
234
+ .code-block-wrapper { position: relative; }
235
+ .code-block-wrapper pre { margin: 0; padding-right: 58px; }
236
+ pre { border: 1px solid #30363d; border-radius: 8px; background: #0d1117; padding: 10px; overflow: auto; }
237
+ pre code { border: 0; padding: 0; background: transparent; }
238
+ .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; border: 1px solid #30363d; border-radius: 6px; background: #161b22; color: #8b949e; padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
239
+ .code-copy-button:hover { color: #e6edf3; border-color: #58a6ff; }
240
+ blockquote { border-left: 3px solid #30363d; padding-left: 10px; color: #8b949e; }
241
+ a { color: #58a6ff; }
242
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
243
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
244
+ h1 { font-size: 20px; }
245
+ h2 { font-size: 17px; }
246
+ h3 { font-size: 15px; }
247
+ h4 { font-size: 14px; }
248
+ table { border-collapse: collapse; display: block; overflow: auto; }
249
+ th, td { border: 1px solid #30363d; padding: 4px 8px; }
250
+ th { background: #161b22; }
251
+ `,Po=B`
252
+ :host { display: block; color: #8b949e; font: 12px system-ui, sans-serif; }
253
+ .bar { display: flex; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid #30363d; background: #0d1117; white-space: nowrap; overflow: hidden; }
254
+ span { overflow: hidden; text-overflow: ellipsis; }
255
+ .bar > span:first-child { flex: 1 1 auto; min-width: 80px; }
256
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: #8b949e; }
257
+ .activity.active { color: #3fb950; }
258
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
259
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
260
+ .muted { color: #6e7681; }
261
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
262
+ `,To=B`
263
+ :host { display: block; }
264
+ .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid #30363d; border-radius: 8px; background: #161b22; box-shadow: 0 10px 30px #0008; }
265
+ button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid #30363d; border-radius: 0; background: transparent; color: #e6edf3; padding: 8px 10px; text-align: left; cursor: pointer; }
266
+ button:last-child { border-bottom: 0; }
267
+ button.selected, button:hover { background: #0d2847; }
268
+ span { color: #8b949e; font-size: 12px; }
269
+ small { grid-column: 1 / -1; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
270
+ `,Co=B`
271
+ :host { position: fixed; inset: 0; z-index: 10; color: #e6edf3; font: 14px system-ui, sans-serif; }
272
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: #0008; }
273
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid #30363d; border-radius: 12px; background: #0d1117; box-shadow: 0 20px 60px #000b; overflow: hidden; }
274
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid #30363d; }
275
+ .options { min-height: 0; overflow: auto; outline: none; }
276
+ button { border: 0; background: transparent; color: #e6edf3; cursor: pointer; }
277
+ header button { font-size: 20px; color: #8b949e; }
278
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid #21262d; text-align: left; }
279
+ .options button.selected, .options button:hover { background: #0d2847; }
280
+ small { display: block; margin-top: 4px; color: #8b949e; }
281
+ `,Ao=B`
282
+ :host { position: fixed; inset: 0; z-index: 20; color: #e6edf3; font: 14px system-ui, sans-serif; }
283
+ .backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: #0008; padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
284
+ section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid #30363d; border-radius: 12px; background: #0d1117; box-shadow: 0 20px 60px #000b; overflow: hidden; }
285
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid #30363d; }
286
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: #e6edf3; font: 16px system-ui, sans-serif; padding: 8px; }
287
+ input::placeholder { color: #6e7681; }
288
+ button { border: 0; background: transparent; color: #e6edf3; cursor: pointer; }
289
+ header button { color: #8b949e; font-size: 22px; padding: 2px 8px; }
290
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; -webkit-overflow-scrolling: touch; }
291
+ .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid #21262d; text-align: left; }
292
+ .options button.selected, .options button:hover { background: #0d2847; }
293
+ .main { min-width: 0; }
294
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
295
+ small { display: block; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
296
+ .group { grid-column: 1 / -1; font-size: 12px; }
297
+ kbd { align-self: center; border: 1px solid #30363d; border-radius: 6px; background: #161b22; color: #8b949e; padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
298
+ .empty { padding: 24px; color: #8b949e; text-align: center; }
299
+ `,_o=B`
300
+ :host { position: relative; z-index: 5; display: block; color: #e6edf3; font: 14px system-ui, sans-serif; }
301
+ footer { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 12px; border-top: 1px solid #30363d; }
302
+ footer.shell-mode { border-top-color: #3fb950; background: #0f1b12; }
303
+ .editor-wrap { position: relative; min-width: 0; }
304
+ .actions { display: flex; gap: 8px; align-items: start; white-space: nowrap; }
305
+ textarea { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow-y: auto; border-radius: 8px; border: 1px solid #30363d; background: #0d1117; color: #e6edf3; padding: 8px; font: 16px/1.4 system-ui, sans-serif; }
306
+ .shell-mode textarea { border-color: #3fb950; box-shadow: 0 0 0 1px #3fb95055; }
307
+ .mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid #238636; border-radius: 999px; background: #0f2a16; color: #3fb950; padding: 2px 8px; font-size: 12px; pointer-events: none; }
308
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
309
+ button:disabled, textarea:disabled { opacity: .5; cursor: not-allowed; }
310
+ @media (max-width: 640px) {
311
+ footer { grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 8px; }
312
+ .actions { justify-content: flex-end; flex-wrap: wrap; }
313
+ }
314
+ `;var Eo=Object.defineProperty,Io=Object.getOwnPropertyDescriptor,le=(t,e,s,i)=>{for(var r=i>1?void 0:i?Io(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Eo(e,s,r),r};let Z=class extends I{constructor(){super(...arguments),this.projects=[],this.menuStyle="",this.onDocumentClick=t=>{t.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(t){t.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(e=>e.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0)}render(){return p`
315
+ <section>
316
+ <h2>Projects</h2>
317
+ ${this.projects.map(t=>p`
318
+ <div class=${`action-row ${this.selected?.id===t.id?"selected":""}`}>
319
+ <button class="action-main" @click=${()=>this.onSelect?.(t)}>
320
+ <span>${t.name}</span><small>${t.path}</small>
321
+ </button>
322
+ <div class="action-menu">
323
+ <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${t.name}`} @click=${e=>{e.stopPropagation(),this.toggleMenu(t.id,e.currentTarget)}}>⋯</button>
324
+ ${this.openMenuProjectId===t.id?p`
325
+ <div class="action-menu-panel" style=${this.menuStyle}>
326
+ <button title="Close project" @click=${()=>{this.close(t)}}>Close</button>
327
+ </div>
328
+ `:null}
329
+ </div>
330
+ </div>
331
+ `)}
332
+ </section>
333
+ `}toggleMenu(t,e){if(this.openMenuProjectId===t){this.openMenuProjectId=void 0;return}if(e instanceof HTMLElement){const s=e.getBoundingClientRect();this.menuStyle=`top: ${String(s.bottom+4)}px; right: ${String(window.innerWidth-s.right)}px;`}this.openMenuProjectId=t}close(t){this.openMenuProjectId=void 0,confirm(`Close ${t.name}?
334
+
335
+ This only removes it from Pi Web; it will not change the project folder.`)&&this.onClose?.(t)}};Z.styles=wt;le([u({attribute:!1})],Z.prototype,"projects",2);le([u({attribute:!1})],Z.prototype,"selected",2);le([u({attribute:!1})],Z.prototype,"onSelect",2);le([u({attribute:!1})],Z.prototype,"onClose",2);le([$()],Z.prototype,"openMenuProjectId",2);le([$()],Z.prototype,"menuStyle",2);Z=le([z("project-list")],Z);var Ro=Object.defineProperty,Mo=Object.getOwnPropertyDescriptor,Qe=(t,e,s,i)=>{for(var r=i>1?void 0:i?Mo(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Ro(e,s,r),r};let ue=class extends I{constructor(){super(...arguments),this.workspaces=[]}render(){return p`
336
+ <section>
337
+ <h2>Workspaces</h2>
338
+ ${this.workspaces.map(t=>p`
339
+ <button class=${this.selected?.id===t.id?"selected":""} @click=${()=>this.onSelect?.(t)}>
340
+ <span>${t.label}${t.isMain?" · main":""}</span><small>${t.path}</small>
341
+ </button>
342
+ `)}
343
+ </section>
344
+ `}};ue.styles=wt;Qe([u({attribute:!1})],ue.prototype,"workspaces",2);Qe([u({attribute:!1})],ue.prototype,"selected",2);Qe([u({attribute:!1})],ue.prototype,"onSelect",2);ue=Qe([z("workspace-list")],ue);var Do=Object.defineProperty,jo=Object.getOwnPropertyDescriptor,L=(t,e,s,i)=>{for(var r=i>1?void 0:i?jo(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Do(e,s,r),r};function Oo(t){return t.name!==void 0&&t.name!==""?t.name:t.firstMessage!==""?t.firstMessage:t.id.slice(0,8)}let D=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=t=>{t.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(t){t.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),t.has("sessions")&&!this.sessions.some(e=>e.archived===!0)&&(this.archivedExpanded=!1)}render(){const t=this.sessions.filter(s=>s.archived!==!0),e=this.sessions.filter(s=>s.archived===!0);return p`
345
+ <section>
346
+ <h2>Sessions <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>
347
+ ${t.map(s=>this.renderSession(s))}
348
+ ${e.length>0?p`
349
+ <h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span><small>${e.length}</small></button></h2>
350
+ ${this.archivedExpanded?e.map(s=>this.renderSession(s)):null}
351
+ `:null}
352
+ </section>
353
+ `}renderSession(t){return p`
354
+ <div class="action-row ${this.selected?.id===t.id?"selected":""} ${t.archived===!0?"archived":""}">
355
+ <button class="action-main" @click=${()=>this.onSelect?.(t)}>
356
+ <span>${Oo(t)}</span><small>${this.renderStatus(t)}${String(t.messageCount)} messages</small>
357
+ </button>
358
+ <div class="action-menu">
359
+ <button class="action-menu-toggle" title="Session actions" @click=${e=>{e.stopPropagation(),this.toggleMenu(t.id,e.currentTarget)}}>⋯</button>
360
+ ${this.openMenuSessionId===t.id?p`
361
+ <div class="action-menu-panel" style=${this.menuStyle}>
362
+ ${t.archived===!0?p`<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(t)}}>Restore</button>`:p`<button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(t)}}>Archive</button>`}
363
+ </div>
364
+ `:null}
365
+ </div>
366
+ </div>
367
+ `}toggleMenu(t,e){if(this.openMenuSessionId===t){this.openMenuSessionId=void 0;return}if(e instanceof HTMLElement){const s=e.getBoundingClientRect();this.menuStyle=`top: ${String(s.bottom+4)}px; right: ${String(window.innerWidth-s.right)}px;`}this.openMenuSessionId=t}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0)}renderStatus(t){if(t.archived===!0)return"read-only · ";const e=this.statuses[t.id],s=this.activities[t.id];return s?.phase==="active"?`● ${s.label} · `:e===void 0?"":e.isStreaming?"● streaming · ":e.isBashRunning?"● bash · ":e.isCompacting?"● compacting · ":e.pendingMessageCount>0?`● ${String(e.pendingMessageCount)} pending · `:""}};D.styles=wt;L([u({attribute:!1})],D.prototype,"sessions",2);L([u({attribute:!1})],D.prototype,"statuses",2);L([u({attribute:!1})],D.prototype,"activities",2);L([u({attribute:!1})],D.prototype,"selected",2);L([u({type:Boolean})],D.prototype,"canStart",2);L([u({attribute:!1})],D.prototype,"onSelect",2);L([u({attribute:!1})],D.prototype,"onStart",2);L([$()],D.prototype,"openMenuSessionId",2);L([$()],D.prototype,"menuStyle",2);L([$()],D.prototype,"archivedExpanded",2);L([u({attribute:!1})],D.prototype,"onArchive",2);L([u({attribute:!1})],D.prototype,"onRestore",2);D=L([z("session-list")],D);function zo(t,e=0){const s=[];let i=[],r=0;const o=(a,c)=>{i.length||(r=c),i.push(a)},n=()=>{i.length&&(s.push({kind:"group",messages:i,startIndex:r}),i=[])};return t.forEach((a,c)=>{const l=a.parts.filter(m=>ns(a,m)),h=a.parts.filter(m=>!ns(a,m)),d=e+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};h.length&&o({role:a.role,parts:h,...f},d),l.length&&(n(),s.push({kind:"message",message:{role:a.role,parts:l,...f},index:d}))}),n(),s}function Lo(t){if(t.every(i=>i.source==="compaction"))return`${String(t.length)} history compaction ${t.length===1?"summary":"summaries"}`;if(t.every(i=>i.source==="branch_summary"))return`${String(t.length)} branch ${t.length===1?"summary":"summaries"}`;const e=t.reduce((i,r)=>(i[r.role]=(i[r.role]??0)+1,i),{}),s=Object.entries(e).map(([i,r])=>`${String(r)} ${i}`).join(" · ");return`${String(t.length)} ${t.length===1?"event":"events"}${s!==""?` · ${s}`:""}`}function ns(t,e){return t.source==="compaction"||t.source==="branch_summary"?!1:e.type==="skillInvocation"?!0:e.type==="text"&&(t.role==="user"||t.role==="assistant"||t.role==="system"||t.role==="bash")}const Uo={CHILD:2},No=t=>(...e)=>({_$litDirective$:t,values:e});class qo{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,s,i){this._$Ct=e,this._$AM=s,this._$Ci=i}_$AS(e,s){return this.update(e,s)}update(e,s){return this.render(...s)}}class lt extends qo{constructor(e){if(super(e),this.it=C,e.type!==Uo.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===C||e==null)return this._t=void 0,this.it=e;if(e===oe)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const s=[e];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}lt.directiveName="unsafeHTML",lt.resultType=1;const Wo=No(lt);function kt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ce=kt();function Os(t){ce=t}var se={exec:()=>null};function b(t,e=""){let s=typeof t=="string"?t:t.source,i={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(R.caret,"$1"),s=s.replace(r,n),i},getRegex:()=>new RegExp(s,e)};return i}var Fo=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),R={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:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},Bo=/^(?:[ \t]*(?:\n|$))+/,Ho=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Go=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ie=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ko=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,St=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zs=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ls=b(zs).replace(/bull/g,St).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Vo=b(zs).replace(/bull/g,St).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),vt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Zo=/^[^\n]+/,$t=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Qo=b(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",$t).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Jo=b(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,St).getRegex(),Je="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",Pt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Xo=b("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\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",Pt).replace("tag",Je).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Us=b(vt).replace("hr",Ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Je).getRegex(),Yo=b(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Us).getRegex(),Tt={blockquote:Yo,code:Ho,def:Qo,fences:Go,heading:Ko,hr:Ie,html:Xo,lheading:Ls,list:Jo,newline:Bo,paragraph:Us,table:se,text:Zo},as=b("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Je).getRegex(),en={...Tt,lheading:Vo,table:as,paragraph:b(vt).replace("hr",Ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",as).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Je).getRegex()},tn={...Tt,html:b(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Pt).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:se,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:b(vt).replace("hr",Ie).replace("heading",` *#{1,6} *[^
368
+ ]`).replace("lheading",Ls).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},sn=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,rn=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ns=/^( {2,}|\\)\n(?!\s*$)/,on=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,be=/[\p{P}\p{S}]/u,Xe=/[\s\p{P}\p{S}]/u,Ct=/[^\s\p{P}\p{S}]/u,nn=b(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Xe).getRegex(),qs=/(?!~)[\p{P}\p{S}]/u,an=/(?!~)[\s\p{P}\p{S}]/u,ln=/(?:[^\s\p{P}\p{S}]|~)/u,cn=b(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Fo?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ws=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,dn=b(Ws,"u").replace(/punct/g,be).getRegex(),pn=b(Ws,"u").replace(/punct/g,qs).getRegex(),Fs="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",hn=b(Fs,"gu").replace(/notPunctSpace/g,Ct).replace(/punctSpace/g,Xe).replace(/punct/g,be).getRegex(),un=b(Fs,"gu").replace(/notPunctSpace/g,ln).replace(/punctSpace/g,an).replace(/punct/g,qs).getRegex(),fn=b("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ct).replace(/punctSpace/g,Xe).replace(/punct/g,be).getRegex(),gn=b(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,be).getRegex(),mn="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",bn=b(mn,"gu").replace(/notPunctSpace/g,Ct).replace(/punctSpace/g,Xe).replace(/punct/g,be).getRegex(),xn=b(/\\(punct)/,"gu").replace(/punct/g,be).getRegex(),yn=b(/^<(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(),wn=b(Pt).replace("(?:-->|$)","-->").getRegex(),kn=b("^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",wn).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Fe=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Sn=b(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Fe).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Bs=b(/^!?\[(label)\]\[(ref)\]/).replace("label",Fe).replace("ref",$t).getRegex(),Hs=b(/^!?\[(ref)\](?:\[\])?/).replace("ref",$t).getRegex(),vn=b("reflink|nolink(?!\\()","g").replace("reflink",Bs).replace("nolink",Hs).getRegex(),ls=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,At={_backpedal:se,anyPunctuation:xn,autolink:yn,blockSkip:cn,br:Ns,code:rn,del:se,delLDelim:se,delRDelim:se,emStrongLDelim:dn,emStrongRDelimAst:hn,emStrongRDelimUnd:fn,escape:sn,link:Sn,nolink:Hs,punctuation:nn,reflink:Bs,reflinkSearch:vn,tag:kn,text:on,url:se},$n={...At,link:b(/^!?\[(label)\]\((.*?)\)/).replace("label",Fe).getRegex(),reflink:b(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Fe).getRegex()},ct={...At,emStrongRDelimAst:un,emStrongLDelim:pn,delLDelim:gn,delRDelim:bn,url:b(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ls).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:b(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ls).getRegex()},Pn={...ct,br:b(Ns).replace("{2,}","*").getRegex(),text:b(ct.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},je={normal:Tt,gfm:en,pedantic:tn},Se={normal:At,gfm:ct,breaks:Pn,pedantic:$n},Tn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},cs=t=>Tn[t];function H(t,e){if(e){if(R.escapeTest.test(t))return t.replace(R.escapeReplace,cs)}else if(R.escapeTestNoEncode.test(t))return t.replace(R.escapeReplaceNoEncode,cs);return t}function ds(t){try{t=encodeURI(t).replace(R.percentDecode,"%")}catch{return null}return t}function ps(t,e){let s=t.replace(R.findPipe,(o,n,a)=>{let c=!1,l=n;for(;--l>=0&&a[l]==="\\";)c=!c;return c?"|":" |"}),i=s.split(R.splitPipe),r=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;r<i.length;r++)i[r]=i[r].trim().replace(R.slashPipe,"|");return i}function X(t,e,s){let i=t.length;if(i===0)return"";let r=0;for(;r<i&&t.charAt(i-r-1)===e;)r++;return t.slice(0,i-r)}function hs(t){let e=t.split(`
369
+ `),s=e.length-1;for(;s>=0&&R.blankLine.test(e[s]);)s--;return e.length-s<=2?t:e.slice(0,s+1).join(`
370
+ `)}function Cn(t,e){if(t.indexOf(e[1])===-1)return-1;let s=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])s++;else if(t[i]===e[1]&&(s--,s<0))return i;return s>0?-2:-1}function An(t,e=0){let s=e,i="";for(let r of t)if(r===" "){let o=4-s%4;i+=" ".repeat(o),s+=o}else i+=r,s++;return i}function us(t,e,s,i,r){let o=e.href,n=e.title||null,a=t[1].replace(r.other.outputLinkReplace,"$1");i.state.inLink=!0;let c={type:t[0].charAt(0)==="!"?"image":"link",raw:s,href:o,title:n,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,c}function _n(t,e,s){let i=t.match(s.other.indentCodeCompensation);if(i===null)return e;let r=i[1];return e.split(`
371
+ `).map(o=>{let n=o.match(s.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
372
+ `)}var Be=class{options;rules;lexer;constructor(t){this.options=t||ce}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let s=this.options.pedantic?e[0]:hs(e[0]),i=s.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:s,codeBlockStyle:"indented",text:i}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let s=e[0],i=_n(s,e[3]||"",this.rules);return{type:"code",raw:s,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let s=e[2].trim();if(this.rules.other.endingHash.test(s)){let i=X(s,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(s=i.trim())}return{type:"heading",raw:X(e[0],`
373
+ `),depth:e[1].length,text:s,tokens:this.lexer.inline(s)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:X(e[0],`
374
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let s=X(e[0],`
375
+ `).split(`
376
+ `),i="",r="",o=[];for(;s.length>0;){let n=!1,a=[],c;for(c=0;c<s.length;c++)if(this.rules.other.blockquoteStart.test(s[c]))a.push(s[c]),n=!0;else if(!n)a.push(s[c]);else break;s=s.slice(c);let l=a.join(`
377
+ `),h=l.replace(this.rules.other.blockquoteSetextReplace,`
378
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
379
+ ${l}`:l,r=r?`${r}
380
+ ${h}`:h;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,o,!0),this.lexer.state.top=d,s.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,x=m.raw+`
381
+ `+s.join(`
382
+ `),V=this.blockquote(x);o[o.length-1]=V,i=i.substring(0,i.length-m.raw.length)+V.raw,r=r.substring(0,r.length-m.text.length)+V.text;break}else if(f?.type==="list"){let m=f,x=m.raw+`
383
+ `+s.join(`
384
+ `),V=this.list(x);o[o.length-1]=V,i=i.substring(0,i.length-f.raw.length)+V.raw,r=r.substring(0,r.length-m.raw.length)+V.raw,s=x.substring(o.at(-1).raw.length).split(`
385
+ `);continue}}return{type:"blockquote",raw:i,tokens:o,text:r}}}list(t){let e=this.rules.block.list.exec(t);if(e){let s=e[1].trim(),i=s.length>1,r={type:"list",raw:"",ordered:i,start:i?+s.slice(0,-1):"",loose:!1,items:[]};s=i?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=i?s:"[*+-]");let o=this.rules.other.listItemRegex(s),n=!1;for(;t;){let c=!1,l="",h="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;l=e[0],t=t.substring(l.length);let d=An(e[2].split(`
386
+ `,1)[0],e[1].length),f=t.split(`
387
+ `,1)[0],m=!d.trim(),x=0;if(this.options.pedantic?(x=2,h=d.trimStart()):m?x=e[1].length+1:(x=d.search(this.rules.other.nonSpaceChar),x=x>4?1:x,h=d.slice(x),x+=e[1].length),m&&this.rules.other.blankLine.test(f)&&(l+=f+`
388
+ `,t=t.substring(f.length+1),c=!0),!c){let V=this.rules.other.nextBulletRegex(x),It=this.rules.other.hrRegex(x),Rt=this.rules.other.fencesBeginRegex(x),Mt=this.rules.other.headingBeginRegex(x),Vs=this.rules.other.htmlBeginRegex(x),Zs=this.rules.other.blockquoteBeginRegex(x);for(;t;){let tt=t.split(`
389
+ `,1)[0],ye;if(f=tt,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),ye=f):ye=f.replace(this.rules.other.tabCharGlobal," "),Rt.test(f)||Mt.test(f)||Vs.test(f)||Zs.test(f)||V.test(f)||It.test(f))break;if(ye.search(this.rules.other.nonSpaceChar)>=x||!f.trim())h+=`
390
+ `+ye.slice(x);else{if(m||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Rt.test(d)||Mt.test(d)||It.test(d))break;h+=`
391
+ `+f}m=!f.trim(),l+=tt+`
392
+ `,t=t.substring(tt.length+1),d=ye.slice(x)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(n=!0)),r.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),r.raw+=l}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(c.raw);if(h){let d={type:"checkbox",raw:h[0]+" ",checked:h[0]!=="[ ]"};c.checked=d.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1);if(!r.loose){let h=c.tokens.filter(f=>f.type==="space"),d=h.length>0&&h.some(f=>this.rules.other.anyLine.test(f.raw));r.loose=d}}if(r.loose)for(let c of r.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return r}}html(t){let e=this.rules.block.html.exec(t);if(e){let s=hs(e[0]);return{type:"html",block:!0,raw:s,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:s}}}def(t){let e=this.rules.block.def.exec(t);if(e){let s=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:s,raw:X(e[0],`
393
+ `),href:i,title:r}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let s=ps(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
394
+ `):[],o={type:"table",raw:X(e[0],`
395
+ `),header:[],align:[],rows:[]};if(s.length===i.length){for(let n of i)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<s.length;n++)o.header.push({text:s[n],tokens:this.lexer.inline(s[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(ps(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let s=e[1].trim();return{type:"heading",raw:X(e[0],`
396
+ `),depth:e[2].charAt(0)==="="?1:2,text:s,tokens:this.lexer.inline(s)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let s=e[1].charAt(e[1].length-1)===`
397
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:s,tokens:this.lexer.inline(s)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let s=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let o=X(s.slice(0,-1),"\\");if((s.length-o.length)%2===0)return}else{let o=Cn(e[2],"()");if(o===-2)return;if(o>-1){let n=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,n).trim(),e[3]=""}}let i=e[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(i);o&&(i=o[1],r=o[3])}else r=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?i=i.slice(1):i=i.slice(1,-1)),us(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let s;if((s=this.rules.inline.reflink.exec(t))||(s=this.rules.inline.nolink.exec(t))){let i=(s[2]||s[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=e[i.toLowerCase()];if(!r){let o=s[0].charAt(0);return{type:"text",raw:o,text:o}}return us(s,r,s[0],this.lexer,this.rules)}}emStrong(t,e,s=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&s.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!s||this.rules.inline.punctuation.exec(s))){let r=[...i[0]].length-1,o,n,a=r,c=0,l=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,e=e.slice(-1*t.length+r);(i=l.exec(e))!==null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o)continue;if(n=[...o].length,i[3]||i[4]){a+=n;continue}else if((i[5]||i[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let h=[...i[0]][0].length,d=t.slice(0,r+i.index+h+n);if(Math.min(r,n)%2){let m=d.slice(1,-1);return{type:"em",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}let f=d.slice(2,-2);return{type:"strong",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let s=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(s),r=this.rules.other.startingSpaceChar.test(s)&&this.rules.other.endingSpaceChar.test(s);return i&&r&&(s=s.substring(1,s.length-1)),{type:"codespan",raw:e[0],text:s}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,s=""){let i=this.rules.inline.delLDelim.exec(t);if(i&&(!i[1]||!s||this.rules.inline.punctuation.exec(s))){let r=[...i[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,e=e.slice(-1*t.length+r);(i=c.exec(e))!==null;){if(o=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!o||(n=[...o].length,n!==r))continue;if(i[3]||i[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let l=[...i[0]][0].length,h=t.slice(0,r+i.index+l+n),d=h.slice(r,-r);return{type:"del",raw:h,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let s,i;return e[2]==="@"?(s=e[1],i="mailto:"+s):(s=e[1],i=s),{type:"link",raw:e[0],text:s,href:i,tokens:[{type:"text",raw:s,text:s}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let s,i;if(e[2]==="@")s=e[0],i="mailto:"+s;else{let r;do r=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(r!==e[0]);s=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:s,href:i,tokens:[{type:"text",raw:s,text:s}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let s=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:s}}}},q=class dt{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ce,this.options.tokenizer=this.options.tokenizer||new Be,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 s={other:R,block:je.normal,inline:Se.normal};this.options.pedantic?(s.block=je.pedantic,s.inline=Se.pedantic):this.options.gfm&&(s.block=je.gfm,this.options.breaks?s.inline=Se.breaks:s.inline=Se.gfm),this.tokenizer.rules=s}static get rules(){return{block:je,inline:Se}}static lex(e,s){return new dt(s).lex(e)}static lexInline(e,s){return new dt(s).inlineTokens(e)}lex(e){e=e.replace(R.carriageReturn,`
398
+ `),this.blockTokens(e,this.tokens);for(let s=0;s<this.inlineQueue.length;s++){let i=this.inlineQueue[s];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,s=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(R.tabCharGlobal," ").replace(R.spaceLine,""));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,s))?(e=e.substring(o.raw.length),s.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=s.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
399
+ `:s.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let a=s.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
400
+ `)?"":`
401
+ `)+o.raw,a.text+=`
402
+ `+o.text,this.inlineQueue.at(-1).src=a.text):s.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let a=s.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
403
+ `)?"":`
404
+ `)+o.raw,a.text+=`
405
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},s.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),s.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),s.push(o);continue}let n=e;if(this.options.extensions?.startBlock){let a=1/0,c=e.slice(1),l;this.options.extensions.startBlock.forEach(h=>{l=h.call({lexer:this},c),typeof l=="number"&&l>=0&&(a=Math.min(a,l))}),a<1/0&&a>=0&&(n=e.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=s.at(-1);i&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
406
+ `)?"":`
407
+ `)+o.raw,a.text+=`
408
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):s.push(o),i=n.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let a=s.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
409
+ `)?"":`
410
+ `)+o.raw,a.text+=`
411
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):s.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,s}inline(e,s=[]){return this.inlineQueue.push({src:e,tokens:s}),s}inlineTokens(e,s=[]){this.tokenizer.lexer=this;let i=e,r=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(i))!==null;)l.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(i))!==null;)i=i.slice(0,r.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(i))!==null;)o=r[2]?r[2].length:0,i=i.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",c=1/0;for(;e;){if(e.length<c)c=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(a=""),n=!1;let l;if(this.options.extensions?.inline?.some(d=>(l=d.call({lexer:this},e,s))?(e=e.substring(l.raw.length),s.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let d=s.at(-1);l.type==="text"&&d?.type==="text"?(d.raw+=l.raw,d.text+=l.text):s.push(l);continue}if(l=this.tokenizer.emStrong(e,i,a)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.del(e,i,a)){e=e.substring(l.raw.length),s.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),s.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),s.push(l);continue}let h=e;if(this.options.extensions?.startInline){let d=1/0,f=e.slice(1),m;this.options.extensions.startInline.forEach(x=>{m=x.call({lexer:this},f),typeof m=="number"&&m>=0&&(d=Math.min(d,m))}),d<1/0&&d>=0&&(h=e.substring(0,d+1))}if(l=this.tokenizer.inlineText(h)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(a=l.raw.slice(-1)),n=!0;let d=s.at(-1);d?.type==="text"?(d.raw+=l.raw,d.text+=l.text):s.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return s}infiniteLoopError(e){let s="Infinite loop on byte: "+e;if(this.options.silent)console.error(s);else throw new Error(s)}},He=class{options;parser;constructor(t){this.options=t||ce}space(t){return""}code({text:t,lang:e,escaped:s}){let i=(e||"").match(R.notSpaceStart)?.[0],r=t.replace(R.endingNewline,"")+`
412
+ `;return i?'<pre><code class="language-'+H(i)+'">'+(s?r:H(r,!0))+`</code></pre>
413
+ `:"<pre><code>"+(s?r:H(r,!0))+`</code></pre>
414
+ `}blockquote({tokens:t}){return`<blockquote>
415
+ ${this.parser.parse(t)}</blockquote>
416
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
417
+ `}hr(t){return`<hr>
418
+ `}list(t){let e=t.ordered,s=t.start,i="";for(let n=0;n<t.items.length;n++){let a=t.items[n];i+=this.listitem(a)}let r=e?"ol":"ul",o=e&&s!==1?' start="'+s+'"':"";return"<"+r+o+`>
419
+ `+i+"</"+r+`>
420
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
421
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
422
+ `}table(t){let e="",s="";for(let r=0;r<t.header.length;r++)s+=this.tablecell(t.header[r]);e+=this.tablerow({text:s});let i="";for(let r=0;r<t.rows.length;r++){let o=t.rows[r];s="";for(let n=0;n<o.length;n++)s+=this.tablecell(o[n]);i+=this.tablerow({text:s})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
423
+ <thead>
424
+ `+e+`</thead>
425
+ `+i+`</table>
426
+ `}tablerow({text:t}){return`<tr>
427
+ ${t}</tr>
428
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),s=t.header?"th":"td";return(t.align?`<${s} align="${t.align}">`:`<${s}>`)+e+`</${s}>
429
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${H(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:s}){let i=this.parser.parseInline(s),r=ds(t);if(r===null)return i;t=r;let o='<a href="'+t+'"';return e&&(o+=' title="'+H(e)+'"'),o+=">"+i+"</a>",o}image({href:t,title:e,text:s,tokens:i}){i&&(s=this.parser.parseInline(i,this.parser.textRenderer));let r=ds(t);if(r===null)return H(s);t=r;let o=`<img src="${t}" alt="${H(s)}"`;return e&&(o+=` title="${H(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:H(t.text)}},_t=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},W=class pt{options;renderer;textRenderer;constructor(e){this.options=e||ce,this.options.renderer=this.options.renderer||new He,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _t}static parse(e,s){return new pt(s).parse(e)}static parseInline(e,s){return new pt(s).parseInline(e)}parse(e){this.renderer.parser=this;let s="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let n=r,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){s+=a||"";continue}}let o=r;switch(o.type){case"space":{s+=this.renderer.space(o);break}case"hr":{s+=this.renderer.hr(o);break}case"heading":{s+=this.renderer.heading(o);break}case"code":{s+=this.renderer.code(o);break}case"table":{s+=this.renderer.table(o);break}case"blockquote":{s+=this.renderer.blockquote(o);break}case"list":{s+=this.renderer.list(o);break}case"checkbox":{s+=this.renderer.checkbox(o);break}case"html":{s+=this.renderer.html(o);break}case"def":{s+=this.renderer.def(o);break}case"paragraph":{s+=this.renderer.paragraph(o);break}case"text":{s+=this.renderer.text(o);break}default:{let n='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return s}parseInline(e,s=this.renderer){this.renderer.parser=this;let i="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){i+=a||"";continue}}let n=o;switch(n.type){case"escape":{i+=s.text(n);break}case"html":{i+=s.html(n);break}case"link":{i+=s.link(n);break}case"image":{i+=s.image(n);break}case"checkbox":{i+=s.checkbox(n);break}case"strong":{i+=s.strong(n);break}case"em":{i+=s.em(n);break}case"codespan":{i+=s.codespan(n);break}case"br":{i+=s.br(n);break}case"del":{i+=s.del(n);break}case"text":{i+=s.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return i}},ve=class{options;block;constructor(t){this.options=t||ce}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?q.lex:q.lexInline}provideParser(t=this.block){return t?W.parse:W.parseInline}},En=class{defaults=kt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=W;Renderer=He;TextRenderer=_t;Lexer=q;Tokenizer=Be;Hooks=ve;constructor(...t){this.use(...t)}walkTokens(t,e){let s=[];for(let i of t)switch(s=s.concat(e.call(this,i)),i.type){case"table":{let r=i;for(let o of r.header)s=s.concat(this.walkTokens(o.tokens,e));for(let o of r.rows)for(let n of o)s=s.concat(this.walkTokens(n.tokens,e));break}case"list":{let r=i;s=s.concat(this.walkTokens(r.items,e));break}default:{let r=i;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);s=s.concat(this.walkTokens(n,e))}):r.tokens&&(s=s.concat(this.walkTokens(r.tokens,e)))}}return s}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(s=>{let i={...s};if(i.async=this.defaults.async||i.async||!1,s.extensions&&(s.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=e.renderers[r.name];o?e.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[r.level];o?o.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),i.extensions=e),s.renderer){let r=this.defaults.renderer||new He(this.defaults);for(let o in s.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=s.renderer[n],c=r[n];r[n]=(...l)=>{let h=a.apply(r,l);return h===!1&&(h=c.apply(r,l)),h||""}}i.renderer=r}if(s.tokenizer){let r=this.defaults.tokenizer||new Be(this.defaults);for(let o in s.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=s.tokenizer[n],c=r[n];r[n]=(...l)=>{let h=a.apply(r,l);return h===!1&&(h=c.apply(r,l)),h}}i.tokenizer=r}if(s.hooks){let r=this.defaults.hooks||new ve;for(let o in s.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=s.hooks[n],c=r[n];ve.passThroughHooks.has(o)?r[n]=l=>{if(this.defaults.async&&ve.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await a.call(r,l);return c.call(r,d)})();let h=a.call(r,l);return c.call(r,h)}:r[n]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(r,l);return d===!1&&(d=await c.apply(r,l)),d})();let h=a.apply(r,l);return h===!1&&(h=c.apply(r,l)),h}}i.hooks=r}if(s.walkTokens){let r=this.defaults.walkTokens,o=s.walkTokens;i.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return q.lex(t,e??this.defaults)}parser(t,e){return W.parse(t,e??this.defaults)}parseMarkdown(t){return(e,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new 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 e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=t),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(e):e,a=await(r.hooks?await r.hooks.provideLexer(t):t?q.lex:q.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let l=await(r.hooks?await r.hooks.provideParser(t):t?W.parse:W.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(l):l})().catch(o);try{r.hooks&&(e=r.hooks.preprocess(e));let n=(r.hooks?r.hooks.provideLexer(t):t?q.lex:q.lexInline)(e,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(t):t?W.parse:W.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(t,e){return s=>{if(s.message+=`
430
+ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+H(s.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(s);throw s}}},ae=new En;function y(t,e){return ae.parse(t,e)}y.options=y.setOptions=function(t){return ae.setOptions(t),y.defaults=ae.defaults,Os(y.defaults),y};y.getDefaults=kt;y.defaults=ce;y.use=function(...t){return ae.use(...t),y.defaults=ae.defaults,Os(y.defaults),y};y.walkTokens=function(t,e){return ae.walkTokens(t,e)};y.parseInline=ae.parseInline;y.Parser=W;y.parser=W.parse;y.Renderer=He;y.TextRenderer=_t;y.Lexer=q;y.lexer=q.lex;y.Tokenizer=Be;y.Hooks=ve;y.parse=y;y.options;y.setOptions;y.use;y.walkTokens;y.parseInline;W.parse;q.lex;const Gs=new y.Renderer;Gs.html=({text:t})=>Rn(t);function In(t){const e=y.parse(t,{async:!1,breaks:!0,gfm:!0,renderer:Gs});return Mn(e)}function Rn(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Mn(t){const e=document.createElement("template");return e.innerHTML=t,e.content.querySelectorAll("script, style, iframe, object, embed").forEach(s=>{s.remove()}),e.content.querySelectorAll("*").forEach(s=>{for(const i of[...s.attributes]){const r=i.name.toLowerCase();r.startsWith("on")&&s.removeAttribute(i.name),(r==="href"||r==="src")&&!Dn(i.value)&&s.removeAttribute(i.name)}s.tagName==="A"&&(s.setAttribute("target","_blank"),s.setAttribute("rel","noreferrer noopener"))}),e.innerHTML}function Dn(t){if(t.startsWith("#")||t.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(t).protocol)}catch{return!1}}var jn=Object.defineProperty,On=Object.getOwnPropertyDescriptor,Ks=(t,e,s,i)=>{for(var r=i>1?void 0:i?On(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&jn(e,s,r),r};let Ge=class extends I{constructor(){super(...arguments),this.text="",this.onFormattedClick=t=>{if(!(t.target instanceof HTMLButtonElement)||!t.target.classList.contains("code-copy-button"))return;const e=t.target.closest(".code-block-wrapper");if(!(e instanceof HTMLElement))return;const s=e.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t.target)}}render(){return p`<div class="formatted" @click=${this.onFormattedClick}>${Wo(In(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(t=>{if(!(t instanceof HTMLPreElement)||t.parentElement?.classList.contains("code-block-wrapper")===!0||!(t.querySelector("code")instanceof HTMLElement))return;const s=document.createElement("div");s.className="code-block-wrapper";const i=document.createElement("button");i.type="button",i.className="code-copy-button",i.textContent="Copy",i.setAttribute("aria-label","Copy code block"),t.before(s),s.append(t,i)})}async copyCode(t,e){const s=await zn(t);e.textContent=s?"Copied":"Failed",window.setTimeout(()=>{e.textContent="Copy"},1200)}};Ge.styles=$o;Ks([u()],Ge.prototype,"text",2);Ge=Ks([z("formatted-text")],Ge);async function zn(t){try{return await navigator.clipboard.writeText(t),!0}catch{return!1}}var Ln=Object.defineProperty,Un=Object.getOwnPropertyDescriptor,_=(t,e,s,i)=>{for(var r=i>1?void 0:i?Un(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Ln(e,s,r),r};function Nn(t){return typeof t=="object"&&t!==null&&"index"in t&&"offset"in t&&typeof t.index=="number"&&typeof t.offset=="number"}let P=class extends I{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.openGroupKeys=new Set,this.loadedScrollPercent=100,this.suppressScrollSave=!1,this.lastScrollTop=0}disconnectedCallback(){window.clearTimeout(this.saveScrollTimer),super.disconnectedCallback()}willUpdate(t){t.has("sessionId")&&(this.openGroupKeys=this.readOpenGroupKeys()),t.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&this.isNearBottom())}updated(t){t.has("sessionId")||(t.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),this.updateLoadedScrollPercent())}render(){return p`
431
+ <div class="chat-wrap">
432
+ ${this.renderHistoryIndicator()}
433
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
434
+ ${this.renderHistoryBoundary()}
435
+ ${zo(this.messages,this.messageStart).map(t=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex))}
436
+ ${this.renderSessionActivity()}
437
+ </div>
438
+ ${this.renderActivityDock()}
439
+ </div>
440
+ `}renderActivityDock(){const t=this.activityState();if(t===void 0)return null;const e=t!=="idle"||this.activity?.phase==="active";return p`
441
+ <div class=${e?"activity-dock active":"activity-dock"} aria-live="polite">
442
+ <span class="dot"></span>
443
+ <span class="activity-text">${this.activityText(t)}</span>
444
+ </div>
445
+ `}renderSessionActivity(){return this.isReceivingPartialStream?p`
446
+ <aside class="session-activity receiving" aria-live="polite">
447
+ <strong>Receiving answer…</strong>
448
+ <span>This session was reconnected mid-response. The answer will appear when complete.</span>
449
+ </aside>
450
+ `:this.isCompacting?p`
451
+ <aside class="session-activity compacting" aria-live="polite">
452
+ <strong>Compacting history…</strong>
453
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
454
+ ${this.pendingMessageCount>0?p`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
455
+ </aside>
456
+ `:null}activityState(){const t=this.status;return t===void 0?this.activity?.label:t.isCompacting?"compacting":t.isBashRunning?"bash":t.isStreaming?"running":t.pendingMessageCount>0?"queued":"idle"}activityText(t){const e=this.activity;return e===void 0||t!=="idle"&&e.phase==="idle"?t:e.detail!==void 0&&e.detail!==""?`${e.label}: ${e.detail}`:e.label}renderHistoryIndicator(){if(!this.messages.length||this.messageTotal<=0)return null;const t=this.messages.length,e=Math.min(100,Math.round(t/this.messageTotal*100)),s=this.messageStart,i=s<=0?"full history loaded":`${String(s)} older not loaded · ${String(e)}% loaded`;return p`
457
+ <div class="history-indicator">
458
+ <div>${i}</div>
459
+ <div>loaded scroll: ${String(this.loadedScrollPercent)}% from top</div>
460
+ </div>
461
+ `}renderHistoryBoundary(){const t=this.historyRangeLabel();return this.loadingMore?p`<div class="history-boundary"><span>Loading earlier messages…</span>${t}</div>`:this.hasMore?p`<div class="history-boundary"><span>Scroll up to load earlier messages</span>${t}</div>`:this.messages.length?p`<div class="history-boundary"><span>Beginning of session</span>${t}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const t=this.messageStart+1,e=this.messageStart+this.messages.length;return p`<small>Showing messages ${t}–${e} of ${this.messageTotal}</small>`}renderMessage(t,e){return p`
462
+ <article class="msg ${t.role}" data-index=${e}>
463
+ ${this.renderMessageHeader(t,String(e))}
464
+ ${t.parts.map(s=>this.renderPart(s,t))}
465
+ </article>
466
+ `}renderMessageGroup(t,e){const s=this.groupKey(e);return p`
467
+ <details class="msg event-group" data-index=${e} ?open=${this.openGroupKeys.has(s)} @toggle=${i=>{this.onGroupToggle(s,i)}}>
468
+ <summary>
469
+ <b class="label">events</b>
470
+ <span>${Lo(t)}</span>
471
+ </summary>
472
+ <div class="group-body">
473
+ ${t.map((i,r)=>p`
474
+ <section class="group-msg ${i.role}">
475
+ ${this.renderMessageHeader(i,`${String(e)}:${String(r)}`)}
476
+ ${i.parts.map(o=>this.renderPart(o,i))}
477
+ </section>
478
+ `)}
479
+ </div>
480
+ </details>
481
+ `}renderMessageHeader(t,e){const s=this.messageMetaLabel(t),i=this.expandedMetaKey===e;return p`
482
+ <div class="msg-header">
483
+ <b class="label">${t.role}</b>
484
+ <div class="msg-header-trailing">
485
+ ${this.renderMessageActions(t,e)}
486
+ <span class=${i?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${s.full} aria-label=${s.full} aria-expanded=${String(i)} @click=${()=>{this.expandedMetaKey=i?void 0:e}} @keydown=${r=>{this.onMetaKeydown(r,e,i)}}>${s.short}</span>
487
+ </div>
488
+ </div>
489
+ `}renderMessageActions(t,e){if(!this.isCopyableMessage(t))return null;const s=this.copiedMessageKey===e;return p`
490
+ <div class="msg-actions" aria-label="Message actions">
491
+ <button type="button" class="msg-action" title=${s?"Copied":"Copy message"} aria-label=${`${s?"Copied":"Copy"} ${t.role} message`} @click=${i=>{this.copyMessage(t,e,i)}}>
492
+ <span aria-hidden="true">${s?"✓":"⧉"}</span>
493
+ </button>
494
+ </div>
495
+ `}onMetaKeydown(t,e,s){t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),this.expandedMetaKey=s?void 0:e)}isCopyableMessage(t){return(t.role==="user"||t.role==="assistant")&&this.messageCopyText(t)!==""}messageCopyText(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text.trim()).filter(e=>e!=="").join(`
496
+
497
+ `)}async copyMessage(t,e,s){s.stopPropagation(),await this.writeClipboard(this.messageCopyText(t))&&(this.copiedMessageKey=e,window.setTimeout(()=>{this.copiedMessageKey===e&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(t){try{return await navigator.clipboard.writeText(t),!0}catch{return!1}}messageMetaLabel(t){const e=t.meta?.timestamp,s=this.modelLabel(t);if(e===void 0&&s===void 0)return{short:"no info",full:"No Pi message metadata available"};const i=e===void 0?void 0:this.formatTimestamp(e),r=[i?.short,s].filter(n=>n!==void 0&&n!==""),o=[i?.full,s===void 0?void 0:`Model: ${s}`].filter(n=>n!==void 0&&n!=="");return{short:r.join(" · "),full:o.join(" · ")}}formatTimestamp(t){const e=new Date(t);if(Number.isFinite(e.getTime()))return{short:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(e),full:new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}).format(e)}}modelLabel(t){const e=t.meta?.model;if(e===void 0)return;const s=e.responseId??e.id;return s===void 0||s===""?e.provider:e.provider!==void 0&&e.provider!==""?`${e.provider}/${s}`:s}renderPart(t,e){return t.type==="text"&&e?.role==="bash"?p`<pre class="part shell-output">${t.text}</pre>`:t.type==="text"?p`<formatted-text class="part" .text=${t.text}></formatted-text>`:t.type==="thinking"?p`<details class="part"><summary>thinking</summary><formatted-text .text=${t.text}></formatted-text></details>`:t.type==="skillInvocation"?p`
498
+ <details class="part skill-invocation">
499
+ <summary><b>[skill]</b> ${t.name}</summary>
500
+ <small>${t.location}</small>
501
+ <formatted-text .text=${t.content}></formatted-text>
502
+ </details>
503
+ `:t.type==="toolCall"?p`<div class="part tool-line">▶ ${t.toolName}<span class="summary">${t.summary}</span></div>`:t.type==="toolResult"?p`
504
+ <details class="part" ?open=${t.isError}>
505
+ <summary>${t.isError?"✖":"✓"} ${t.toolName} result</summary>
506
+ <formatted-text .text=${t.text}></formatted-text>
507
+ </details>
508
+ `:null}onGroupToggle(t,e){const s=e.currentTarget;if(!(s instanceof HTMLDetailsElement))return;const i=new Set(this.openGroupKeys);s.open?i.add(t):i.delete(t),this.openGroupKeys=i,this.saveOpenGroupKeys()}onScroll(){this.updateLoadedScrollPercent(),this.chat&&this.chat.scrollTop<64&&this.hasMore&&!this.loadingMore&&this.onLoadMore?.(),this.updatePinnedToBottomFromScroll(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(t){t.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(t){this.touchStartY=t.touches[0]?.clientY}onTouchMove(t){const e=t.touches[0]?.clientY;this.touchStartY!==void 0&&e!==void 0&&e>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const t=this.chat;if(!t)return;const e=t.scrollTop<this.lastScrollTop;this.isAtBottom()?this.pinnedToBottom=!0:e?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=t.scrollTop}updateLoadedScrollPercent(){const t=this.chat;if(!t)return;const e=t.scrollHeight-t.clientHeight,s=e<=0?100:Math.round(t.scrollTop/e*100);this.loadedScrollPercent=Math.max(0,Math.min(100,s))}isNearBottom(){const t=this.chat;return t?this.distanceFromBottom(t)<48:!0}isAtBottom(){const t=this.chat;return t?this.distanceFromBottom(t)<2:!0}canScrollUp(){const t=this.chat;return t!==void 0&&t.scrollTop>0}distanceFromBottom(t){return t.scrollHeight-t.scrollTop-t.clientHeight}scrollToBottom(){requestAnimationFrame(()=>{const t=this.chat;t&&this.withSuppressedScrollSave(()=>{t.scrollTop=t.scrollHeight,this.lastScrollTop=t.scrollTop})})}restoreScrollPosition(){requestAnimationFrame(()=>{const t=this.chat,e=this.readStoredScrollPosition();if(!t||!e){this.withSuppressedScrollSave(()=>{t&&(t.scrollTop=t.scrollHeight,this.lastScrollTop=t.scrollTop)});return}const s=this.articleAt(e.index);if(!s){this.withSuppressedScrollSave(()=>{t.scrollTop=t.scrollHeight,this.lastScrollTop=t.scrollTop});return}this.withSuppressedScrollSave(()=>{const i=t.getBoundingClientRect().top,r=s.getBoundingClientRect().top-i;t.scrollTop+=r-e.offset,this.lastScrollTop=t.scrollTop})})}capturePrependScrollAnchor(){const t=this.chat;if(t)return{scrollTop:t.scrollTop,scrollHeight:t.scrollHeight}}restorePrependScrollAnchor(t){const e=this.chat;!e||!t||(this.withSuppressedScrollSave(()=>{e.scrollTop=t.scrollTop+(e.scrollHeight-t.scrollHeight),this.lastScrollTop=e.scrollTop}),this.updateLoadedScrollPercent())}saveScrollPosition(t=this.sessionId){const e=this.chat;if(!(!e||!t))try{if(this.isNearBottom()){localStorage.removeItem(this.storageKey(t));return}const s=this.firstVisibleArticle();if(!s){localStorage.removeItem(this.storageKey(t));return}const i=e.getBoundingClientRect().top,r={index:Number(s.dataset.index??0),offset:s.getBoundingClientRect().top-i};localStorage.setItem(this.storageKey(t),JSON.stringify(r))}catch{}}scheduleScrollPositionSave(){window.clearTimeout(this.saveScrollTimer),this.saveScrollTimer=window.setTimeout(()=>{this.saveScrollPosition()},180)}readStoredScrollPosition(){if(this.sessionId!=="")try{const t=localStorage.getItem(this.storageKey());if(t===null||t==="")return;const e=JSON.parse(t);return Nn(e)?e:void 0}catch{return}}firstVisibleArticle(){const t=this.chat;if(!t)return;const e=t.getBoundingClientRect();return this.articles().find(s=>{const i=s.getBoundingClientRect();return i.bottom>=e.top&&i.top<=e.bottom})}articleAt(t){return this.articles().find(e=>Number(e.dataset.index)===t)}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}withSuppressedScrollSave(t){this.suppressScrollSave=!0,t(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}storageKey(t=this.sessionId){return`pi-web:chat-scroll:${t}`}groupStorageKey(t=this.sessionId){return`pi-web:chat-groups:${t}`}groupKey(t){return`${this.sessionId}:${String(t)}`}readOpenGroupKeys(){if(this.sessionId==="")return new Set;try{const t=localStorage.getItem(this.groupStorageKey()),e=t!==null&&t!==""?JSON.parse(t):[];return new Set(Array.isArray(e)?e.filter(s=>typeof s=="string"):[])}catch{return new Set}}saveOpenGroupKeys(){if(this.sessionId!=="")try{localStorage.setItem(this.groupStorageKey(),JSON.stringify([...this.openGroupKeys]))}catch{}}};P.styles=vo;_([u({attribute:!1})],P.prototype,"messages",2);_([u()],P.prototype,"sessionId",2);_([u({type:Number})],P.prototype,"messageStart",2);_([u({type:Number})],P.prototype,"messageTotal",2);_([u({type:Boolean})],P.prototype,"hasMore",2);_([u({type:Boolean})],P.prototype,"loadingMore",2);_([u({type:Boolean})],P.prototype,"isReceivingPartialStream",2);_([u({type:Boolean})],P.prototype,"isCompacting",2);_([u({type:Number})],P.prototype,"pendingMessageCount",2);_([u({attribute:!1})],P.prototype,"status",2);_([u({attribute:!1})],P.prototype,"activity",2);_([u({attribute:!1})],P.prototype,"onLoadMore",2);_([me(".chat")],P.prototype,"chat",2);_([$()],P.prototype,"pinnedToBottom",2);_([$()],P.prototype,"openGroupKeys",2);_([$()],P.prototype,"loadedScrollPercent",2);_([$()],P.prototype,"expandedMetaKey",2);_([$()],P.prototype,"copiedMessageKey",2);P=_([z("chat-view")],P);var qn=Object.defineProperty,Wn=Object.getOwnPropertyDescriptor,Ye=(t,e,s,i)=>{for(var r=i>1?void 0:i?Wn(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&qn(e,s,r),r};let fe=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?p`
509
+ <div class="menu">
510
+ ${this.items.map((t,e)=>p`
511
+ <button class=${e===this.selectedIndex?"selected":""} @mousedown=${s=>{s.preventDefault(),this.onPick?.(t)}}>
512
+ <strong>${t.insertText}</strong>
513
+ <span>${t.detail}</span>
514
+ ${t.description!==void 0&&t.description!==""?p`<small>${t.description}</small>`:null}
515
+ </button>
516
+ `)}
517
+ </div>
518
+ `:null}};fe.styles=To;Ye([u({attribute:!1})],fe.prototype,"items",2);Ye([u({type:Number})],fe.prototype,"selectedIndex",2);Ye([u({attribute:!1})],fe.prototype,"onPick",2);fe=Ye([z("autocomplete-menu")],fe);var Fn=Object.defineProperty,Bn=Object.getOwnPropertyDescriptor,U=(t,e,s,i)=>{for(var r=i>1?void 0:i?Bn(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Fn(e,s,r),r};let j=class extends I{constructor(){super(...arguments),this.disabled=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0}willUpdate(t){if(!t.has("sessionId"))return;const e=t.get("sessionId");e!==void 0&&e!==""&&rt(e,this.draft),this.draft=this.sessionId!==void 0&&this.sessionId!==""?Zn(this.sessionId):"",this.completions=[],this.selectedIndex=0}updated(t){(t.has("draft")||t.has("sessionId"))&&this.resizeTextarea()}render(){const t=Ps(this.draft),e=t.kind==="shell",s=this.canSteer||this.isCompacting;return p`
519
+ <footer class=${e?"shell-mode":""}>
520
+ <div class="editor-wrap">
521
+ <textarea
522
+ .value=${this.draft}
523
+ ?disabled=${this.disabled}
524
+ @input=${i=>{i.target instanceof HTMLTextAreaElement&&this.updateDraft(i.target.value)}}
525
+ @keydown=${i=>{this.handleKeyDown(i)}}
526
+ placeholder="Message pi... Use / for commands, @ for files"
527
+ ></textarea>
528
+ ${e?p`<div class="mode-hint">Shell command${t.excludeFromContext?" · excluded from context":""}</div>`:null}
529
+ ${this.isCompacting&&!e?p`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
530
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${i=>{this.pick(i)}}></autocomplete-menu>
531
+ </div>
532
+ <div class="actions">
533
+ <button ?disabled=${this.disabled} title=${s?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${s?"Queue":"Send"}</button>
534
+ ${this.canSteer&&!this.isCompacting?p`<button ?disabled=${this.disabled} title="Steer the current response before the next model call" @click=${()=>{this.send("steer")}}>Steer</button>`:null}
535
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</button>
536
+ </div>
537
+ </footer>
538
+ `}focusInput(){this.textarea?.focus()}resizeTextarea(){const t=this.textarea;t&&(t.style.height="auto",t.style.height=`${String(t.scrollHeight)}px`)}updateDraft(t){this.draft=t,this.sessionId!==void 0&&this.sessionId!==""&&rt(this.sessionId,this.draft),this.refreshCompletions()}async refreshCompletions(){const t=this.currentTrigger(),e=++this.requestVersion;if(this.selectedIndex=0,t===void 0){this.completions=[];return}if(t.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const s=await w.commands(this.sessionId).catch(Gn);if(e!==this.requestVersion)return;this.completions=s.filter(i=>i.name.toLowerCase().includes(t.query.toLowerCase())).slice(0,12).map(i=>({kind:"command",replaceFrom:t.from,replaceTo:t.to,insertText:`/${i.name}`,detail:i.source,...i.description===void 0?{}:{description:i.description}}))}else if(t.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const s=await w.files(this.cwd,t.query,t.fileKind,t.fileMode).catch(Kn);if(e!==this.requestVersion)return;this.completions=s.slice(0,12).map(i=>{const r=Hn(i.path,t.fileMode==="path",t.quoted===!0);return{kind:"file",replaceFrom:t.from,replaceTo:t.to,insertText:r,detail:i.kind,...i.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){const t=this.textarea?.selectionStart??this.draft.length,e=this.draft.slice(0,t),s=this.currentQuotedTrigger(e,t);if(s!==void 0)return s;const i=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
539
+ `))+1,r=e.slice(i);if(e.slice(0,i).endsWith("@ "))return{kind:"file",query:r,from:i,to:t,fileMode:"path"};if(r.startsWith("/")&&i===0)return{kind:"command",query:r.slice(1),from:i,to:t};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:i,to:t}}currentQuotedTrigger(t,e){const s=t.lastIndexOf('"');if(s===-1)return;const i=t.slice(0,s);if(i.endsWith("@"))return{kind:"file",query:t.slice(s+1),from:i.length-1,to:e,quoted:!0};if(i.endsWith("@ "))return{kind:"file",query:t.slice(s+1),from:s,to:e,fileMode:"path",quoted:!0}}handleKeyDown(t){if(this.completions.length){if(t.key==="ArrowDown"){t.preventDefault(),this.selectedIndex=(this.selectedIndex+1)%this.completions.length;return}if(t.key==="ArrowUp"){t.preventDefault(),this.selectedIndex=(this.selectedIndex-1+this.completions.length)%this.completions.length;return}if(t.key==="Tab"||t.key==="Enter"){t.preventDefault();const e=this.completions[this.selectedIndex];e!==void 0&&this.pick(e);return}if(t.key==="Escape"){t.preventDefault(),this.completions=[];return}}if(t.key==="Tab"&&this.currentTrigger()?.kind==="file"){t.preventDefault(),this.refreshCompletions();return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.send(this.canSteer||this.isCompacting?"followUp":void 0))}pick(t){const e=t.kind==="file"&&(t.insertText.endsWith("/")||t.cursorOffset!==void 0)?"":" ",s=t.replaceFrom+(t.cursorOffset??t.insertText.length)+e.length,i=t.insertText.endsWith('"')&&this.draft.slice(t.replaceTo).startsWith('"')?this.draft.slice(t.replaceTo+1):this.draft.slice(t.replaceTo);this.draft=`${this.draft.slice(0,t.replaceFrom)}${t.insertText}${e}${i}`,this.sessionId!==void 0&&this.sessionId!==""&&rt(this.sessionId,this.draft),this.completions=[],this.updateComplete.then(()=>this.textarea?.setSelectionRange(s,s))}send(t){const e=this.draft.trim();e===""||this.disabled||(this.draft="",this.sessionId!==void 0&&this.sessionId!==""&&Qn(this.sessionId),this.completions=[],this.onSend?.(e,this.canSteer||this.isCompacting?t:void 0))}};j.styles=_o;U([u({type:Boolean})],j.prototype,"disabled",2);U([u()],j.prototype,"sessionId",2);U([u()],j.prototype,"cwd",2);U([u({type:Boolean})],j.prototype,"canSteer",2);U([u({type:Boolean})],j.prototype,"isCompacting",2);U([u({type:Boolean})],j.prototype,"canStop",2);U([u({attribute:!1})],j.prototype,"onSend",2);U([u({attribute:!1})],j.prototype,"onStop",2);U([me("textarea")],j.prototype,"textarea",2);U([$()],j.prototype,"draft",2);U([$()],j.prototype,"completions",2);U([$()],j.prototype,"selectedIndex",2);j=U([z("prompt-editor")],j);function Hn(t,e,s){const i=e?"":"@";return!s&&!t.includes(" ")?`${i}${t}`:`${i}"${t}"`}function Gn(){return[]}function Kn(){return[]}const Vn="pi-web:prompt-draft:";function Ke(t){return`${Vn}${t}`}function Zn(t){try{return localStorage.getItem(Ke(t))??""}catch{return""}}function rt(t,e){try{e?localStorage.setItem(Ke(t),e):localStorage.removeItem(Ke(t))}catch{}}function Qn(t){try{localStorage.removeItem(Ke(t))}catch{}}function Oe(t){return Number.isFinite(t)?t<1e3?Math.round(t).toString():t<1e4?`${(t/1e3).toFixed(1)}k`:t<1e6?`${String(Math.round(t/1e3))}k`:t<1e7?`${(t/1e6).toFixed(1)}M`:`${String(Math.round(t/1e6))}M`:"0"}function Jn(t){return!Number.isFinite(t)||t===0?"$0":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}var Xn=Object.defineProperty,Yn=Object.getOwnPropertyDescriptor,Et=(t,e,s,i)=>{for(var r=i>1?void 0:i?Yn(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Xn(e,s,r),r};let _e=class extends I{render(){const t=this.status;if(t===void 0)return p`<div class="bar muted">No session status yet</div>`;const e=t.model?.id??"no model",s=t.model?.provider!==void 0&&t.model.provider!==""?`${t.model.provider}/`:"",i=t.contextUsage,r=i?i.percent==null?`context ${Oe(i.contextWindow)}`:`${i.percent.toFixed(1)}%/${Oe(i.contextWindow)}`:"context unknown",o=t.tokens;return p`
540
+ <div class="bar">
541
+ <span title=${this.workspace?.path??""}>${this.workspace?.label??"workspace"}</span>
542
+ <span>${s}${e}</span>
543
+ <span>thinking ${t.thinkingLevel??"off"}</span>
544
+ <span>↑${Oe(o.input)}</span>
545
+ <span>↓${Oe(o.output)}</span>
546
+ <span>${r}</span>
547
+ <span>${Jn(t.cost)}</span>
548
+ ${t.pendingMessageCount>0?p`<span>${String(t.pendingMessageCount)} queued</span>`:null}
549
+ </div>
550
+ `}};_e.styles=Po;Et([u({attribute:!1})],_e.prototype,"status",2);Et([u({attribute:!1})],_e.prototype,"workspace",2);_e=Et([z("status-bar")],_e);var ea=Object.defineProperty,ta=Object.getOwnPropertyDescriptor,xe=(t,e,s,i)=>{for(var r=i>1?void 0:i?ta(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&ea(e,s,r),r};let ee=class extends I{constructor(){super(...arguments),this.title="Select",this.options=[],this.selectedIndex=0}render(){return p`
551
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
552
+ <section @mousedown=${t=>{t.stopPropagation()}}>
553
+ <header>
554
+ <strong>${this.title}</strong>
555
+ <button @click=${()=>this.onCancel?.()}>×</button>
556
+ </header>
557
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
558
+ ${this.options.map((t,e)=>p`
559
+ <button class=${e===this.selectedIndex?"selected":""} @click=${()=>this.onPick?.(t.value)}>
560
+ <span>${t.label}</span>
561
+ ${t.description!==void 0&&t.description!==""?p`<small>${t.description}</small>`:null}
562
+ </button>
563
+ `)}
564
+ </div>
565
+ </section>
566
+ </div>
567
+ `}firstUpdated(){this.renderRoot.querySelector(".options")?.focus()}handleKeyDown(t){if(t.key==="Escape")t.preventDefault(),this.onCancel?.();else if(t.key==="ArrowDown")t.preventDefault(),this.selectedIndex=(this.selectedIndex+1)%this.options.length;else if(t.key==="ArrowUp")t.preventDefault(),this.selectedIndex=(this.selectedIndex-1+this.options.length)%this.options.length;else if(t.key==="Enter"){t.preventDefault();const e=this.options[this.selectedIndex];e&&this.onPick?.(e.value)}}};ee.styles=Co;xe([u()],ee.prototype,"title",2);xe([u({attribute:!1})],ee.prototype,"options",2);xe([u({attribute:!1})],ee.prototype,"onPick",2);xe([u({attribute:!1})],ee.prototype,"onCancel",2);xe([$()],ee.prototype,"selectedIndex",2);ee=xe([z("command-picker")],ee);var sa=Object.defineProperty,ia=Object.getOwnPropertyDescriptor,de=(t,e,s,i)=>{for(var r=i>1?void 0:i?ia(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&sa(e,s,r),r};let Q=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const t=this.filteredActions();return p`
568
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
569
+ <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
570
+ <header>
571
+ <input
572
+ .value=${this.queryText}
573
+ placeholder="Search actions..."
574
+ @input=${e=>{e.target instanceof HTMLInputElement&&(this.queryText=e.target.value,this.selectedIndex=0)}}
575
+ >
576
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
577
+ </header>
578
+ <div class="options">
579
+ ${t.length===0?p`<div class="empty">No actions found.</div>`:t.map((e,s)=>p`
580
+ <button class=${s===this.selectedIndex?"selected":""} @click=${()=>{this.run(e)}}>
581
+ <span class="main">
582
+ <strong>${e.title}</strong>
583
+ ${e.description!==void 0&&e.description!==""?p`<small>${e.description}</small>`:null}
584
+ </span>
585
+ ${e.shortcut!==void 0?p`<kbd>${Gr(e.shortcut)}</kbd>`:null}
586
+ ${e.group!==void 0&&e.group!==""?p`<small class="group">${e.group}</small>`:null}
587
+ </button>
588
+ `)}
589
+ </div>
590
+ </section>
591
+ </div>
592
+ `}firstUpdated(){this.input?.focus()}updated(t){if(!t.has("actions")&&!t.has("queryText"))return;const e=Math.max(0,this.filteredActions().length-1);this.selectedIndex>e&&(this.selectedIndex=e)}filteredActions(){const t=this.queryText.trim().toLowerCase();return this.actions.filter(e=>e.enabled!==!1).filter(e=>t===""?!0:[e.title,e.description??"",e.group??"",e.shortcut??""].join(" ").toLowerCase().includes(t))}handleKeyDown(t){const e=this.filteredActions();if(t.key==="Escape")t.preventDefault(),this.onCancel?.();else if(t.key==="ArrowDown")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex+1)%e.length);else if(t.key==="ArrowUp")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex-1+e.length)%e.length);else if(t.key==="Enter"){t.preventDefault();const s=e[this.selectedIndex];s!==void 0&&this.run(s)}}run(t){this.onRun?.(t.id)}};Q.styles=Ao;de([u({attribute:!1})],Q.prototype,"actions",2);de([u({attribute:!1})],Q.prototype,"onRun",2);de([u({attribute:!1})],Q.prototype,"onCancel",2);de([me("input")],Q.prototype,"input",2);de([$()],Q.prototype,"queryText",2);de([$()],Q.prototype,"selectedIndex",2);Q=de([z("action-palette")],Q);var ra=Object.defineProperty,oa=Object.getOwnPropertyDescriptor,J=(t,e,s,i)=>{for(var r=i>1?void 0:i?oa(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&ra(e,s,r),r};let F=class extends I{constructor(){super(...arguments),this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const t=++this.requestId;this.loading=!0;try{const e=await w.projectDirectories(this.path);if(t!==this.requestId)return;this.suggestions=e,this.selected=Math.min(this.selected,Math.max(0,e.length-1))}catch{t===this.requestId&&(this.suggestions=[])}finally{t===this.requestId&&(this.loading=!1)}}setPath(t){this.path=t,this.selected=0,this.loadSuggestions()}pick(t){this.setPath(t.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(t){t.target instanceof HTMLInputElement&&this.setPath(t.target.value)}onCreateMissingChange(t){t.target instanceof HTMLInputElement&&(this.createMissing=t.target.checked)}onKeyDown(t){if(t.key==="Escape")t.preventDefault(),this.onCancel?.();else if(t.key==="Enter")t.preventDefault(),this.submit();else if(t.key==="ArrowDown")t.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(t.key==="ArrowUp")t.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(t.key==="Tab"){const e=this.suggestions[this.selected];if(e===void 0)return;t.preventDefault(),this.pick(e)}}render(){return p`
593
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
594
+ <section @click=${t=>{t.stopPropagation()}}>
595
+ <header>
596
+ <strong>Add project</strong>
597
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
598
+ </header>
599
+ <div class="body">
600
+ <label>
601
+ Project folder
602
+ <input .value=${this.path} @input=${t=>{this.onPathInput(t)}} @keydown=${t=>{this.onKeyDown(t)}} placeholder="/path/to/project or ~/code/project" autofocus />
603
+ </label>
604
+ <div class="suggestions">
605
+ ${this.loading?p`<div class="hint">Loading folders…</div>`:null}
606
+ ${this.suggestions.map((t,e)=>p`
607
+ <button class=${e===this.selected?"selected":""} @click=${()=>{this.pick(t)}}>
608
+ ${t.path}
609
+ </button>
610
+ `)}
611
+ ${!this.loading&&this.suggestions.length===0?p`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
612
+ </div>
613
+ <label class="check">
614
+ <input type="checkbox" .checked=${this.createMissing} @change=${t=>{this.onCreateMissingChange(t)}} />
615
+ Create the folder if it does not exist
616
+ </label>
617
+ </div>
618
+ <footer>
619
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
620
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
621
+ </footer>
622
+ </section>
623
+ </div>
624
+ `}};F.styles=B`
625
+ :host { position: fixed; inset: 0; z-index: 30; color: #e6edf3; font: 14px system-ui, sans-serif; }
626
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: #0008; }
627
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid #30363d; border-radius: 12px; background: #0d1117; box-shadow: 0 20px 60px #000b; overflow: hidden; }
628
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid #30363d; }
629
+ footer { border-top: 1px solid #30363d; border-bottom: 0; justify-content: end; }
630
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
631
+ label { display: grid; gap: 6px; color: #8b949e; }
632
+ input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid #30363d; border-radius: 8px; background: #0d1117; color: #e6edf3; padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
633
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: #e6edf3; }
634
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid #30363d; border-radius: 8px; background: #161b22; }
635
+ .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid #30363d; border-radius: 0; background: transparent; color: #e6edf3; padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
636
+ .suggestions button.selected, .suggestions button:hover { background: #0d2847; }
637
+ .hint { padding: 12px; color: #8b949e; }
638
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
639
+ header button { border: 0; background: transparent; color: #8b949e; font-size: 22px; padding: 0 8px; }
640
+ .primary { border-color: #238636; background: #238636; }
641
+ button:disabled { opacity: .5; cursor: not-allowed; }
642
+ `;J([u({attribute:!1})],F.prototype,"onSubmit",2);J([u({attribute:!1})],F.prototype,"onCancel",2);J([$()],F.prototype,"path",2);J([$()],F.prototype,"createMissing",2);J([$()],F.prototype,"suggestions",2);J([$()],F.prototype,"selected",2);J([$()],F.prototype,"loading",2);J([me("input")],F.prototype,"pathInput",2);F=J([z("project-dialog")],F);var na=Object.defineProperty,aa=Object.getOwnPropertyDescriptor,T=(t,e,s,i)=>{for(var r=i>1?void 0:i?aa(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&na(e,s,r),r};let v=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.fileTree=[],this.expandedDirs={},this.fileTreeStale=!1,this.gitStale=!1,this.onSelectTool=()=>{},this.onRefreshFiles=()=>{},this.onExpandDir=()=>{},this.onSelectFile=()=>{},this.onRefreshGit=()=>{},this.onSelectDiff=()=>{}}render(){const t=this.workspace;if(t===void 0)return p`<section class="empty">Select a workspace.</section>`;const e=this.panels.filter(i=>i.visible?.(t)??!0),s=e.find(i=>i.id===this.tool)??e[0];return p`
643
+ <header>
644
+ ${this.hideToolTabs?null:p`
645
+ <div class="tabs">
646
+ ${e.map(i=>p`
647
+ <button class=${s?.id===i.id?"selected":""} @click=${()=>{this.onSelectTool(i.id)}}>${i.title}</button>
648
+ `)}
649
+ </div>
650
+ `}
651
+ <small title=${t.path}>${t.label}</small>
652
+ </header>
653
+ ${s===void 0?p`<section class="empty">No workspace panels registered.</section>`:s.render(this.createPanelContext(t))}
654
+ `}createPanelContext(t){return{workspace:t,fileTree:this.fileTree,expandedDirs:this.expandedDirs,selectedFilePath:this.selectedFilePath,selectedFileContent:this.selectedFileContent,fileTreeStale:this.fileTreeStale,gitStatus:this.gitStatus,selectedDiffPath:this.selectedDiffPath,selectedDiff:this.selectedDiff,selectedStagedDiff:this.selectedStagedDiff,gitStale:this.gitStale,onRefreshFiles:this.onRefreshFiles,onExpandDir:this.onExpandDir,onSelectFile:this.onSelectFile,onRefreshGit:this.onRefreshGit,onSelectDiff:this.onSelectDiff}}};v.styles=So;T([u({attribute:!1})],v.prototype,"workspace",2);T([u()],v.prototype,"tool",2);T([u({attribute:!1})],v.prototype,"panels",2);T([u({type:Boolean})],v.prototype,"hideToolTabs",2);T([u({attribute:!1})],v.prototype,"fileTree",2);T([u({attribute:!1})],v.prototype,"expandedDirs",2);T([u({attribute:!1})],v.prototype,"selectedFilePath",2);T([u({attribute:!1})],v.prototype,"selectedFileContent",2);T([u({type:Boolean})],v.prototype,"fileTreeStale",2);T([u({attribute:!1})],v.prototype,"gitStatus",2);T([u({attribute:!1})],v.prototype,"selectedDiffPath",2);T([u({attribute:!1})],v.prototype,"selectedDiff",2);T([u({attribute:!1})],v.prototype,"selectedStagedDiff",2);T([u({type:Boolean})],v.prototype,"gitStale",2);T([u({attribute:!1})],v.prototype,"onSelectTool",2);T([u({attribute:!1})],v.prototype,"onRefreshFiles",2);T([u({attribute:!1})],v.prototype,"onExpandDir",2);T([u({attribute:!1})],v.prototype,"onSelectFile",2);T([u({attribute:!1})],v.prototype,"onRefreshGit",2);T([u({attribute:!1})],v.prototype,"onSelectDiff",2);v=T([z("workspace-panel")],v);var la=Object.defineProperty,ca=Object.getOwnPropertyDescriptor,et=(t,e,s,i)=>{for(var r=i>1?void 0:i?ca(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&la(e,s,r),r};let ge=class extends I{constructor(){super(...arguments),this.state=ki(),this.sessions=new qr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.workspaces=new Fr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()},this.sessions),this.projects=new ar(()=>this.state,t=>{this.setState(t)},this.workspaces),this.files=new rr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.git=new nr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.keyboard=new Hr,this.plugins=da(),this.onPopState=()=>{this.withChatScrollTransition(()=>this.restoreRoute(!1))},this.onKeyDown=t=>{this.keyboard.handle(t,this.getActions())&&(t.preventDefault(),t.stopPropagation())}}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("keydown",this.onKeyDown),this.sessions.connectStatusUpdates(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("keydown",this.onKeyDown),this.keyboard.reset(),this.sessions.dispose(),this.git.dispose(),super.disconnectedCallback()}setState(t){const e=this.state;this.state={...this.state,...t},this.handleActivityTransition(e,this.state),this.handleWorkspaceChange(e,this.state)}async loadProjectsAndRestoreRoute(){await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRoute(!1))}async restoreRoute(t){const e=bo(),s=Jt(qe("core:workspace.files"),"file"),i=Jt(qe("core:workspace.git"),"diff");if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:e.view??this.state.mainView,selectedFilePath:s,selectedDiffPath:i}),e.projectId===void 0||e.projectId==="")return;const r=this.state.projects.find(o=>o.id===e.projectId);r&&(await this.workspaces.selectProject(r,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:t}),this.setState({selectedFilePath:s,selectedDiffPath:i}),e.tool==="core:workspace.files"&&await this.files.refreshFiles(),e.tool==="core:workspace.files"&&s!==void 0&&await this.files.restoreFile(s),e.tool==="core:workspace.git"&&await this.git.refreshGit(),this.git.updatePolling())}async withChatScrollTransition(t){this.chatView?.saveScrollPosition(),await t(),await this.updateComplete,await this.chatView?.updateComplete,await gs(),this.chatView?.restoreScrollPosition(),this.promptEditor?.focusInput()}async withChatPrependTransition(t){const e=this.chatView?.capturePrependScrollAnchor();await t(),await this.updateComplete,await this.chatView?.updateComplete,await gs(),this.chatView?.restorePrependScrollAnchor(e)}updateUrl(t){xo({projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},t)}selectWorkspaceTool(t){this.setState({workspaceTool:t,mainView:t}),this.updateUrl(),this.refreshSelectedWorkspaceTool(t),this.git.updatePolling()}selectMainView(t){if(t==="navigation"){this.setState({mainView:t}),this.updateUrl(),this.git.updatePolling();return}this.setState({mainView:t,workspaceTool:t==="chat"?this.state.workspaceTool:t}),this.updateUrl(),t!=="chat"&&this.refreshSelectedWorkspaceTool(t),this.git.updatePolling()}handleWorkspaceChange(t,e){t.selectedWorkspace?.id===e.selectedWorkspace?.id||e.selectedWorkspace===void 0||(this.refreshSelectedWorkspaceTool(e.workspaceTool),this.git.updatePolling())}handleActivityTransition(t,e){const s=fs(t.status),i=fs(e.status);s&&!i&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}refreshSelectedWorkspaceTool(t){t==="core:workspace.files"&&this.files.refreshFiles(),t==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(t=!1){return p`<workspace-panel .workspace=${this.state.selectedWorkspace} .tool=${this.state.workspaceTool} .panels=${this.visibleWorkspacePanels()} .hideToolTabs=${t} .fileTree=${this.state.fileTree} .expandedDirs=${this.state.expandedDirs} .selectedFilePath=${this.state.selectedFilePath} .selectedFileContent=${this.state.selectedFileContent} .fileTreeStale=${this.state.fileTreeStale} .gitStatus=${this.state.gitStatus} .selectedDiffPath=${this.state.selectedDiffPath} .selectedDiff=${this.state.selectedDiff} .selectedStagedDiff=${this.state.selectedStagedDiff} .gitStale=${this.state.gitStale} .onSelectTool=${e=>{this.selectWorkspaceTool(e)}} .onRefreshFiles=${()=>this.files.refreshFiles()} .onExpandDir=${e=>this.files.expandDir(e)} .onSelectFile=${e=>this.files.selectFile(e)} .onRefreshGit=${()=>this.git.refreshGit()} .onSelectDiff=${e=>this.git.selectDiff(e)}></workspace-panel>`}renderNavigationPanel(t){const e=s=>this.withChatScrollTransition(async()=>{await s(),t&&this.setState({mainView:"chat"}),t&&this.updateUrl()});return p`
655
+ <header>
656
+ <strong>Pi Web</strong>
657
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.setState({actionPaletteOpen:!0})}}>Actions</button>
658
+ </header>
659
+ <project-list .projects=${this.state.projects} .selected=${this.state.selectedProject} .onSelect=${s=>this.withChatScrollTransition(()=>this.workspaces.selectProject(s))} .onClose=${s=>this.projects.closeProject(s.id)}></project-list>
660
+ <workspace-list .workspaces=${this.state.workspaces} .selected=${this.state.selectedWorkspace} .onSelect=${s=>e(()=>this.workspaces.selectWorkspace(s))}></workspace-list>
661
+ <session-list .sessions=${this.state.sessions} .statuses=${this.state.sessionStatuses} .activities=${this.state.sessionActivities} .selected=${this.state.selectedSession} .canStart=${!!this.state.selectedWorkspace} .onStart=${()=>e(()=>this.sessions.startSession())} .onSelect=${s=>e(()=>this.sessions.selectSession(s))} .onArchive=${s=>this.sessions.archiveSession(s)} .onRestore=${s=>e(()=>this.sessions.restoreSession(s))}></session-list>
662
+ `}visibleWorkspacePanels(){const t=this.state.selectedWorkspace;return this.plugins.getWorkspacePanels().filter(e=>t===void 0||(e.visible?.(t)??!0))}getActions(){return this.plugins.getActions(this.createPluginRuntimeContext())}createPluginRuntimeContext(){return{state:this.state,openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},selectMainView:t=>{this.selectMainView(t)},selectWorkspaceTool:t=>{this.selectWorkspaceTool(t)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),stopActiveWork:()=>this.sessions.stopActiveWork()}}runAction(t){const e=this.getActions().find(s=>s.id===t&&s.enabled!==!1);e!==void 0&&e.run()}render(){const t=this.state;return p`
663
+ <div class="shell">
664
+ <aside>${this.renderNavigationPanel(!1)}</aside>
665
+ <main class=${t.mainView==="chat"?"chat-view":t.mainView==="navigation"?"navigation-view":"workspace-view"}>
666
+ <div class="mobile-tabs">
667
+ <button class=${t.mainView==="navigation"?"mobile-navigation-tab selected":"mobile-navigation-tab"} @click=${()=>{this.selectMainView("navigation")}}>Sessions</button>
668
+ <button class=${t.mainView==="chat"?"selected":""} @click=${()=>{this.selectMainView("chat")}}>Chat</button>
669
+ ${this.visibleWorkspacePanels().map(e=>p`
670
+ <button class=${t.mainView===e.id?"selected":""} @click=${()=>{this.selectMainView(e.id)}}>${e.title}</button>
671
+ `)}
672
+ </div>
673
+ ${t.error?p`<div class="error">${t.error}</div>`:null}
674
+ <div class="mobile-navigation-panel">${this.renderNavigationPanel(!0)}</div>
675
+ ${t.selectedSession?p`
676
+ <chat-view .sessionId=${t.selectedSession.id} .messages=${t.messages} .messageStart=${t.messagePageStart} .messageTotal=${t.messagePageTotal} .hasMore=${t.messagePageStart>0} .loadingMore=${t.isLoadingEarlierMessages} .isReceivingPartialStream=${t.isReceivingPartialStream} .isCompacting=${t.status?.isCompacting===!0} .pendingMessageCount=${t.status?.pendingMessageCount??0} .status=${t.status} .activity=${t.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
677
+ <prompt-editor .sessionId=${t.selectedSession.id} .cwd=${t.selectedWorkspace?.path} .disabled=${t.selectedSession.archived===!0} .canSteer=${t.status?.isStreaming===!0} .isCompacting=${t.status?.isCompacting===!0} .canStop=${t.status?.isStreaming===!0||t.status?.isBashRunning===!0||t.status?.isCompacting===!0} .onSend=${(e,s)=>this.sessions.send(e,s)} .onStop=${()=>this.sessions.stopActiveWork()}></prompt-editor>
678
+ <status-bar .status=${t.status} .workspace=${t.selectedWorkspace}></status-bar>
679
+ ${t.commandDialog!==void 0?p`<command-picker .title=${t.commandDialog.title} .options=${t.commandDialog.options} .onPick=${e=>this.sessions.respondToCommand(t.commandDialog?.requestId??"",e)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
680
+ `:p`<div class="empty">Select or start a session.</div>`}
681
+ <div class="mobile-panel">${this.renderWorkspacePanel(!0)}</div>
682
+ </main>
683
+ ${this.renderWorkspacePanel()}
684
+ ${t.actionPaletteOpen?p`<action-palette .actions=${this.getActions()} .onRun=${e=>{this.setState({actionPaletteOpen:!1}),this.runAction(e)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
685
+ ${t.projectDialogOpen?p`<project-dialog .onSubmit=${(e,s)=>this.projects.addProject(e,s)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
686
+ </div>
687
+ `}};ge.styles=ko;et([$()],ge.prototype,"state",2);et([me("chat-view")],ge.prototype,"chatView",2);et([me("prompt-editor")],ge.prototype,"promptEditor",2);ge=et([z("pi-web-app")],ge);function da(){const t=new mo;return t.register(ho),t.register(uo),t}function fs(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}function gs(){return new Promise(t=>requestAnimationFrame(()=>{t()}))}export{B as a,p as b,Qi as c,xa as d,me as e,I as i,u as n,$ as r,z as t};