@jmfederico/pi-web 1.202605.6 → 1.202605.8

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 (30) hide show
  1. package/README.md +28 -0
  2. package/dist/cli.js +121 -20
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/assets/{CodeViewer-CbO-Cu6v.js → CodeViewer-Cp0QKepT.js} +1 -1
  5. package/dist/client/assets/{TerminalPanel-D4bhXEax.js → TerminalPanel-C7TcN1cv.js} +1 -1
  6. package/dist/client/assets/index-b1ytby08.js +871 -0
  7. package/dist/client/index.html +1 -1
  8. package/dist/server/piWebPluginService.js +51 -58
  9. package/dist/server/piWebPluginService.js.map +1 -1
  10. package/dist/server/realtime/sessionEventHub.js.map +1 -1
  11. package/dist/server/sessiond/sessionProxyRoutes.js +2 -0
  12. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  13. package/dist/server/sessiond.js +7 -1
  14. package/dist/server/sessiond.js.map +1 -1
  15. package/dist/server/sessions/authProviderOptions.js +56 -0
  16. package/dist/server/sessions/authProviderOptions.js.map +1 -0
  17. package/dist/server/sessions/authRoutes.js +59 -0
  18. package/dist/server/sessions/authRoutes.js.map +1 -0
  19. package/dist/server/sessions/authService.js +74 -0
  20. package/dist/server/sessions/authService.js.map +1 -0
  21. package/dist/server/sessions/oauthLoginFlowService.js +219 -0
  22. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -0
  23. package/dist/server/sessions/piSessionService.js +68 -15
  24. package/dist/server/sessions/piSessionService.js.map +1 -1
  25. package/dist/server/sessions/sessionCommandService.js.map +1 -1
  26. package/docs/plugins.md +580 -0
  27. package/package.json +3 -2
  28. package/pi-web-plugins/info/package.json +3 -2
  29. package/pi-web-plugins/info/pi-web-plugin.js +37 -37
  30. package/dist/client/assets/index-C0G9UyhD.js +0 -805
@@ -0,0 +1,871 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Cp0QKepT.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-C7TcN1cv.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as ls,w as Ie,J as xt,R as Hi,S as Vi,G as Ki,U as Gi,V as Qi,A as Zi,W as Ji,X as Yi,Y as Xi,Z as cs,x as ds,_ as er}from"./vendor-editor-core-B4Sq6exx.js";import{m as tr,i as sr,d as ir}from"./vendor-editor-languages-DznYbTkJ.js";(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 Ye=globalThis,Dt=Ye.ShadowRoot&&(Ye.ShadyCSS===void 0||Ye.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ot=Symbol(),ps=new WeakMap;let si=class{constructor(e,s,i){if(this._$cssResult$=!0,i!==Ot)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(Dt&&e===void 0){const i=s!==void 0&&s.length===1;i&&(e=ps.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&ps.set(s,e))}return e}toString(){return this.cssText}};const rr=t=>new si(typeof t=="string"?t:t+"",void 0,Ot),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 si(s,t,Ot)},or=(t,e)=>{if(Dt)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const i=document.createElement("style"),r=Ye.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=s.cssText,t.appendChild(i)}},hs=Dt?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const i of e.cssRules)s+=i.cssText;return rr(s)})(t):t;const{is:nr,defineProperty:ar,getOwnPropertyDescriptor:lr,getOwnPropertyNames:cr,getOwnPropertySymbols:dr,getPrototypeOf:pr}=Object,ht=globalThis,us=ht.trustedTypes,hr=us?us.emptyScript:"",ur=ht.reactiveElementPolyfillSupport,je=(t,e)=>t,et={toAttribute(t,e){switch(e){case Boolean:t=t?hr: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}},Lt=(t,e)=>!nr(t,e),fs={attribute:!0,type:String,converter:et,reflect:!1,useDefault:!1,hasChanged:Lt};Symbol.metadata??=Symbol("metadata"),ht.litPropertyMetadata??=new WeakMap;let ve=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=fs){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&&ar(this.prototype,e,r)}}static getPropertyDescriptor(e,s,i){const{get:r,set:o}=lr(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)??fs}static _$Ei(){if(this.hasOwnProperty(je("elementProperties")))return;const e=pr(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(je("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(je("properties"))){const s=this.properties,i=[...cr(s),...dr(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(hs(r))}else e!==void 0&&s.push(hs(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 or(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:et).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:et;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??Lt)(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){}};ve.elementStyles=[],ve.shadowRootOptions={mode:"open"},ve[je("elementProperties")]=new Map,ve[je("finalized")]=new Map,ur?.({ReactiveElement:ve}),(ht.reactiveElementVersions??=[]).push("2.1.2");const jt=globalThis,gs=t=>t,tt=jt.trustedTypes,ms=tt?tt.createPolicy("lit-html",{createHTML:t=>t}):void 0,ii="$lit$",ie=`lit$${Math.random().toFixed(9).slice(2)}$`,ri="?"+ie,fr=`<${ri}>`,de=document,Ne=()=>de.createComment(""),qe=t=>t===null||typeof t!="object"&&typeof t!="function",Nt=Array.isArray,gr=t=>Nt(t)||typeof t?.[Symbol.iterator]=="function",St=`[
3
+ \f\r]`,Me=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,bs=/-->/g,ys=/>/g,ne=RegExp(`>|${St}(?:([^\\s"'>=/]+)(${St}*=${St}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),ws=/'/g,vs=/"/g,oi=/^(?:script|style|textarea|title)$/i,mr=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),d=mr(1),re=Symbol.for("lit-noChange"),A=Symbol.for("lit-nothing"),xs=new WeakMap,ce=de.createTreeWalker(de,129);function ni(t,e){if(!Nt(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return ms!==void 0?ms.createHTML(e):e}const br=(t,e)=>{const s=t.length-1,i=[];let r,o=e===2?"<svg>":e===3?"<math>":"",n=Me;for(let a=0;a<s;a++){const l=t[a];let c,u,p=-1,f=0;for(;f<l.length&&(n.lastIndex=f,u=n.exec(l),u!==null);)f=n.lastIndex,n===Me?u[1]==="!--"?n=bs:u[1]!==void 0?n=ys:u[2]!==void 0?(oi.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ne):u[3]!==void 0&&(n=ne):n===ne?u[0]===">"?(n=r??Me,p=-1):u[1]===void 0?p=-2:(p=n.lastIndex-u[2].length,c=u[1],n=u[3]===void 0?ne:u[3]==='"'?vs:ws):n===vs||n===ws?n=ne:n===bs||n===ys?n=Me:(n=ne,r=void 0);const g=n===ne&&t[a+1].startsWith("/>")?" ":"";o+=n===Me?l+fr:p>=0?(i.push(c),l.slice(0,p)+ii+l.slice(p)+ie+g):l+ie+(p===-2?a:g)}return[ni(t,o+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Fe{constructor({strings:e,_$litType$:s},i){let r;this.parts=[];let o=0,n=0;const a=e.length-1,l=this.parts,[c,u]=br(e,s);if(this.el=Fe.createElement(c,i),ce.currentNode=this.el.content,s===2||s===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(r=ce.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const p of r.getAttributeNames())if(p.endsWith(ii)){const f=u[n++],g=r.getAttribute(p).split(ie),b=/([.?@])?(.*)/.exec(f);l.push({type:1,index:o,name:b[2],strings:g,ctor:b[1]==="."?wr:b[1]==="?"?vr:b[1]==="@"?xr:ut}),r.removeAttribute(p)}else p.startsWith(ie)&&(l.push({type:6,index:o}),r.removeAttribute(p));if(oi.test(r.tagName)){const p=r.textContent.split(ie),f=p.length-1;if(f>0){r.textContent=tt?tt.emptyScript:"";for(let g=0;g<f;g++)r.append(p[g],Ne()),ce.nextNode(),l.push({type:2,index:++o});r.append(p[f],Ne())}}}else if(r.nodeType===8)if(r.data===ri)l.push({type:2,index:o});else{let p=-1;for(;(p=r.data.indexOf(ie,p+1))!==-1;)l.push({type:7,index:o}),p+=ie.length-1}o++}}static createElement(e,s){const i=de.createElement("template");return i.innerHTML=e,i}}function Se(t,e,s=t,i){if(e===re)return e;let r=i!==void 0?s._$Co?.[i]:s._$Cl;const o=qe(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=Se(t,r._$AS(t,e.values),r,i)),e}class yr{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??de).importNode(s,!0);ce.currentNode=r;let o=ce.nextNode(),n=0,a=0,l=i[0];for(;l!==void 0;){if(n===l.index){let c;l.type===2?c=new Pe(o,o.nextSibling,this,e):l.type===1?c=new l.ctor(o,l.name,l.strings,this,e):l.type===6&&(c=new Sr(o,this,e)),this._$AV.push(c),l=i[++a]}n!==l?.index&&(o=ce.nextNode(),n++)}return ce.currentNode=de,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 Pe{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,i,r){this.type=2,this._$AH=A,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=Se(this,e,s),qe(e)?e===A||e==null||e===""?(this._$AH!==A&&this._$AR(),this._$AH=A):e!==this._$AH&&e!==re&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):gr(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!==A&&qe(this._$AH)?this._$AA.nextSibling.data=e:this.T(de.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=Fe.createElement(ni(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(s);else{const o=new yr(r,this),n=o.u(this.options);o.p(s),this.T(n),this._$AH=o}}_$AC(e){let s=xs.get(e.strings);return s===void 0&&xs.set(e.strings,s=new Fe(e)),s}k(e){Nt(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 Pe(this.O(Ne()),this.O(Ne()),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=gs(e).nextSibling;gs(e).remove(),e=i}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}let ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,i,r,o){this.type=1,this._$AH=A,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=A}_$AI(e,s=this,i,r){const o=this.strings;let n=!1;if(o===void 0)e=Se(this,e,s,0),n=!qe(e)||e!==this._$AH&&e!==re,n&&(this._$AH=e);else{const a=e;let l,c;for(e=o[0],l=0;l<o.length-1;l++)c=Se(this,a[i+l],s,l),c===re&&(c=this._$AH[l]),n||=!qe(c)||c!==this._$AH[l],c===A?e=A:e!==A&&(e+=(c??"")+o[l+1]),this._$AH[l]=c}n&&!r&&this.j(e)}j(e){e===A?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},wr=class extends ut{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===A?void 0:e}},vr=class extends ut{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==A)}},xr=class extends ut{constructor(e,s,i,r,o){super(e,s,i,r,o),this.type=5}_$AI(e,s=this){if((e=Se(this,e,s,0)??A)===re)return;const i=this._$AH,r=e===A&&i!==A||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,o=e!==A&&(i===A||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 Sr{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){Se(this,e)}}const kr={I:Pe},$r=jt.litHtmlPolyfillSupport;$r?.(Fe,Pe),(jt.litHtmlVersions??=[]).push("3.3.2");const Pr=(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 Pe(e.insertBefore(Ne(),o),o,void 0,s??{})}return r._$AI(t),r};const qt=globalThis;let R=class extends ve{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=Pr(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return re}};R._$litElement$=!0,R.finalized=!0,qt.litElementHydrateSupport?.({LitElement:R});const Cr=qt.litElementPolyfillSupport;Cr?.({LitElement:R});(qt.litElementVersions??=[]).push("4.2.2");const W=t=>(e,s)=>{s!==void 0?s.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};const Tr={attribute:!0,type:String,converter:et,reflect:!1,hasChanged:Lt},Ar=(t=Tr,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 l=e.get.call(this);e.set.call(this,a),this.requestUpdate(n,l,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 l=this[n];e.call(this,a),this.requestUpdate(n,l,t,!0,a)}}throw Error("Unsupported decorator location: "+i)};function h(t){return(e,s)=>typeof s=="object"?Ar(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 h({...t,state:!0,attribute:!1})}const Ir=(t,e,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(t,e,s),s);function fe(t,e){return(s,i,r)=>{const o=n=>n.renderRoot?.querySelector(t)??null;return Ir(s,i,{get(){return o(this)}})}}async function y(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(Mr(n)??r.statusText)}const o=await r.json();return e(o)}function Mr(t){if(Er(t))return typeof t.error=="string"?t.error:void 0}function Er(t){return typeof t=="object"&&t!==null}function Rr(t){return typeof t=="object"&&t!==null}function w(t){if(!Rr(t))throw new Error("Expected object response");return t}function m(t,e){const s=t[e];if(typeof s!="string")throw new Error(`Expected string field: ${e}`);return s}function C(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 U(t,e){const s=t[e];if(typeof s!="number")throw new Error(`Expected number field: ${e}`);return s}function F(t,e){const s=t[e];if(typeof s!="boolean")throw new Error(`Expected boolean field: ${e}`);return s}function j(t){return e=>{if(!Array.isArray(e))throw new Error("Expected array response");return e.map(t)}}function _r(t){if(!Array.isArray(t))throw new Error("Expected array response");return t}function Dr(t){if(Array.isArray(t))return{messages:t,start:0,total:t.length};const e=w(t);return{messages:_r(e.messages),start:U(e,"start"),total:U(e,"total")}}function Ss(t){const e=w(t);return{id:m(e,"id"),name:m(e,"name"),path:m(e,"path"),createdAt:m(e,"createdAt")}}function Or(t){const e=w(t),s=C(e,"branch");return{id:m(e,"id"),projectId:m(e,"projectId"),path:m(e,"path"),label:m(e,"label"),...s===void 0?{}:{branch:s},isMain:F(e,"isMain"),isGitRepo:F(e,"isGitRepo"),isGitWorktree:F(e,"isGitWorktree")}}function $t(t){const e=w(t),s=C(e,"name"),i=C(e,"parentSessionPath"),r=C(e,"archivedAt");return{id:m(e,"id"),path:m(e,"path"),cwd:m(e,"cwd"),...s===void 0?{}:{name:s},created:m(e,"created"),modified:m(e,"modified"),messageCount:U(e,"messageCount"),firstMessage:m(e,"firstMessage"),...i===void 0?{}:{parentSessionPath:i},...e.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ee(t){const e=w(t);return{sessionId:m(e,"sessionId"),isStreaming:F(e,"isStreaming"),isCompacting:F(e,"isCompacting"),isBashRunning:F(e,"isBashRunning"),pendingMessageCount:U(e,"pendingMessageCount"),queuedMessages:e.queuedMessages===void 0?[]:j(Lr)(e.queuedMessages),tokens:jr(e.tokens),cost:U(e,"cost"),...Nr(e.model),...Jr(e.contextUsage),...S("thinkingLevel",C(e,"thinkingLevel"))}}function Lr(t){const e=w(t),s=m(e,"kind");if(s!=="steer"&&s!=="followUp")throw new Error("Invalid queued message kind");return{kind:s,text:m(e,"text")}}function jr(t){const e=w(t);return{input:U(e,"input"),output:U(e,"output"),cacheRead:U(e,"cacheRead"),cacheWrite:U(e,"cacheWrite"),total:U(e,"total")}}function ai(t){const e=w(t);return{...S("provider",C(e,"provider")),...S("id",C(e,"id")),...S("name",C(e,"name")),...S("contextWindow",ze(e,"contextWindow")),...S("reasoning",e.reasoning)}}function Nr(t){return t===void 0?{}:{model:ai(t)}}function qr(t){const e=w(t);return{models:j(ai)(e.models)}}function Fr(t){if(t!=="off"&&t!=="minimal"&&t!=="low"&&t!=="medium"&&t!=="high"&&t!=="xhigh")throw new Error("Invalid thinking level");return t}function zr(t){const e=w(t);return{levels:j(Fr)(e.levels)}}function Wr(t){if(t!=="oauth"&&t!=="api_key")throw new Error("Invalid auth type");return t}function Ur(t){if(t!=="stored"&&t!=="runtime"&&t!=="environment"&&t!=="fallback"&&t!=="models_json_key"&&t!=="models_json_command")throw new Error("Invalid auth status source");return t}function Br(t){const e=w(t),s=e.source===void 0?void 0:Ur(e.source);return{configured:F(e,"configured"),...S("source",s),...S("label",C(e,"label"))}}function Hr(t){const e=w(t);return{id:m(e,"id"),name:m(e,"name"),authType:Wr(e.authType),status:Br(e.status)}}function Vr(t){const e=w(t);return{providers:j(Hr)(e.providers)}}function Ve(t){const e=w(t);return{flowId:m(e,"flowId"),providerId:m(e,"providerId"),providerName:m(e,"providerName"),status:Kr(e.status),progress:j(i=>{if(typeof i!="string")throw new Error("Expected progress item string");return i})(e.progress),...S("error",C(e,"error")),...S("auth",Gr(e.auth)),...S("prompt",Qr(e.prompt)),...S("select",Zr(e.select))}}function Kr(t){if(t!=="running"&&t!=="complete"&&t!=="error"&&t!=="cancelled")throw new Error("Invalid OAuth flow status");return t}function Gr(t){if(t===void 0)return;const e=w(t);return{url:m(e,"url"),...S("instructions",C(e,"instructions"))}}function Qr(t){if(t===void 0)return;const e=w(t),s=m(e,"kind");if(s!=="prompt"&&s!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(e,"requestId"),message:m(e,"message"),kind:s,...S("placeholder",C(e,"placeholder")),...e.allowEmpty===!0?{allowEmpty:!0}:{}}}function Zr(t){if(t===void 0)return;const e=w(t);return{requestId:m(e,"requestId"),message:m(e,"message"),options:j(ci)(e.options)}}function Jr(t){if(t===void 0)return{};const e=w(t);return{contextUsage:{tokens:Cs(e,"tokens"),contextWindow:U(e,"contextWindow"),percent:Cs(e,"percent")}}}function Yr(t){const e=w(t),s=m(e,"source");if(s!=="extension"&&s!=="prompt"&&s!=="skill"&&s!=="builtin")throw new Error("Invalid command source");return{name:m(e,"name"),source:s,...S("description",C(e,"description"))}}function li(t){const e=w(t),s=m(e,"kind");if(s!=="tracked"&&s!=="untracked"&&s!=="other")throw new Error("Invalid file kind");return{path:m(e,"path"),kind:s}}function Xr(t){const e=w(t);return{path:m(e,"path"),entries:j(eo)(e.entries),scannedAt:m(e,"scannedAt"),truncated:F(e,"truncated")}}function eo(t){const e=w(t),s=m(e,"type");if(s!=="file"&&s!=="directory"&&s!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(e,"name"),path:m(e,"path"),type:s,...S("size",ze(e,"size")),...S("modifiedAt",C(e,"modifiedAt"))}}function to(t){const e=w(t),s=m(e,"encoding");if(s!=="utf8")throw new Error("Invalid file encoding");return{path:m(e,"path"),...S("language",C(e,"language")),encoding:s,size:U(e,"size"),modifiedAt:m(e,"modifiedAt"),content:m(e,"content"),truncated:F(e,"truncated"),binary:F(e,"binary")}}function so(t){const e=w(t);return{isGitRepo:F(e,"isGitRepo"),hash:m(e,"hash"),...S("branch",C(e,"branch")),...S("upstream",C(e,"upstream")),...S("ahead",ze(e,"ahead")),...S("behind",ze(e,"behind")),files:j(io)(e.files)}}function io(t){const e=w(t);return{path:m(e,"path"),...S("oldPath",C(e,"oldPath")),index:ks(e.index),workingTree:ks(e.workingTree)}}function ks(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 ro(t){const e=w(t);return{...S("path",C(e,"path")),staged:F(e,"staged"),hash:m(e,"hash"),diff:m(e,"diff"),truncated:F(e,"truncated")}}function $s(t){const e=w(t);return{id:m(e,"id"),cwd:m(e,"cwd"),name:m(e,"name"),createdAt:m(e,"createdAt"),exited:F(e,"exited"),...S("exitCode",ze(e,"exitCode"))}}function Ps(t){const e=w(t),s=m(e,"type");if(s==="unsupported")return{type:s,message:m(e,"message")};if(s==="select")return{type:s,requestId:m(e,"requestId"),title:m(e,"title"),options:j(ci)(e.options)};if(s==="done")return{type:s,...S("message",C(e,"message")),...oo(e.session)};throw new Error("Invalid command result type")}function ci(t){const e=w(t);return{value:m(e,"value"),label:m(e,"label"),...S("description",C(e,"description"))}}function oo(t){return t===void 0?{}:{session:$t(t)}}function Ke(t){if(w(t).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function di(t){if(w(t).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function no(t){if(w(t).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function ao(t){if(w(t).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function lo(t){if(w(t).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function co(t){if(w(t).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function po(t){if(w(t).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function ze(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 Cs(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 S(t,e){return e===void 0?{}:{[t]:e}}function ho(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 uo(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 fo={projects:()=>y("/api/projects",j(Ss)),addProject:(t,e,s)=>y("/api/projects",Ss,{method:"POST",body:JSON.stringify({path:t,name:e,create:s})}),closeProject:t=>y(`/api/projects/${encodeURIComponent(t)}`,di,{method:"DELETE"}),projectDirectories:t=>y(`/api/project-directories?q=${encodeURIComponent(t)}`,j(li))},go={workspaces:t=>y(`/api/projects/${t}/workspaces`,j(Or)),workspaceTree:(t,e,s="")=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/tree?path=${encodeURIComponent(s)}`,Xr),workspaceFile:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/file?path=${encodeURIComponent(s)}`,to)},mo={sessions:t=>y(`/api/sessions?cwd=${encodeURIComponent(t)}`,j($t)),startSession:t=>y("/api/sessions",$t,{method:"POST",body:JSON.stringify({cwd:t})}),messages:(t,e)=>y(uo(t,e),Dr),status:t=>y(`/api/sessions/${t}/status`,Ee),models:t=>y(`/api/sessions/${t}/models`,qr),setModel:(t,e,s)=>y(`/api/sessions/${t}/model`,Ee,{method:"POST",body:JSON.stringify({provider:e,modelId:s})}),cycleModel:(t,e)=>y(`/api/sessions/${t}/model/cycle`,Ee,{method:"POST",body:JSON.stringify({direction:e})}),thinkingLevels:t=>y(`/api/sessions/${t}/thinking-levels`,zr),setThinkingLevel:(t,e)=>y(`/api/sessions/${t}/thinking-level`,Ee,{method:"POST",body:JSON.stringify({level:e})}),cycleThinkingLevel:t=>y(`/api/sessions/${t}/thinking-level/cycle`,Ee,{method:"POST"}),commands:t=>y(`/api/sessions/${t}/commands`,j(Yr)),prompt:(t,e,s)=>y(`/api/sessions/${t}/prompt`,Ke,{method:"POST",body:JSON.stringify(s===void 0?{text:e}:{text:e,streamingBehavior:s})}),shell:(t,e)=>y(`/api/sessions/${t}/shell`,Ke,{method:"POST",body:JSON.stringify({text:e})}),runCommand:(t,e)=>y(`/api/sessions/${t}/commands/run`,Ps,{method:"POST",body:JSON.stringify({text:e})}),respondToCommand:(t,e,s)=>y(`/api/sessions/${t}/commands/respond`,Ps,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),abort:t=>y(`/api/sessions/${t}/abort`,no,{method:"POST"}),stop:t=>y(`/api/sessions/${t}/stop`,ao,{method:"POST"}),archive:t=>y(`/api/sessions/${t}/archive`,lo,{method:"POST"}),restore:t=>y(`/api/sessions/${t}/restore`,co,{method:"POST"}),detachParent:t=>y(`/api/sessions/${t}/detach-parent`,po,{method:"POST"}),authProviders:t=>{const e=new URLSearchParams;t?.mode!==void 0&&e.set("mode",t.mode),t?.authType!==void 0&&e.set("authType",t.authType);const s=e.toString();return y(`/api/auth/providers${s===""?"":`?${s}`}`,Vr)},saveApiKey:(t,e)=>y("/api/auth/api-key",Ke,{method:"POST",body:JSON.stringify({providerId:t,key:e})}),logoutProvider:t=>y("/api/auth/logout",Ke,{method:"POST",body:JSON.stringify({providerId:t})}),startOAuthLogin:t=>y("/api/auth/oauth",Ve,{method:"POST",body:JSON.stringify({providerId:t})}),oauthFlow:t=>y(`/api/auth/oauth/${encodeURIComponent(t)}`,Ve),respondOAuthFlow:(t,e,s)=>y(`/api/auth/oauth/${encodeURIComponent(t)}/respond`,Ve,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),cancelOAuthFlow:t=>y(`/api/auth/oauth/${encodeURIComponent(t)}/cancel`,Ve,{method:"POST"})},pi={terminals:(t,e)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,j($s)),startTerminal:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,$s,{method:"POST",body:JSON.stringify(s??{})}),closeTerminal:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}`,di,{method:"DELETE"})},bo={files:(t,e,s,i)=>y(`/api/files?cwd=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}${s!==void 0?`&kind=${encodeURIComponent(s)}`:""}${i!==void 0?`&mode=${encodeURIComponent(i)}`:""}`,j(li))},yo={gitStatus:(t,e)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/status`,so),gitDiff:(t,e,s)=>y(ho(t,e,s),ro)},D={...fo,...go,...mo,...pi,...bo,...yo};function wo(t){return new WebSocket(`${Ft()}/api/sessions/${t}/events`)}function Yc(t,e,s,i){const r=i===void 0?"":`?cols=${encodeURIComponent(String(i.cols))}&rows=${encodeURIComponent(String(i.rows))}`;return new WebSocket(`${Ft()}/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}/socket${r}`)}function vo(){return new WebSocket(`${Ft()}/api/events`)}function Ft(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function xo(){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,modelDialog:void 0,thinkingDialog:void 0,authDialog: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,activeTerminalCount:0,error:""}}class So{constructor(e,s,i,r={}){this.getState=e,this.setState=s,this.applyStatus=i,this.api=r.api??D,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(e){const s=ko(e);return s===void 0?!1:(s.command==="login"?this.openLogin(s.providerId):this.openLogout(s.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==""){await this.openLoginProvider(e);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(e){try{const{providers:s}=await this.api.authProviders({mode:"login",authType:e});this.setState({authDialog:{step:"providers",mode:"login",authType:e,providers:s}})}catch(s){this.setState({error:String(s)})}}async selectLoginProvider(e,s){const i=this.getState().authDialog;if(i?.step!=="providers")return;const r=i.providers.find(o=>o.id===e&&(s===void 0||o.authType===s));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(e){const s=this.getState().authDialog;if(s?.step!=="apiKey")return;const i={...s};delete i.error,this.setState({authDialog:{...i,value:e}})}async saveApiKey(){const e=this.getState().authDialog;if(e?.step!=="apiKey")return;const s=e.value.trim();if(s===""){this.setState({authDialog:{...e,error:"API key is required"}});return}const i={...e};delete i.error,this.setState({authDialog:{...i,saving:!0}});try{await this.api.saveApiKey(e.provider.id,s),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...e,saving:!1,error:String(r)}})}}async openLogout(e){try{const{providers:s}=await this.api.authProviders({mode:"logout"});if(e!==void 0&&e!==""){const i=s.find(r=>r.id===e);i!==void 0?await this.logoutProvider(i.id):this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:"logout",providers:s}})}catch(s){this.setState({error:String(s)})}}async logoutProvider(e){try{await this.api.logoutProvider(e),this.closeDialog(),this.refreshStatus()}catch(s){this.setState({error:String(s)})}}updateOAuthInput(e){const s=this.getState().authDialog;if(s?.step!=="oauth")return;const i={...s};delete i.error,this.setState({authDialog:{...i,inputValue:e}})}async respondOAuth(e){const s=this.getState().authDialog;if(s?.step!=="oauth")return;const i=s.flow.prompt??s.flow.select;if(i===void 0)return;const r=e??s.inputValue??"",o={...s};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(s.flow.flowId,i.requestId,r);this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...s,responding:!1,error:String(n)}})}}async cancelOAuth(){const e=this.getState().authDialog;if(e?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(e.flow.flowId)}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{const{providers:s}=await this.api.authProviders({mode:"login"}),i=s.filter(o=>o.id===e);if(i.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(i.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:i}});return}const r=i[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(s){this.setState({error:String(s)})}}async startOAuth(e){try{const s=await this.api.startOAuthLogin(e.id);this.updateOAuthFlow(s),this.startPolling(s.flowId)}catch(s){this.setState({error:String(s)})}}updateOAuthFlow(e){if(e.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(e.status==="error"||e.status==="cancelled")&&this.stopPolling();const s=this.getState().authDialog,i=s?.step==="oauth"&&s.flow.flowId===e.flowId?s.inputValue??"":"",r=s?.step==="oauth"?s.flow.prompt?.requestId??s.flow.select?.requestId:void 0,o=e.prompt?.requestId??e.select?.requestId,n=r!==void 0&&r===o,a=n?i:"",l=n&&s?.step==="oauth"?s.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:e,inputValue:a,responding:l}})}startPolling(e){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(e)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e){const s=this.getState().authDialog;if(s?.step!=="oauth"||s.flow.flowId!==e){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(e))}catch(i){this.stopPolling(),this.setState({authDialog:{...s,error:String(i)}})}}async refreshStatus(){const e=this.sessionId();if(e!==void 0)try{this.applyStatus(await this.api.status(e))}catch{}}sessionId(){const e=this.getState().selectedSession;if(!(e===void 0||e.archived===!0))return e.id}}function ko(t){const e=t.trim(),s=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(e);if(s===null)return;const i=s[1];if(i!=="login"&&i!=="logout")return;const r=s[2];return r===void 0||r===""?{command:i}:{command:i,providerId:r}}function st(t){return t.replaceAll(":",".")}function $o(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 Ts(t,e){const s=$o(t)[e];return Array.isArray(s)?s[0]:s===""?void 0:s}function it(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));Po(r,i)}function Po(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 As=st("core:workspace.files");class Co{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 D.workspaceTree(e.id,s.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await D.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:Ao(this.getState().expandedDirs,e)});return}try{const r=await D.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"}),it(As,"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{const r=await D.workspaceFile(s.id,i.id,e);this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==e)return;if(To(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),it(As,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function To(t){const e=String(t);return e.includes("Path does not exist")||e.includes("ENOENT")||e.includes("no such file or directory")}function Ao(t,e){return Object.fromEntries(Object.entries(t).filter(([s])=>s!==e))}const Is=st("core:workspace.git");class Io{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 D.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}),it(Is,"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"}),it(Is,"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([D.gitDiff(s.id,i.id,{path:e}),D.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 Mo{constructor(e,s,i){this.getState=e,this.setState=s,this.workspaces=i}async loadProjects(){this.setState({error:""});try{this.setState({projects:await D.projects()})}catch(e){this.setState({error:String(e)})}}async addProject(e,s){if(e.trim()!=="")try{const i=await D.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 D.closeProject(e),this.workspaces.forgetProject(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)})}}}const Pt="pi-web:cached-new-sessions:v1",Eo="browserCachedNew";function We(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ms(t,e=We()){if(t.messageCount!==0||t.archived===!0)return;const s=zt(e).filter(i=>i.id!==t.id);Wt([Ct(t),...s],e)}function Ct(t){return{...t,browserCachedNew:!0}}function Es(t,e=We()){const s=zt(e).filter(i=>i.id!==t);Wt(s,e)}function Ro(t,e,s=We()){const i=new Set(e.map(a=>a.id)),r=zt(s),o=r.filter(a=>!i.has(a.id));return o.length!==r.length&&Wt(o,s),[...o.filter(a=>a.cwd===t),...e]}function xe(t){return t===void 0?!1:Oo(t)&&t.browserCachedNew===!0}function _o(t){return{id:t.id,path:t.path,cwd:t.cwd,...t.name===void 0?{}:{name:t.name},created:t.created,modified:t.modified,messageCount:t.messageCount,firstMessage:t.firstMessage,...t.parentSessionPath===void 0?{}:{parentSessionPath:t.parentSessionPath},...t.archived===!0?{archived:!0}:{},...t.archivedAt===void 0?{}:{archivedAt:t.archivedAt}}}function zt(t=We()){try{const e=t?.getItem(Pt);if(e==null||e==="")return[];const s=JSON.parse(e);return Array.isArray(s)?s.flatMap(i=>Do(i)):[]}catch{return[]}}function Wt(t,e=We()){try{t.length===0?e?.removeItem(Pt):e?.setItem(Pt,JSON.stringify(t))}catch{}}function Do(t){if(!Lo(t))return[];const e=we(t,"id"),s=we(t,"path"),i=we(t,"cwd"),r=we(t,"created"),o=we(t,"modified"),n=we(t,"firstMessage"),a=jo(t,"messageCount");if(e===void 0||s===void 0||i===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const l=Rs(t,"name"),c=Rs(t,"parentSessionPath");return[{id:e,path:s,cwd:i,...l===void 0?{}:{name:l},created:r,modified:o,messageCount:a,firstMessage:n,...c===void 0?{}:{parentSessionPath:c},browserCachedNew:!0}]}function Oo(t){return Eo in t}function Lo(t){return typeof t=="object"&&t!==null}function we(t,e){const s=t[e];return typeof s=="string"?s:void 0}function Rs(t,e){const s=t[e];return s===void 0||typeof s!="string"?void 0:s}function jo(t,e){const s=t[e];return typeof s=="number"?s:void 0}function No(t){return t.flatMap(ft).filter(e=>e.parts.length>0)}function J(t,e){return{role:t,parts:[{type:"text",text:e}]}}function Ge(t,e){const s=Ho(e);return s===void 0?t:{...t,meta:s}}function qo(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,J(e,s)]}function Fo(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 ft(t){if(zo(t))return[t];if(M(t,"role")==="bashExecution")return[Ge(Go(t),t)];const e=Qo(M(t,"role")),s=Zo(oe(t,"content"),t),i=e==="user"?Wo(s):void 0;if(i!==void 0)return i.map(a=>Ge(a,t));const r=Bo(t);if(e==="tool")return[Ge({role:e,parts:s,...r===void 0?{}:{source:r}},t)];const o=s.filter(a=>a.type!=="empty"),n=e==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":e;return o.length>0?[Ge({role:n,parts:o,...r===void 0?{}:{source:r}},t)]:[]}function zo(t){const e=M(t,"role");return(e==="user"||e==="assistant"||e==="tool"||e==="system"||e==="bash"||e==="skill")&&Array.isArray(oe(t,"parts"))}function Wo(t){if(t.length!==1||t[0]?.type!=="text")return;const e=Uo(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 Uo(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 Bo(t){const e=M(t,"source");if(e==="compaction"||e==="branch_summary")return e}function Ho(t){const e=Vo(oe(t,"timestamp")),s=Ko(t);if(!(e===void 0&&s===void 0))return{...e===void 0?{}:{timestamp:e},...s===void 0?{}:{model:s}}}function Vo(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 Ko(t){if(M(t,"role")!=="assistant")return;const e=M(t,"provider"),s=M(t,"model"),i=M(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 Go(t){const e=M(t,"command")??"",s=Xe(t,"excludeFromContext")===!0?["excluded from context","",`$ ${e}`]:[`$ ${e}`],i=oe(t,"output");i!=null&&s.push("",rt(i));const r=oe(t,"exitCode");r!=null&&s.push("",`exit ${rt(r)}`),Xe(t,"cancelled")===!0&&s.push("","cancelled"),Xe(t,"truncated")===!0&&s.push("","output truncated");const o=M(t,"fullOutputPath");return o!==void 0&&o!==""&&s.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:s.join(`
5
+ `)}]}}function Qo(t){return t==="assistant"?"assistant":t==="user"?"user":t==="toolResult"?"tool":"system"}function Zo(t,e){return typeof t=="string"?t!==""?[{type:"text",text:t}]:[]:Array.isArray(t)?t.flatMap(s=>{const i=M(s,"type"),r=M(s,"text");if(i==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(i==="thinking"){const o=M(s,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(i==="toolCall"){const o=M(s,"name")??"tool",n=oe(s,"arguments"),a=o==="read"?Jo(M(n,"path")):void 0;return a!==void 0?[{type:"skillRead",...a}]:[{type:"toolCall",toolName:o,summary:hi(n)}]}return i==="image"?[{type:"text",text:"[image]"}]:_s(s)}).map(s=>s.type==="text"&&M(e,"role")==="toolResult"?{type:"toolResult",toolName:M(e,"toolName")??"tool",text:s.text,isError:Xe(e,"isError")===!0}:s):_s(t)}function Jo(t){if(t===void 0||t==="")return;const e=t.replace(/\\/g,"/");if(!e.endsWith("/SKILL.md")&&e!=="SKILL.md")return;const s=e.split("/").at(-2);if(!(s===void 0||s===""))return{name:s,path:t}}function _s(t){return t==null?[]:typeof t=="object"?[{type:"text",text:hi(t)}]:[{type:"text",text:rt(t)}]}function hi(t){if(!ui(t))return rt(t);const e=M(t,"command");if(e!==void 0)return e;const s=M(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}: ${Yo(n)}`).join(" · ")}function Yo(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 ui(t){return typeof t=="object"&&t!==null}function oe(t,e){return ui(t)?t[e]:void 0}function M(t,e){const s=oe(t,e);return typeof s=="string"?s:void 0}function Xe(t,e){const s=oe(t,e);return typeof s=="boolean"?s:void 0}function rt(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):""}const Xo="pi-web:prompt-draft:";function ot(t){return`${Xo}${t}`}function gt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function fi(t,e=gt()){try{return e?.getItem(ot(t))??""}catch{return""}}function Tt(t,e,s=gt()){try{e?s?.setItem(ot(t),e):s?.removeItem(ot(t))}catch{}}function Ut(t,e=gt()){try{e?.removeItem(ot(t))}catch{}}function en(t,e,s=gt()){const i=fi(t,s);i!==""&&(Tt(e,i,s),Ut(t,s))}function tn(t,e){return J("bash",`${e===!0?`excluded from context
6
+
7
+ `:""}$ ${t}`)}function sn(t,e){const s=t.at(-1),i=s?.parts.at(-1);if(s?.role!=="bash"||i?.type!=="text")return[...t,J("bash",e)];const r=on(i.text)?"":`
8
+
9
+ `;return[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:i.text+r+e}]}]}function rn(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 on(t){const e=t.lastIndexOf(`
15
+
16
+ `),s=t.lastIndexOf("$ ");return e>s}function nn(t,e){if(e.type==="message.append")return pn(t,e.message);if(e.type==="assistant.delta")return qo(t,"assistant",e.text);if(e.type==="assistant.thinking.delta")return Fo(t,e.text);if(e.type==="tool.start")return Ls(t,{role:"assistant",content:[{type:"toolCall",name:e.toolName,arguments:e.args}]});if(e.type==="tool.end")return Ls(t,{role:"toolResult",toolName:e.toolName,content:e.content??[{type:"text",text:e.text}],isError:e.isError});if(e.type==="shell.start")return[...t,tn(e.command,e.excludeFromContext)];if(e.type==="shell.chunk")return sn(t,e.chunk);if(e.type==="shell.end")return rn(t,e);if(e.type==="command.output")return[...t,J(e.level==="error"?"system":"tool",e.message)];if(e.type==="session.error")return[...t,J("system",e.message)];if(e.type==="message.end")return e.message===void 0?void 0:an(t,e.message)}function an(t,e){const s=ft(e)[0];if(s===void 0)return;const i=ln(t,s);if(i>=0)return[...t.slice(0,i),s,...t.slice(i+1)];const r=t.at(-1);return r?.role!==s.role?[...t,s]:s.role==="assistant"||dn(r,s)?[...t.slice(0,-1),s]:[...t,s]}function ln(t,e){const s=nt(e);if(s.length===0)return-1;for(let i=t.length-1;i>=0;i--){const r=t[i];if(r?.role!=="skill")continue;const o=nt(r);if(gi(o,s))return i}return-1}function nt(t){return t===void 0?[]:t.parts.filter(e=>e.type==="skillRead")}function gi(t,e){return t.length===e.length&&t.every((s,i)=>cn(s,e[i]))}function cn(t,e){return e===void 0?!1:Ds(t.path)===Ds(e.path)||t.name===e.name}function Ds(t){return t.replace(/\\/g,"/")}function dn(t,e){return Os(t)===Os(e)}function Os(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join(`
17
+
18
+ `)}function pn(t,e){const s=ft(e);return s.length===0?t:[...t,...s]}function Ls(t,e){return ft(e).reduce(hn,t)}function hn(t,e){const s=t.at(-1);return e.role==="skill"&&gi(nt(s),nt(e))?t:s?.role===e.role&&e.role!=="skill"?[...t.slice(0,-1),{...s,parts:[...s.parts,...e.parts]}]:[...t,e]}const un="pi-web:chat-history:v2:",fn=1800*1e3;function gn(t){try{const e=sessionStorage.getItem(At(t));if(e===null||e==="")return;const s=JSON.parse(e);if(!vn(s))return;if(Date.now()-s.savedAt>fn){sessionStorage.removeItem(At(t));return}return{messages:s.messages,start:s.start,total:s.total}}catch{return}}function mn(t,e){try{sessionStorage.setItem(At(t),JSON.stringify({...e,savedAt:Date.now()}))}catch{}}function bn(t,e){if(t===void 0||!It(t))return e;if(!It(e))return t;if(yn(t,e))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 js(r,s,t),js(r,s,e),wn(r)?e:{start:s,total:Math.max(t.total,e.total),messages:r}}function yn(t,e){return t.total>e.total&&t.start===0&&e.start===0&&e.messages.length===e.total}function wn(t){for(let e=0;e<t.length;e+=1)if(!(e in t)||t[e]===void 0)return!0;return!1}function js(t,e,s){s.messages.forEach((i,r)=>{t[s.start-e+r]=i})}function At(t){return`${un}${t}`}function vn(t){if(typeof t!="object"||t===null||!("messages"in t)||!("start"in t)||!("total"in t)||!("savedAt"in t))return!1;const{messages:e,start:s,total:i,savedAt:r}=t;return Array.isArray(e)&&typeof s=="number"&&typeof i=="number"&&typeof r=="number"&&It({messages:e,start:s,total:i})}function It(t){return Number.isInteger(t.start)&&Number.isInteger(t.total)&&t.start>=0&&t.total>=t.start&&t.messages.length<=t.total-t.start&&!t.messages.some(xn)}function xn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&!("content"in t)&&typeof t.role=="string"&&Array.isArray(t.parts)}const Sn={read:gn,write:mn};class kn{constructor(e=Sn){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return Ns(this.rawHistoryPage(e))}mergeHistory(e,s){const i=bn(this.rawHistoryPage(e),s);return this.rawHistoryPages.set(e,i),this.cache.write(e,i),Ns(i)}applyLiveEvent(e,s){return nn(e,s)}rawHistoryPage(e){const s=this.rawHistoryPages.get(e)??this.cache.read(e);return s!==void 0&&this.rawHistoryPages.set(e,s),s}}function Ns(t){return{messages:No(t?.messages??[]),messagePageStart:t?.start??0,messagePageTotal:t?.total??0}}function mi(t){const e=t.trimStart();return e.startsWith("!")?{kind:"shell",excludeFromContext:e.startsWith("!!")}:bi(t).startsWith("/")?{kind:"command"}:Pn(t)?{kind:"file"}:{kind:"normal"}}function $n(t){return mi(t).kind==="shell"}function bi(t){const e=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
19
+ `))+1;return t.slice(e)}function Pn(t){const e=bi(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 Cn{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1}connect(e,s,i){this.close(),this.sessionId=e,this.onEvent=s,this.onReconnect=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),wi(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const e=wo(this.sessionId);this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},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 yi(e);An(s)&&this.onEvent?.(s)}}class Tn{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(e,s){this.close(),this.onEvent=e,this.onOpen=s,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),wi(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const e=vo();this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},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 yi(e);Mn(s)&&this.onEvent?.(s)}}function An(t){const e=Bt(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 In(t){const e=Bt(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function Mn(t){const e=Bt(t);return In(t)||e==="terminal.created"||e==="terminal.exited"||e==="terminal.closed"}function Bt(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function yi(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 wi(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()}}class En{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}}function Rn(t,e){const s=e?.targetSessionId;if(s!==void 0&&s!=="")return _n(t,s);const i=e?.latestSessionId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t.find(r=>r.archived!==!0):t.find(r=>r.archived!==!0)}function _n(t,e){return t.find(s=>s.id===e||s.id.startsWith(e))}function Dn(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function On(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 Re=100;class Ln{constructor(e,s,i,r=new En,o={}){this.getState=e,this.setState=s,this.updateUrl=i,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Cn,this.api=o.api??D,this.transcripts=o.transcripts??new kn}applyGlobalEvent(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.clearPendingTranscriptEvents()}clearActiveSession(){this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),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 this.api.startSession(e.path);Ms(s);const i=Ct(s);this.setState({sessions:[i,...this.getState().sessions]}),await this.selectSession(i)}catch(s){this.setState({error:String(s)})}}preferredSession(e,s,i){return Rn(s,{targetSessionId:i,latestSessionId:this.sessionSelection.latestSessionId(e)})}async selectSession(e,s){this.sessionSelection.rememberSession(e);const i=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=this.transcripts.cachedView(e.id);this.setState({selectedSession:e,...r,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 u=await this.api.messages(e.id,{limit:Re});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const p=this.transcripts.mergeHistory(e.id,u);this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),s?.updateUrl!==!1&&this.updateUrl();return}const o=[];this.socket.connect(e.id,u=>o.push(u),()=>{this.refreshSelectedSession(e.id)});const[n,a]=await Promise.all([this.api.messages(e.id,{limit:Re}),this.api.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const l=this.transcripts.mergeHistory(e.id,n),c=a.isStreaming;this.catchupStreamSessionId=c?e.id:void 0,this.setState({...l,isLoadingEarlierMessages:!1,isReceivingPartialStream:c,status:a,activity:this.getState().sessionActivities[e.id]}),this.applyStatus(a);for(const u of o)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),s?.updateUrl!==!1&&this.updateUrl()}catch(o){if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;if(xe(e)&&qn(o)){await this.recreateCachedNewSession(e,s);return}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 this.api.messages(s.id,{before:e.messagePageStart,limit:Re});if(this.getState().selectedSession?.id!==s.id)return;const r=this.transcripts.mergeHistory(s.id,i);this.setState(r)}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($n(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,e,s),this.markCachedNewSessionPersisted(r)}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,J("user",e)]});try{await this.api.shell(s.id,e),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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,J("user",e)]});try{this.applyCommandResult(await this.api.runCommand(s.id,e)),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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 this.api.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(e){if(xe(e)){await this.deleteCachedNewSession(e);return}try{await this.api.archive(e.id);const s=this.getState(),i=Dn(s.sessions,e.id,new Date().toISOString()),r=On(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 deleteCachedNewSession(e=this.getState().selectedSession){if(!xe(e))return;this.api.stop(e.id).catch(()=>{}),Es(e.id),Ut(e.id);const s=this.getState().sessions.filter(r=>r.id!==e.id);if(this.setState({sessions:s}),this.getState().selectedSession?.id!==e.id)return;const i=s.find(r=>r.archived!==!0)??s[0];i!==void 0?await this.selectSession(i):(this.clearActiveSession(),this.updateUrl())}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.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 detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e.id);const s={...e};delete s.parentSessionPath,this.replaceSession(s)}catch(s){this.setState({error:String(s)})}}async listModels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e.id)).models}catch(s){return this.setState({error:String(s)}),[]}}async setModel(e,s){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setModel(i.id,e,s))}catch(r){this.setState({error:String(r)})}}async cycleModel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.cycleModel(s.id,e))}catch(i){this.setState({error:String(i)})}}async listThinkingLevels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e.id)).levels}catch(s){return this.setState({error:String(s)}),[]}}async setThinkingLevel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(s.id,e))}catch(i){this.setState({error:String(i)})}}async cycleThinkingLevel(){const e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e.id))}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await this.api.abort(e.id)}catch(s){this.setState({error:String(s)})}}async refreshSelectedSession(e=this.getState().selectedSession?.id){const s=this.getState().selectedSession;if(!(e===void 0||s?.id!==e||s.archived===!0))try{this.flushPendingTranscriptEvents();const[i,r]=await Promise.all([this.api.messages(e,{limit:Re}),this.api.status(e)]);if(this.getState().selectedSession?.id!==e)return;const o=this.transcripts.mergeHistory(e,i);this.setState({...o,status:r,activity:this.getState().sessionActivities[e],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}catch(i){this.getState().selectedSession?.id===e&&this.setState({error:String(i)})}}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})}async recreateCachedNewSession(e,s){try{const i=await this.api.startSession(e.cwd);Ms(i),en(e.id,i.id),Es(e.id);const r=Ct(i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==e.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(s?.updateUrl===!1?{replace:!0}:void 0)}catch(i){this.setState({error:String(i)})}}markCachedNewSessionPersisted(e){xe(e)&&this.replaceSession(_o(e))}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,J(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(jn(e))return}if(Nn(e)){this.queueTranscriptEvent(e);return}this.flushPendingTranscriptEvents();const i=this.transcripts.applyLiveEvent(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)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let s=this.getState().messages;for(const i of e)s=this.transcripts.applyLiveEvent(s,i)??s;s!==this.getState().messages&&this.setState({messages:s})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}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 this.api.messages(e,{limit:Re});if(this.getState().selectedSession?.id!==e)return;this.setState(this.transcripts.mergeHistory(e,s))}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function jn(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)}function Nn(t){return t.type==="assistant.delta"||t.type==="assistant.thinking.delta"||t.type==="shell.chunk"}function qn(t){return t instanceof Error&&t.message.toLowerCase().includes("session not found")}class Fn{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}}function zn(t,e){const s=e?.targetWorkspaceId;if(s!==void 0&&s!=="")return t.find(r=>r.id===s);const i=e?.latestWorkspaceId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t[0]:t[0]}class Wn{constructor(e,s,i,r,o=new Fn){this.getState=e,this.setState=s,this.updateUrl=i,this.sessions=r,this.workspaceSelection=o}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()}forgetProject(e){this.workspaceSelection.forgetProject(e)}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 D.workspaces(e.id);this.setState({workspaces:i});const r=zn(i,{targetWorkspaceId:s?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(e.id)});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.workspaceSelection.rememberWorkspace(e),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=Ro(e.path,await D.sessions(e.path));this.setState({sessions:i});const r=this.sessions.preferredSession(e.path,i,s?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}}const Un=1200;class Bn{constructor(){this.pendingTokens=[]}handle(e,s){const i=Vn(e);if(i===void 0||!qs(i))return!1;const r=s.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:vi(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!qs(i)?[...this.pendingTokens,i]:[i],n=r.find(l=>Gn(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>xi(l.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},Un)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Hn(t){return vi(t).map(e=>e.split("+").map(s=>s==="mod"?Fs()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?Fs()?"⌥":"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 Vn(t){if(t.isComposing)return;const e=Kn(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 vi(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function Kn(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 Gn(t,e){return t.length===e.length&&xi(t,e)}function xi(t,e){return e.every((s,i)=>t[i]===s)}function qs(t){return t.includes("+")}function Fs(){return navigator.userAgent.toLowerCase().includes("mac")}function Qn(){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:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:t=>t.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:t=>t.logoutAuth()},{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:Qe,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:zs,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Qe,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:zs,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Qe,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:Qe,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&&Zn(t.state.status),run:t=>t.stopActiveWork()}]}function Qe(t){return t.state.selectedWorkspace!==void 0}function zs(t){return t.state.selectedWorkspace?.isGitRepo===!0}function Zn(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const Jn="modulepreload",Yn=function(t){return"/"+t},Ws={},Si=function(e,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=l(s.map(c=>{if(c=Yn(c),c in Ws)return;Ws[c]=!0;const u=c.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Jn,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((g,b)=>{f.addEventListener("load",g),f.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${c}`)))})}))}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 Xn(){return[{id:"workspace.files",title:"Files",order:10,render:ea},{id:"workspace.git",title:"Git",order:20,visible:({workspace:t})=>t.isGitRepo,render:ra},{id:"workspace.terminal",title:"Terminal",order:30,badge:t=>t.activeTerminalCount>0?t.activeTerminalCount:void 0,render:ia}]}function ea(t){return d`
20
+ <section class="toolbar">
21
+ <strong>Files</strong>
22
+ ${t.fileTreeStale?d`<span class="stale">stale</span>`:null}
23
+ <button @click=${t.onRefreshFiles}>Refresh</button>
24
+ </section>
25
+ <section class="split">
26
+ <div class="list tree">
27
+ ${t.fileTree.length===0?d`<p class="muted">No files loaded.</p>`:t.fileTree.map(e=>ki(t,e,0))}
28
+ </div>
29
+ <div class="viewer">
30
+ ${sa(t)}
31
+ </div>
32
+ </section>
33
+ `}function ki(t,e,s){const i=t.expandedDirs[e.path],r=i!==void 0;return d`
34
+ <button class="row" style=${`--depth:${String(s)}`} @click=${()=>{ta(t,e)}}>
35
+ <span>${e.type==="directory"?r?"▾":"▸":"·"}</span>
36
+ <span>${e.name}</span>
37
+ </button>
38
+ ${r?i.map(o=>ki(t,o,s+1)):null}
39
+ `}function ta(t,e){e.type==="directory"?t.onExpandDir(e.path):t.onSelectFile(e.path)}function sa(t){const e=t.selectedFileContent;return t.selectedFilePath===void 0||t.selectedFilePath===""?d`<p class="muted">Select a file.</p>`:e===void 0?d`<p class="muted">Loading ${t.selectedFilePath}…</p>`:e.binary?d`<p class="muted">Binary file: ${e.path}</p>`:($i(),d`
40
+ <div class="viewer-header"><strong>${e.path}</strong><small>${e.language??"text"}${e.truncated?" · truncated":""}</small></div>
41
+ <code-viewer .content=${e.content} .language=${e.language}></code-viewer>
42
+ `)}function ia(t){return aa(),d`<terminal-panel .workspace=${t.workspace} .autoStart=${t.terminalAutoStart}></terminal-panel>`}function ra(t){const e=t.gitStatus;return d`
43
+ <section class="toolbar">
44
+ <strong>Git</strong>
45
+ ${t.gitStale?d`<span class="stale">stale</span>`:null}
46
+ <button @click=${t.onRefreshGit}>Refresh</button>
47
+ </section>
48
+ <section class="split">
49
+ <div class="list">
50
+ ${e===void 0?d`<p class="muted">No status loaded.</p>`:e.isGitRepo?d`
51
+ <p class="summary">${la(e)}</p>
52
+ ${e.files.length===0?d`<p class="muted">No changes.</p>`:e.files.map(s=>d`
53
+ <button class="row ${t.selectedDiffPath===s.path?"selected":""}" @click=${()=>{t.onSelectDiff(s.path)}}>
54
+ <span>${ca(s.index,s.workingTree)}</span>
55
+ <span>${s.path}</span>
56
+ </button>
57
+ `)}
58
+ `:d`<p class="muted">Not a git repository.</p>`}
59
+ </div>
60
+ <div class="viewer">
61
+ ${oa(t)}
62
+ </div>
63
+ </section>
64
+ `}function oa(t){if(t.selectedDiffPath===void 0||t.selectedDiffPath==="")return d`<p class="muted">Select a changed file.</p>`;const e=t.selectedDiff,s=t.selectedStagedDiff;if(e===void 0||s===void 0)return d`<p class="muted">Loading diff…</p>`;const i=[s,e].filter(r=>r.diff!=="");return i.length===0?d`<p class="muted">No staged or unstaged diff.</p>`:d`
65
+ <div class=${i.length===1?"diffs single":"diffs"}>
66
+ ${i.map(r=>na(r))}
67
+ </div>
68
+ `}function na(t){return $i(),d`
69
+ <section class="diff-section">
70
+ <div class="viewer-header"><strong>${t.path??"diff"}</strong><small>${t.staged?"staged":"unstaged"}${t.truncated?" · truncated":""}</small></div>
71
+ <code-viewer .content=${t.diff} .language=${"diff"}></code-viewer>
72
+ </section>
73
+ `}function $i(){Si(()=>import("./CodeViewer-Cp0QKepT.js"),__vite__mapDeps([0,1,2,3]))}function aa(){Si(()=>import("./TerminalPanel-C7TcN1cv.js"),__vite__mapDeps([4,5,6,1,2]))}function la(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 ca(t,e){return(e!=="unmodified"?e:t).slice(0,1).toUpperCase()}const da={apiVersion:1,name:"Pi Web Core",activate:()=>({contributions:{actions:Qn(),workspacePanels:Xn()}})};async function pa(t="/pi-web-plugins/manifest.json"){const e=await ha(t);if(e===void 0)return[];const s=[];for(const i of e.plugins)try{const r=new URL(i.module,new URL(t,window.location.href)).toString(),o=await import(r),n=fa(o,r);s.push({id:i.id,plugin:n})}catch(r){console.warn(`Failed to load Pi Web plugin ${i.module}`,r)}return s}async function ha(t){const e=await fetch(t,{cache:"no-store"});if(e.status!==404){if(!e.ok)throw new Error(`Failed to load plugin manifest: ${e.statusText}`);return ua(await e.json())}}function ua(t){if(!at(t)||!Array.isArray(t.plugins))throw new Error("Invalid plugin manifest");return{plugins:t.plugins.map(e=>{if(!at(e)||typeof e.id!="string"||e.id===""||typeof e.module!="string"||e.module==="")throw new Error("Invalid plugin manifest entry");return{id:e.id,module:e.module}})}}function fa(t,e){if(!at(t))throw new Error(`Plugin module ${e} did not export an object`);const s=t.default;if(!ga(s))throw new Error(`Plugin module ${e} default export is not a PiWebPlugin`);return s}function ga(t){return at(t)&&t.apiVersion===1&&typeof t.name=="string"&&typeof t.activate=="function"}function at(t){return typeof t=="object"&&t!==null}const ma=/^[a-z][a-z0-9.-]*$/u,ba=/^[a-z][a-z0-9.-]*$/u;class ya{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.pluginIds=new Set,this.contributionIds=new Set}register(e){const{id:s,plugin:i}=e;if(this.validatePluginId(s),this.pluginIds.has(s))throw new Error(`Duplicate plugin id: ${s}`);this.pluginIds.add(s);const r=i.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${s}: ${String(r)}`);const n=i.activate({apiVersion:1,pluginId:s,html:d}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(s,a));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(s,a));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(s,a))}getActions(e){return this.actions.map(s=>{const i=s.enabled?.(e),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))}getWorkspaceLabelItems(e,s){const i={state:e,workspace:s};return[...this.workspaceLabels].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>r.visible?.(i)===!1?[]:r.items(i))}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}}qualifyWorkspaceLabelContribution(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(!ma.test(e))throw new Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!ba.test(e))throw new Error(`Invalid contribution id: ${e}`)}}function wa(){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:xa(t.get("tool")),view:Sa(t.get("view"))}}function va(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 xa(t){return t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Sa(t){return t==="chat"?"chat":t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Pi(t){return t!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(t)}const ka=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Ci(t){return t.composedPath().some(e=>$a(e,ka))}function $a(t,e){if(typeof Element<"u"&&t instanceof Element)return t.matches(e);if(!("matches"in t))return!1;const{matches:s}=t;return typeof s=="function"&&s.call(t,e)===!0}function Ht(t,e){Ci(t)||e()}function Vt(t,e){t.key!=="Enter"&&t.key!==" "||Ci(t)||(t.preventDefault(),e())}const Pa=B`
74
+ :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; }
75
+ .shell { display: grid; grid-template-columns: 340px minmax(420px, 1fr) minmax(360px, 42vw); height: 100%; min-height: 0; }
76
+ aside { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid #30363d; overflow: hidden; }
77
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid #30363d; }
78
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; overflow: auto; border-bottom: 1px solid #21262d; }
79
+ session-list { flex: 1 1 auto; min-height: 0; overflow: auto; }
80
+ main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
81
+ .mobile-tabs { display: none; flex: 0 0 auto; gap: 6px; padding: 8px; border-bottom: 1px solid #30363d; overflow-x: auto; }
82
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
83
+ .mobile-tabs button.selected { border-color: #58a6ff; background: #0d2847; }
84
+ .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid #238636; border-radius: 999px; background: #0f2a16; color: #3fb950; padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
85
+ workspace-panel { min-width: 0; min-height: 0; border-left: 1px solid #30363d; overflow: hidden; }
86
+ @media (max-width: 1180px) {
87
+ .shell { grid-template-columns: 340px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
88
+ aside { grid-row: 1 / 3; }
89
+ main { grid-column: 2; grid-row: 1 / 3; }
90
+ .mobile-tabs { display: flex; }
91
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
92
+ .shell.workspace-view > workspace-panel { grid-column: 2; grid-row: 2; display: flex; border-left: 0; }
93
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
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.workspace-view { overflow: hidden; }
97
+ }
98
+ @media (max-width: 760px) {
99
+ .shell { grid-template-columns: minmax(0, 1fr); }
100
+ aside { display: none; }
101
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
102
+ .mobile-navigation-tab { display: block; }
103
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
104
+ main.navigation-view .empty { display: none; }
105
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
106
+ }
107
+ status-bar { flex: 0 0 auto; }
108
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
109
+ prompt-editor, chat-composer { flex: 0 0 auto; }
110
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
111
+ .empty { margin: auto; color: #8b949e; }
112
+ .error { padding: 10px 16px; border-bottom: 1px solid #30363d; color: #ff7b72; }
113
+ `,Ca=B`
114
+ :host { display: flex; flex-direction: column; min-height: 0; color: #e6edf3; background: #0d1117; font: 13px system-ui, sans-serif; }
115
+ header { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid #30363d; }
116
+ .tabs { display: flex; gap: 6px; }
117
+ button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid #30363d; border-radius: 7px; background: #161b22; color: #e6edf3; padding: 5px 7px; cursor: pointer; }
118
+ button.selected { border-color: #58a6ff; background: #0d2847; }
119
+ .tab-badge { display: inline-block; min-width: 14px; border: 1px solid #238636; border-radius: 999px; background: #0f2a16; color: #3fb950; padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
120
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
121
+ small, .muted { color: #8b949e; }
122
+ header small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
123
+ @media (max-width: 1180px) { .tabs { display: none; } }
124
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
125
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
126
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: #8b949e; }
127
+ .workspace-label-link { color: #58a6ff; text-decoration: none; }
128
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
129
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid #21262d; }
130
+ .toolbar button { margin-left: auto; }
131
+ .stale { border: 1px solid #6e5200; border-radius: 999px; color: #d29922; padding: 1px 6px; font-size: 12px; }
132
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
133
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid #30363d; padding: 6px; }
134
+ .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); }
135
+ .row:hover, .row.selected { background: #0d2847; }
136
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
137
+ .summary { margin: 4px 6px 8px; color: #8b949e; }
138
+ .viewer { min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
139
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
140
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
141
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid #30363d; }
142
+ .diff-section:last-child { border-bottom: 0; }
143
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid #21262d; background: #0d1117; }
144
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
145
+ code-viewer { flex: 1 1 auto; min-height: 0; }
146
+ 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; }
147
+ p { margin: 10px; }
148
+ `,Kt=B`
149
+ :host { display: block; color: #e6edf3; font: 14px system-ui, sans-serif; }
150
+ section { padding: 10px; }
151
+ h2 { display: flex; justify-content: space-between; align-items: center; margin: 0 0 8px; color: #8b949e; font-size: 12px; text-transform: uppercase; }
152
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
153
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
154
+ .subheading { margin-top: 14px; }
155
+ .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; }
156
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
157
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
158
+ .action-row:focus-visible { outline: 2px solid #58a6ff; outline-offset: 2px; border-radius: 8px; }
159
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: #58a6ff; background: #0d2847; }
160
+ .action-row.archived .action-main { color: #8b949e; }
161
+ .action-main { box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid #30363d; border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
162
+ .action-row:not(.selected):hover .action-main { background: #21262d; }
163
+ .workspace-row .action-main { border-radius: 8px; }
164
+ .tree-marker { color: #6e7681; margin-right: 5px; }
165
+ .badge { display: inline-block; margin-left: 5px; border: 1px solid #30363d; border-radius: 999px; color: #8b949e; padding: 0 5px; font-size: 11px; font-weight: 400; }
166
+ .action-menu { position: relative; align-self: stretch; }
167
+ .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; }
168
+ .action-menu-toggle:hover { color: #e6edf3; background: #21262d; }
169
+ .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; }
170
+ .action-menu-panel button { display: block; width: 100%; text-align: left; border: 0; background: transparent; color: #e6edf3; }
171
+ .action-menu-panel button:hover { background: #0d2847; }
172
+ button.selected { border-color: #58a6ff; background: #0d2847; }
173
+ button:disabled { opacity: .5; cursor: not-allowed; }
174
+ small { display: block; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
175
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
176
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
177
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: #8b949e; }
178
+ .workspace-label-link { color: #58a6ff; text-decoration: none; }
179
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
180
+ `,Ta=B`
181
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: #e6edf3; font: 14px system-ui, sans-serif; }
182
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
183
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 16px 16px 64px; box-sizing: border-box; }
184
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
185
+ .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; }
186
+ .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); }
187
+ .activity-dock.active { border-color: #238636; color: #3fb950; background: #0f1b12ee; }
188
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
189
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
190
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
191
+ .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; }
192
+ .msg.user { border-color: #2f81f7; background: #0d2847; }
193
+ .msg.tool { border-color: #6e5200; background: #1f1a10; color: #d29922; }
194
+ .msg.system { color: #ff7b72; }
195
+ .msg.bash { border-color: #3fb950; background: #0f1b12; }
196
+ .msg.skill { border-color: #a371f7; background: #21132f; }
197
+ .msg.event-group { padding: 0; border-color: #30363d; background: #0d1117; color: #8b949e; }
198
+ .msg.event-group > summary { display: flex; align-items: center; gap: 8px; padding: 8px 12px; color: #8b949e; }
199
+ .msg.event-group > summary .label { margin: 0; }
200
+ .group-body { padding: 0 12px 12px; }
201
+ .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid #21262d; color: #e6edf3; overflow: hidden; }
202
+ .group-msg.tool { color: #d29922; }
203
+ .group-msg.system { color: #ff7b72; }
204
+ .group-msg.bash { color: #3fb950; }
205
+ .history-boundary { display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: #8b949e; font-size: 12px; text-align: center; }
206
+ .history-load-button { border: 1px solid #30363d; border-radius: 999px; background: #161b22; color: #c9d1d9; padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
207
+ .history-load-button:hover, .history-load-button:focus { border-color: #58a6ff; color: #f0f6fc; }
208
+ .history-load-button:disabled { cursor: default; opacity: .55; }
209
+ .queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid #6e5200; border-radius: 10px; background: #1f1a10; color: #e6edf3; overflow: hidden; }
210
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
211
+ .queued-header strong { color: #d29922; }
212
+ .queued-header small { color: #8b949e; }
213
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid #30363d; }
214
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
215
+ .queued-kind { color: #8b949e; font-size: 12px; text-transform: uppercase; }
216
+ .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: hidden; }
217
+ .session-activity.compacting { border-color: #a371f7; background: #21132f; }
218
+ .session-activity.receiving { border-color: #238636; background: #0f1b12; }
219
+ .session-activity strong { color: #d2a8ff; }
220
+ .session-activity.receiving strong { color: #3fb950; }
221
+ .session-activity span, .session-activity small { color: #8b949e; }
222
+ .history-boundary small { color: #6e7681; }
223
+ .msg-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
224
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
225
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
226
+ .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; }
227
+ .msg-action:hover, .msg-action:focus { color: #e6edf3; border-color: #58a6ff; }
228
+ .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; }
229
+ .label { display: block; color: #8b949e; font-size: 12px; text-transform: uppercase; }
230
+ .msg-header .label { margin: 0; }
231
+ .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; }
232
+ .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; }
233
+ .msg-meta:focus { outline: 1px solid #30363d; outline-offset: 3px; border-radius: 4px; }
234
+ @media (hover: none) {
235
+ .msg-actions { opacity: 1; }
236
+ .msg-meta { opacity: .75; max-width: 26px; }
237
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
238
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
239
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
240
+ }
241
+ formatted-text.part { display: block; }
242
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
243
+ .part + .part { margin-top: 10px; }
244
+ .tool-line { color: #d29922; }
245
+ .summary { color: #8b949e; margin-left: 6px; }
246
+ .part:is(details) { border-top: 1px solid #30363d; padding-top: 8px; }
247
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
248
+ .skill-invocation, .skill-read { border: 1px solid #30363d; border-radius: 8px; background: #161b22; padding: 8px 10px; }
249
+ .skill-invocation > summary, .skill-read > strong { color: #d2a8ff; }
250
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: #8b949e; }
251
+ summary { cursor: pointer; color: #8b949e; }
252
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
253
+ .shell-output { color: #e6edf3; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
254
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
255
+ `,Aa=B`
256
+ :host { display: block; }
257
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
258
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
259
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
260
+ ul, ol { padding-left: 22px; }
261
+ li + li { margin-top: 3px; }
262
+ code { border: 1px solid #30363d; border-radius: 4px; background: #0d1117; padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
263
+ .code-block-wrapper { position: relative; }
264
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
265
+ pre { border: 1px solid #30363d; border-radius: 8px; background: #0d1117; padding: 10px; overflow-x: auto; overflow-y: hidden; }
266
+ pre code { border: 0; padding: 0; background: transparent; }
267
+ .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; 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; }
268
+ .code-copy-button:hover, .code-copy-button:focus { color: #e6edf3; border-color: #58a6ff; }
269
+ blockquote { border-left: 3px solid #30363d; padding-left: 10px; color: #8b949e; }
270
+ a { color: #58a6ff; }
271
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
272
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
273
+ h1 { font-size: 20px; }
274
+ h2 { font-size: 17px; }
275
+ h3 { font-size: 15px; }
276
+ h4 { font-size: 14px; }
277
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
278
+ th, td { border: 1px solid #30363d; padding: 4px 8px; }
279
+ th { background: #161b22; }
280
+ `,Ia=B`
281
+ :host { display: block; color: #8b949e; font: 12px system-ui, sans-serif; }
282
+ .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; }
283
+ span { overflow: hidden; text-overflow: ellipsis; }
284
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
285
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
286
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: #8b949e; }
287
+ .workspace-label-link { color: #58a6ff; text-decoration: none; }
288
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
289
+ .bar > span:first-child { flex: 1 1 auto; min-width: 80px; }
290
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: #8b949e; }
291
+ .activity.active { color: #3fb950; }
292
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
293
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
294
+ .muted { color: #6e7681; }
295
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
296
+ `,Ma=B`
297
+ :host { display: block; }
298
+ .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; }
299
+ 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; }
300
+ button:last-child { border-bottom: 0; }
301
+ button.selected, button:hover { background: #0d2847; }
302
+ span { color: #8b949e; font-size: 12px; }
303
+ small { grid-column: 1 / -1; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
304
+ `,Ti=B`
305
+ :host { position: fixed; inset: 0; z-index: 10; color: #e6edf3; font: 14px system-ui, sans-serif; }
306
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: #0008; }
307
+ 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; }
308
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid #30363d; }
309
+ .options { min-height: 0; overflow: auto; outline: none; }
310
+ button { border: 0; background: transparent; color: #e6edf3; cursor: pointer; }
311
+ header button { font-size: 20px; color: #8b949e; }
312
+ input { margin: 10px 12px; border: 1px solid #30363d; border-radius: 8px; background: #0d1117; color: #e6edf3; font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
313
+ input:focus { border-color: #58a6ff; }
314
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid #21262d; text-align: left; }
315
+ .options button.selected, .options button:hover { background: #0d2847; }
316
+ small { display: block; margin-top: 4px; color: #8b949e; }
317
+ .empty { padding: 24px; color: #8b949e; text-align: center; }
318
+ `,Ea=B`
319
+ :host { position: fixed; inset: 0; z-index: 20; color: #e6edf3; font: 14px system-ui, sans-serif; }
320
+ .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; }
321
+ 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; }
322
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid #30363d; }
323
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: #e6edf3; font: 16px system-ui, sans-serif; padding: 8px; }
324
+ input::placeholder { color: #6e7681; }
325
+ button { border: 0; background: transparent; color: #e6edf3; cursor: pointer; }
326
+ header button { color: #8b949e; font-size: 22px; padding: 2px 8px; }
327
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; -webkit-overflow-scrolling: touch; }
328
+ .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; }
329
+ .options button.selected, .options button:hover { background: #0d2847; }
330
+ .main { min-width: 0; }
331
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
332
+ small { display: block; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
333
+ .group { grid-column: 1 / -1; font-size: 12px; }
334
+ 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; }
335
+ .empty { padding: 24px; color: #8b949e; text-align: center; }
336
+ `,Ra=B`
337
+ :host { position: relative; z-index: 5; display: block; color: #e6edf3; font: 14px system-ui, sans-serif; }
338
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid #30363d; }
339
+ footer.shell-mode { border-top-color: #3fb950; background: #0f1b12; }
340
+ .editor-wrap { position: relative; min-width: 0; }
341
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
342
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: #8b949e; font-size: 12px; flex: 1 1 0; }
343
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
344
+ .select-model { max-width: min(42vw, 320px); }
345
+ .select-thinking { max-width: 110px; }
346
+ textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid #30363d; background: #0d1117; color: #e6edf3; font: 16px/1.4 system-ui, sans-serif; }
347
+ textarea { overflow-y: auto; padding: 8px; }
348
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
349
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: #e6edf3; }
350
+ .markdown-editor .cm-line { padding: 0; }
351
+ .markdown-editor .cm-placeholder { color: #6e7681; }
352
+ .markdown-editor .cm-focused { outline: none; }
353
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: #3fb950; box-shadow: 0 0 0 1px #3fb95055; }
354
+ .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; }
355
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
356
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
357
+ @media (max-width: 640px) {
358
+ footer { gap: 8px; padding: 8px; }
359
+ .actions { gap: 6px; }
360
+ .compact-status { flex: 1 1 220px; gap: 4px; }
361
+ .select-model { max-width: min(58vw, 260px); }
362
+ button { padding: 6px 8px; }
363
+ }
364
+ @media (max-width: 430px) {
365
+ .compact-status { flex-basis: 170px; font-size: 11px; }
366
+ .select-model { max-width: 48vw; }
367
+ .select-thinking { max-width: 70px; }
368
+ button { padding: 5px 7px; }
369
+ }
370
+ `;var _a=Object.defineProperty,Da=Object.getOwnPropertyDescriptor,ge=(t,e,s,i)=>{for(var r=i>1?void 0:i?Da(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&&_a(e,s,r),r};let Y=class extends R{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 d`
371
+ <section>
372
+ <h2>Projects</h2>
373
+ ${this.projects.map(t=>d`
374
+ <div
375
+ class=${`action-row ${this.selected?.id===t.id?"selected":""}`}
376
+ tabindex="0"
377
+ title=${t.path}
378
+ @click=${e=>{Ht(e,()=>this.onSelect?.(t))}}
379
+ @keydown=${e=>{Vt(e,()=>this.onSelect?.(t))}}
380
+ >
381
+ <div class="action-main">
382
+ <span>${t.name}</span><small>${t.path}</small>
383
+ </div>
384
+ <div class="action-menu">
385
+ <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>
386
+ ${this.openMenuProjectId===t.id?d`
387
+ <div class="action-menu-panel" style=${this.menuStyle}>
388
+ <button title="Close project" @click=${()=>{this.close(t)}}>Close</button>
389
+ </div>
390
+ `:null}
391
+ </div>
392
+ </div>
393
+ `)}
394
+ </section>
395
+ `}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}?
396
+
397
+ This only removes it from Pi Web; it will not change the project folder.`)&&this.onClose?.(t)}};Y.styles=Kt;ge([h({attribute:!1})],Y.prototype,"projects",2);ge([h({attribute:!1})],Y.prototype,"selected",2);ge([h({attribute:!1})],Y.prototype,"onSelect",2);ge([h({attribute:!1})],Y.prototype,"onClose",2);ge([$()],Y.prototype,"openMenuProjectId",2);ge([$()],Y.prototype,"menuStyle",2);Y=ge([W("project-list")],Y);function Ai(t,e=[],s){return d`
398
+ <span class="workspace-label">
399
+ <span class="workspace-label-base" title=${s??t}>${t}</span>
400
+ ${Ii(e)}
401
+ </span>
402
+ `}function Ii(t=[]){return t.map(e=>d`<span class="workspace-label-separator">·</span>${Oa(e)}`)}function Oa(t){if(t.type==="render")return d`<span class="workspace-label-render">${t.render()}</span>`;if(t.type==="link"&&La(t.href)){const e=t.target??"_blank",s=e==="_blank"?"noopener noreferrer":void 0;return d`<a class="workspace-label-item workspace-label-link" href=${t.href} title=${t.title??t.text} target=${e} rel=${s??void 0}>${t.text}</a>`}return d`<span class="workspace-label-item" title=${t.title??t.text}>${t.text}</span>`}function La(t){const e=t.trim().toLowerCase();return e!==""&&!e.startsWith("javascript:")&&!e.startsWith("data:")}var ja=Object.defineProperty,Na=Object.getOwnPropertyDescriptor,Ue=(t,e,s,i)=>{for(var r=i>1?void 0:i?Na(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&&ja(e,s,r),r};let pe=class extends R{constructor(){super(...arguments),this.workspaces=[],this.workspaceLabelItems=()=>[]}updated(t){(t.has("selected")||t.has("workspaces"))&&this.scrollSelectedIntoView()}render(){return d`
403
+ <section>
404
+ <h2>Workspaces</h2>
405
+ ${this.workspaces.map(t=>{const e=`${t.label}${t.isMain?" · main":""}`;return d`
406
+ <div
407
+ class=${`action-row workspace-row ${this.selected?.id===t.id?"selected":""}`}
408
+ tabindex="0"
409
+ title=${t.path}
410
+ @click=${s=>{Ht(s,()=>this.onSelect?.(t))}}
411
+ @keydown=${s=>{Vt(s,()=>this.onSelect?.(t))}}
412
+ >
413
+ <div class="action-main">
414
+ <span class="workspace-label">
415
+ <span class="workspace-label-base">${e}</span>
416
+ ${Ii(this.workspaceLabelItems(t))}
417
+ </span>
418
+ <small>${t.path}</small>
419
+ </div>
420
+ </div>
421
+ `})}
422
+ </section>
423
+ `}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};pe.styles=Kt;Ue([h({attribute:!1})],pe.prototype,"workspaces",2);Ue([h({attribute:!1})],pe.prototype,"selected",2);Ue([h({attribute:!1})],pe.prototype,"workspaceLabelItems",2);Ue([h({attribute:!1})],pe.prototype,"onSelect",2);pe=Ue([W("workspace-list")],pe);var qa=Object.defineProperty,Fa=Object.getOwnPropertyDescriptor,q=(t,e,s,i)=>{for(var r=i>1?void 0:i?Fa(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&&qa(e,s,r),r};function za(t){return t.name!==void 0&&t.name!==""?t.name:t.firstMessage!==""?t.firstMessage:t.id.slice(0,8)}let O=class extends R{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){if(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),this.selected?.archived===!0&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(t.has("selected")||t.has("sessions"))&&this.scrollSelectedIntoView()}render(){const t=Wa(this.sessions),e=new Set(t.map(i=>i.session.id)),s=Mi(this.sessions.filter(i=>i.archived===!0&&!e.has(i.id)));return d`
424
+ <section>
425
+ <h2>Sessions <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>
426
+ ${t.map(i=>this.renderSession(i))}
427
+ ${s.length>0?d`
428
+ <h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span><small>${s.length}</small></button></h2>
429
+ ${this.archivedExpanded?s.map(i=>this.renderSession(i)):null}
430
+ `:null}
431
+ </section>
432
+ `}renderSession(t){const{session:e}=t,s=Math.min(t.depth,2);return d`
433
+ <div
434
+ class="action-row ${this.selected?.id===e.id?"selected":""} ${e.archived===!0?"archived":""}"
435
+ style=${`--depth:${String(s)}`}
436
+ tabindex="0"
437
+ title=${e.path}
438
+ @click=${i=>{Ht(i,()=>this.onSelect?.(e))}}
439
+ @keydown=${i=>{Vt(i,()=>this.onSelect?.(e))}}
440
+ >
441
+ <div class="action-main">
442
+ <span>${t.depth>0?d`<span class="tree-marker">↳</span>`:null}${za(e)}${t.depth>2?d` <span class="badge">depth ${t.depth}</span>`:null}${t.hasMissingParent?d` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderStatus(e)}${String(e.messageCount)} messages</small>
443
+ </div>
444
+ <div class="action-menu">
445
+ <button class="action-menu-toggle" title="Session actions" @click=${i=>{i.stopPropagation(),this.toggleMenu(e.id,i.currentTarget)}}>⋯</button>
446
+ ${this.openMenuSessionId===e.id?d`
447
+ <div class="action-menu-panel" style=${this.menuStyle}>
448
+ ${e.parentSessionPath!==void 0?d`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(e)}}>Detach from parent</button>`:null}
449
+ ${xe(e)?d`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(e)}}>Delete</button>`:e.archived===!0?d`<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(e)}}>Restore</button>`:d`<button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(e)}}>Archive</button>`}
450
+ </div>
451
+ `:null}
452
+ </div>
453
+ </div>
454
+ `}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)}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(t){if(xe(t))return"new · ";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 · `:""}};O.styles=Kt;q([h({attribute:!1})],O.prototype,"sessions",2);q([h({attribute:!1})],O.prototype,"statuses",2);q([h({attribute:!1})],O.prototype,"activities",2);q([h({attribute:!1})],O.prototype,"selected",2);q([h({type:Boolean})],O.prototype,"canStart",2);q([h({attribute:!1})],O.prototype,"onSelect",2);q([h({attribute:!1})],O.prototype,"onStart",2);q([$()],O.prototype,"openMenuSessionId",2);q([$()],O.prototype,"menuStyle",2);q([$()],O.prototype,"archivedExpanded",2);q([h({attribute:!1})],O.prototype,"onArchive",2);q([h({attribute:!1})],O.prototype,"onRestore",2);q([h({attribute:!1})],O.prototype,"onDelete",2);q([h({attribute:!1})],O.prototype,"onDetachParent",2);O=q([W("session-list")],O);function Wa(t){const e=new Map(t.map(i=>[i.path,i])),s=new Set;for(const i of t){if(i.archived===!0)continue;s.add(i.id);let r=i.parentSessionPath;const o=new Set([i.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=e.get(r);if(n===void 0)break;s.add(n.id),r=n.parentSessionPath}}return Mi(t.filter(i=>s.has(i.id)))}function Mi(t){const e=new Map(t.map(n=>[n.path,n])),s=new Map,i=[];for(const n of t){const a=n.parentSessionPath,l=a===void 0?void 0:e.get(a);if(l===void 0){i.push(n);continue}const c=s.get(l.path)??[];c.push(n),s.set(l.path,c)}const r=[],o=(n,a,l)=>{if(l.has(n.path))return;const c=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:c!==void 0&&!e.has(c)});const u=new Set(l);u.add(n.path);for(const p of s.get(n.path)??[])o(p,a+1,u)};for(const n of i)o(n,0,new Set);return r}const Gt={CHILD:2,ELEMENT:6},Qt=t=>(...e)=>({_$litDirective$:t,values:e});let Zt=class{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)}};const{I:Ua}=kr,Us=t=>t,Bs=()=>document.createComment(""),_e=(t,e,s)=>{const i=t._$AA.parentNode,r=e===void 0?t._$AB:e._$AA;if(s===void 0){const o=i.insertBefore(Bs(),r),n=i.insertBefore(Bs(),r);s=new Ua(o,n,t,t.options)}else{const o=s._$AB.nextSibling,n=s._$AM,a=n!==t;if(a){let l;s._$AQ?.(t),s._$AM=t,s._$AP!==void 0&&(l=t._$AU)!==n._$AU&&s._$AP(l)}if(o!==r||a){let l=s._$AA;for(;l!==o;){const c=Us(l).nextSibling;Us(i).insertBefore(l,r),l=c}}}return s},ae=(t,e,s=t)=>(t._$AI(e,s),t),Ba={},Ha=(t,e=Ba)=>t._$AH=e,Va=t=>t._$AH,kt=t=>{t._$AR(),t._$AA.remove()};const Hs=(t,e,s)=>{const i=new Map;for(let r=e;r<=s;r++)i.set(t[r],r);return i},Ka=Qt(class extends Zt{constructor(t){if(super(t),t.type!==Gt.CHILD)throw Error("repeat() can only be used in text expressions")}dt(t,e,s){let i;s===void 0?s=e:e!==void 0&&(i=e);const r=[],o=[];let n=0;for(const a of t)r[n]=i?i(a,n):n,o[n]=s(a,n),n++;return{values:o,keys:r}}render(t,e,s){return this.dt(t,e,s).values}update(t,[e,s,i]){const r=Va(t),{values:o,keys:n}=this.dt(e,s,i);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],l=[];let c,u,p=0,f=r.length-1,g=0,b=o.length-1;for(;p<=f&&g<=b;)if(r[p]===null)p++;else if(r[f]===null)f--;else if(a[p]===n[g])l[g]=ae(r[p],o[g]),p++,g++;else if(a[f]===n[b])l[b]=ae(r[f],o[b]),f--,b--;else if(a[p]===n[b])l[b]=ae(r[p],o[b]),_e(t,l[b+1],r[p]),p++,b--;else if(a[f]===n[g])l[g]=ae(r[f],o[g]),_e(t,r[p],r[f]),f--,g++;else if(c===void 0&&(c=Hs(n,g,b),u=Hs(a,p,f)),c.has(a[p]))if(c.has(a[f])){const I=u.get(n[g]),ye=I!==void 0?r[I]:null;if(ye===null){const Te=_e(t,r[p]);ae(Te,o[g]),l[g]=Te}else l[g]=ae(ye,o[g]),_e(t,r[p],ye),r[I]=null;g++}else kt(r[f]),f--;else kt(r[p]),p++;for(;g<=b;){const I=_e(t,l[b+1]);ae(I,o[g]),l[g++]=I}for(;p<=f;){const I=r[p++];I!==null&&kt(I)}return this.ut=n,Ha(t,l),re}});function Ga(t,e=0){const s=[];let i=[],r=0;const o=(a,l)=>{i.length||(r=l),i.push(a)},n=()=>{i.length&&(s.push({kind:"group",messages:i,startIndex:r,endIndex:r+i.length-1}),i=[])};return t.forEach((a,l)=>{const c=a.parts.filter(g=>Vs(a,g)),u=a.parts.filter(g=>!Vs(a,g)),p=e+l,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...f},p),c.length){n();const g=c.every(b=>b.type==="skillRead")?"skill":a.role;s.push({kind:"message",message:{role:g,parts:c,...f},index:p})}}),n(),s}function Qa(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 Vs(t,e){return t.source==="compaction"||t.source==="branch_summary"?!1:e.type==="skillInvocation"||e.type==="skillRead"?!0:e.type==="text"&&(t.role==="user"||t.role==="assistant"||t.role==="system"||t.role==="bash")}const Za=30;function Ja(t,e){const s=Xa(sl(t,e)),i={distanceFromBottom:t.scrollHeight-t.scrollTop};return s===void 0?i:{...i,markerId:s.id,markerOffset:s.offset}}function Ya(t,e,s){if(s!==void 0&&e.markerOffset!==void 0){const i=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=el(i,e.markerOffset);return}t.scrollTop=tl(t.scrollHeight,e.distanceFromBottom)}function Xa(t){let e,s=Number.NEGATIVE_INFINITY,i,r=Number.POSITIVE_INFINITY;for(const o of t)o.offset<=0&&o.offset>=s?(e=o,s=o.offset):o.offset>0&&o.offset<r&&(i=o,r=o.offset);return e??i}function el(t,e){return t-e}function tl(t,e){return Math.max(0,t-e)}function sl(t,e){const s=t.getBoundingClientRect().top;return e.flatMap(i=>{const r=i.dataset.markerId;return r===void 0?[]:[{id:r,offset:i.getBoundingClientRect().top-s}]})}const il=600,rl=1;function ol(t){return!t.hasMore||t.loadingMore||!t.canRequest||t.clientHeight<=0?!1:nl(t)||al(t)}function nl(t){return t.scrollTop<(t.topThreshold??Math.max(il,t.clientHeight))}function al(t){return t.scrollHeight<=t.clientHeight+rl}class Mt extends Zt{constructor(e){if(super(e),this.it=A,e.type!==Gt.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===A||e==null)return this._t=void 0,this.it=e;if(e===re)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:[]}}}Mt.directiveName="unsafeHTML",Mt.resultType=1;const ll=Qt(Mt);function Jt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var me=Jt();function Ei(t){me=t}var le={exec:()=>null};function v(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(L.caret,"$1"),s=s.replace(r,n),i},getRegex:()=>new RegExp(s,e)};return i}var cl=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),L={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)}}>`)},dl=/^(?:[ \t]*(?:\n|$))+/,pl=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,hl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Be=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ul=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Yt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ri=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_i=v(Ri).replace(/bull/g,Yt).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(),fl=v(Ri).replace(/bull/g,Yt).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(),Xt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,gl=/^[^\n]+/,es=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ml=v(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",es).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),bl=v(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Yt).getRegex(),mt="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",ts=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,yl=v("^ {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",ts).replace("tag",mt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Di=v(Xt).replace("hr",Be).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",mt).getRegex(),wl=v(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Di).getRegex(),ss={blockquote:wl,code:pl,def:ml,fences:hl,heading:ul,hr:Be,html:yl,lheading:_i,list:bl,newline:dl,paragraph:Di,table:le,text:gl},Ks=v("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Be).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",mt).getRegex(),vl={...ss,lheading:fl,table:Ks,paragraph:v(Xt).replace("hr",Be).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ks).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",mt).getRegex()},xl={...ss,html:v(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ts).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:le,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:v(Xt).replace("hr",Be).replace("heading",` *#{1,6} *[^
455
+ ]`).replace("lheading",_i).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Sl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,kl=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Oi=/^( {2,}|\\)\n(?!\s*$)/,$l=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ce=/[\p{P}\p{S}]/u,bt=/[\s\p{P}\p{S}]/u,is=/[^\s\p{P}\p{S}]/u,Pl=v(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,bt).getRegex(),Li=/(?!~)[\p{P}\p{S}]/u,Cl=/(?!~)[\s\p{P}\p{S}]/u,Tl=/(?:[^\s\p{P}\p{S}]|~)/u,Al=v(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",cl?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ji=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Il=v(ji,"u").replace(/punct/g,Ce).getRegex(),Ml=v(ji,"u").replace(/punct/g,Li).getRegex(),Ni="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",El=v(Ni,"gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,bt).replace(/punct/g,Ce).getRegex(),Rl=v(Ni,"gu").replace(/notPunctSpace/g,Tl).replace(/punctSpace/g,Cl).replace(/punct/g,Li).getRegex(),_l=v("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,bt).replace(/punct/g,Ce).getRegex(),Dl=v(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ce).getRegex(),Ol="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ll=v(Ol,"gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,bt).replace(/punct/g,Ce).getRegex(),jl=v(/\\(punct)/,"gu").replace(/punct/g,Ce).getRegex(),Nl=v(/^<(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(),ql=v(ts).replace("(?:-->|$)","-->").getRegex(),Fl=v("^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",ql).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),lt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,zl=v(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",lt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),qi=v(/^!?\[(label)\]\[(ref)\]/).replace("label",lt).replace("ref",es).getRegex(),Fi=v(/^!?\[(ref)\](?:\[\])?/).replace("ref",es).getRegex(),Wl=v("reflink|nolink(?!\\()","g").replace("reflink",qi).replace("nolink",Fi).getRegex(),Gs=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,rs={_backpedal:le,anyPunctuation:jl,autolink:Nl,blockSkip:Al,br:Oi,code:kl,del:le,delLDelim:le,delRDelim:le,emStrongLDelim:Il,emStrongRDelimAst:El,emStrongRDelimUnd:_l,escape:Sl,link:zl,nolink:Fi,punctuation:Pl,reflink:qi,reflinkSearch:Wl,tag:Fl,text:$l,url:le},Ul={...rs,link:v(/^!?\[(label)\]\((.*?)\)/).replace("label",lt).getRegex(),reflink:v(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",lt).getRegex()},Et={...rs,emStrongRDelimAst:Rl,emStrongLDelim:Ml,delLDelim:Dl,delRDelim:Ll,url:v(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gs).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:v(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Gs).getRegex()},Bl={...Et,br:v(Oi).replace("{2,}","*").getRegex(),text:v(Et.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ze={normal:ss,gfm:vl,pedantic:xl},De={normal:rs,gfm:Et,breaks:Bl,pedantic:Ul},Hl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Qs=t=>Hl[t];function Z(t,e){if(e){if(L.escapeTest.test(t))return t.replace(L.escapeReplace,Qs)}else if(L.escapeTestNoEncode.test(t))return t.replace(L.escapeReplaceNoEncode,Qs);return t}function Zs(t){try{t=encodeURI(t).replace(L.percentDecode,"%")}catch{return null}return t}function Js(t,e){let s=t.replace(L.findPipe,(o,n,a)=>{let l=!1,c=n;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),i=s.split(L.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(L.slashPipe,"|");return i}function se(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 Ys(t){let e=t.split(`
456
+ `),s=e.length-1;for(;s>=0&&L.blankLine.test(e[s]);)s--;return e.length-s<=2?t:e.slice(0,s+1).join(`
457
+ `)}function Vl(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 Kl(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 Xs(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 l={type:t[0].charAt(0)==="!"?"image":"link",raw:s,href:o,title:n,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,l}function Gl(t,e,s){let i=t.match(s.other.indentCodeCompensation);if(i===null)return e;let r=i[1];return e.split(`
458
+ `).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(`
459
+ `)}var ct=class{options;rules;lexer;constructor(t){this.options=t||me}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]:Ys(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=Gl(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=se(s,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(s=i.trim())}return{type:"heading",raw:se(e[0],`
460
+ `),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:se(e[0],`
461
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let s=se(e[0],`
462
+ `).split(`
463
+ `),i="",r="",o=[];for(;s.length>0;){let n=!1,a=[],l;for(l=0;l<s.length;l++)if(this.rules.other.blockquoteStart.test(s[l]))a.push(s[l]),n=!0;else if(!n)a.push(s[l]);else break;s=s.slice(l);let c=a.join(`
464
+ `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
465
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
466
+ ${c}`:c,r=r?`${r}
467
+ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=p,s.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let g=f,b=g.raw+`
468
+ `+s.join(`
469
+ `),I=this.blockquote(b);o[o.length-1]=I,i=i.substring(0,i.length-g.raw.length)+I.raw,r=r.substring(0,r.length-g.text.length)+I.text;break}else if(f?.type==="list"){let g=f,b=g.raw+`
470
+ `+s.join(`
471
+ `),I=this.list(b);o[o.length-1]=I,i=i.substring(0,i.length-f.raw.length)+I.raw,r=r.substring(0,r.length-g.raw.length)+I.raw,s=b.substring(o.at(-1).raw.length).split(`
472
+ `);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 l=!1,c="",u="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let p=Kl(e[2].split(`
473
+ `,1)[0],e[1].length),f=t.split(`
474
+ `,1)[0],g=!p.trim(),b=0;if(this.options.pedantic?(b=2,u=p.trimStart()):g?b=e[1].length+1:(b=p.search(this.rules.other.nonSpaceChar),b=b>4?1:b,u=p.slice(b),b+=e[1].length),g&&this.rules.other.blankLine.test(f)&&(c+=f+`
475
+ `,t=t.substring(f.length+1),l=!0),!l){let I=this.rules.other.nextBulletRegex(b),ye=this.rules.other.hrRegex(b),Te=this.rules.other.fencesBeginRegex(b),as=this.rules.other.headingBeginRegex(b),Ui=this.rules.other.htmlBeginRegex(b),Bi=this.rules.other.blockquoteBeginRegex(b);for(;t;){let vt=t.split(`
476
+ `,1)[0],Ae;if(f=vt,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),Ae=f):Ae=f.replace(this.rules.other.tabCharGlobal," "),Te.test(f)||as.test(f)||Ui.test(f)||Bi.test(f)||I.test(f)||ye.test(f))break;if(Ae.search(this.rules.other.nonSpaceChar)>=b||!f.trim())u+=`
477
+ `+Ae.slice(b);else{if(g||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Te.test(p)||as.test(p)||ye.test(p))break;u+=`
478
+ `+f}g=!f.trim(),c+=vt+`
479
+ `,t=t.substring(vt.length+1),p=Ae.slice(b)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(n=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=c}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 l of r.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=p.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=p.raw+l.tokens[0].raw,l.tokens[0].text=p.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(p)):l.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):l.tokens.unshift(p)}}else l.task&&(l.task=!1);if(!r.loose){let u=l.tokens.filter(f=>f.type==="space"),p=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));r.loose=p}}if(r.loose)for(let l of r.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(t){let e=this.rules.block.html.exec(t);if(e){let s=Ys(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:se(e[0],`
480
+ `),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=Js(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
481
+ `):[],o={type:"table",raw:se(e[0],`
482
+ `),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(Js(n,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let s=e[1].trim();return{type:"heading",raw:se(e[0],`
483
+ `),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)===`
484
+ `?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=se(s.slice(0,-1),"\\");if((s.length-o.length)%2===0)return}else{let o=Vl(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)),Xs(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 Xs(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,l=0,c=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;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)continue;if(n=[...o].length,i[3]||i[4]){a+=n;continue}else if((i[5]||i[6])&&r%3&&!((r+n)%3)){l+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+l);let u=[...i[0]][0].length,p=t.slice(0,r+i.index+u+n);if(Math.min(r,n)%2){let g=p.slice(1,-1);return{type:"em",raw:p,text:g,tokens:this.lexer.inlineTokens(g)}}let f=p.slice(2,-2);return{type:"strong",raw:p,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,l=this.rules.inline.delRDelim;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||(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 c=[...i[0]][0].length,u=t.slice(0,r+i.index+c+n),p=u.slice(r,-r);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}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}}}},V=class Rt{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||me,this.options.tokenizer=this.options.tokenizer||new ct,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:L,block:Ze.normal,inline:De.normal};this.options.pedantic?(s.block=Ze.pedantic,s.inline=De.pedantic):this.options.gfm&&(s.block=Ze.gfm,this.options.breaks?s.inline=De.breaks:s.inline=De.gfm),this.tokenizer.rules=s}static get rules(){return{block:Ze,inline:De}}static lex(e,s){return new Rt(s).lex(e)}static lexInline(e,s){return new Rt(s).inlineTokens(e)}lex(e){e=e.replace(L.carriageReturn,`
485
+ `),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(L.tabCharGlobal," ").replace(L.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+=`
486
+ `: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(`
487
+ `)?"":`
488
+ `)+o.raw,a.text+=`
489
+ `+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(`
490
+ `)?"":`
491
+ `)+o.raw,a.text+=`
492
+ `+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,l=e.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),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(`
493
+ `)?"":`
494
+ `)+o.raw,a.text+=`
495
+ `+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(`
496
+ `)?"":`
497
+ `)+o.raw,a.text+=`
498
+ `+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 c=Object.keys(this.tokens.links);if(c.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(i))!==null;)c.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="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(a=""),n=!1;let c;if(this.options.extensions?.inline?.some(p=>(c=p.call({lexer:this},e,s))?(e=e.substring(c.raw.length),s.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let p=s.at(-1);c.type==="text"&&p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):s.push(c);continue}if(c=this.tokenizer.emStrong(e,i,a)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.del(e,i,a)){e=e.substring(c.raw.length),s.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),s.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),s.push(c);continue}let u=e;if(this.options.extensions?.startInline){let p=1/0,f=e.slice(1),g;this.options.extensions.startInline.forEach(b=>{g=b.call({lexer:this},f),typeof g=="number"&&g>=0&&(p=Math.min(p,g))}),p<1/0&&p>=0&&(u=e.substring(0,p+1))}if(c=this.tokenizer.inlineText(u)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),n=!0;let p=s.at(-1);p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):s.push(c);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)}},dt=class{options;parser;constructor(t){this.options=t||me}space(t){return""}code({text:t,lang:e,escaped:s}){let i=(e||"").match(L.notSpaceStart)?.[0],r=t.replace(L.endingNewline,"")+`
499
+ `;return i?'<pre><code class="language-'+Z(i)+'">'+(s?r:Z(r,!0))+`</code></pre>
500
+ `:"<pre><code>"+(s?r:Z(r,!0))+`</code></pre>
501
+ `}blockquote({tokens:t}){return`<blockquote>
502
+ ${this.parser.parse(t)}</blockquote>
503
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
504
+ `}hr(t){return`<hr>
505
+ `}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+`>
506
+ `+i+"</"+r+`>
507
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
508
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
509
+ `}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>
510
+ <thead>
511
+ `+e+`</thead>
512
+ `+i+`</table>
513
+ `}tablerow({text:t}){return`<tr>
514
+ ${t}</tr>
515
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),s=t.header?"th":"td";return(t.align?`<${s} align="${t.align}">`:`<${s}>`)+e+`</${s}>
516
+ `}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>${Z(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=Zs(t);if(r===null)return i;t=r;let o='<a href="'+t+'"';return e&&(o+=' title="'+Z(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=Zs(t);if(r===null)return Z(s);t=r;let o=`<img src="${t}" alt="${Z(s)}"`;return e&&(o+=` title="${Z(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Z(t.text)}},os=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}},K=class _t{options;renderer;textRenderer;constructor(e){this.options=e||me,this.options.renderer=this.options.renderer||new dt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new os}static parse(e,s){return new _t(s).parse(e)}static parseInline(e,s){return new _t(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}},Le=class{options;block;constructor(t){this.options=t||me}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?V.lex:V.lexInline}provideParser(t=this.block){return t?K.parse:K.parseInline}},Ql=class{defaults=Jt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=K;Renderer=dt;TextRenderer=os;Lexer=V;Tokenizer=ct;Hooks=Le;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 dt(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],l=r[n];r[n]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}i.renderer=r}if(s.tokenizer){let r=this.defaults.tokenizer||new ct(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],l=r[n];r[n]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}i.tokenizer=r}if(s.hooks){let r=this.defaults.hooks||new Le;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],l=r[n];Le.passThroughHooks.has(o)?r[n]=c=>{if(this.defaults.async&&Le.passThroughHooksRespectAsync.has(o))return(async()=>{let p=await a.call(r,c);return l.call(r,p)})();let u=a.call(r,c);return l.call(r,u)}:r[n]=(...c)=>{if(this.defaults.async)return(async()=>{let p=await a.apply(r,c);return p===!1&&(p=await l.apply(r,c)),p})();let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}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 V.lex(t,e??this.defaults)}parser(t,e){return K.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?V.lex:V.lexInline)(n,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(t):t?K.parse:K.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(o);try{r.hooks&&(e=r.hooks.preprocess(e));let n=(r.hooks?r.hooks.provideLexer(t):t?V.lex:V.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?K.parse:K.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+=`
517
+ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+Z(s.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(s);throw s}}},he=new Ql;function x(t,e){return he.parse(t,e)}x.options=x.setOptions=function(t){return he.setOptions(t),x.defaults=he.defaults,Ei(x.defaults),x};x.getDefaults=Jt;x.defaults=me;x.use=function(...t){return he.use(...t),x.defaults=he.defaults,Ei(x.defaults),x};x.walkTokens=function(t,e){return he.walkTokens(t,e)};x.parseInline=he.parseInline;x.Parser=K;x.parser=K.parse;x.Renderer=dt;x.TextRenderer=os;x.Lexer=V;x.lexer=V.lex;x.Tokenizer=ct;x.Hooks=Le;x.parse=x;x.options;x.setOptions;x.use;x.walkTokens;x.parseInline;K.parse;V.lex;const zi=new x.Renderer;zi.html=({text:t})=>Yl(t);const Zl=300,Oe=new Map;function Jl(t){const e=Oe.get(t);if(e!==void 0)return e;const s=x.parse(t,{async:!1,breaks:!0,gfm:!0,renderer:zi}),i=Xl(s);if(Oe.set(t,i),Oe.size>Zl){const r=Oe.keys().next().value;r!==void 0&&Oe.delete(r)}return i}function Yl(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Xl(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")&&!ec(i.value)&&s.removeAttribute(i.name)}s.tagName==="A"&&(s.setAttribute("target","_blank"),s.setAttribute("rel","noreferrer noopener"))}),e.innerHTML}function ec(t){if(t.startsWith("#")||t.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(t).protocol)}catch{return!1}}var tc=Object.defineProperty,sc=Object.getOwnPropertyDescriptor,Wi=(t,e,s,i)=>{for(var r=i>1?void 0:i?sc(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&&tc(e,s,r),r};let pt=class extends R{constructor(){super(...arguments),this.text="",this.onFormattedClick=t=>{if(!(t.target instanceof Element))return;const e=t.target.closest(".code-copy-button");if(!(e instanceof HTMLButtonElement))return;const s=e.closest(".code-block-wrapper");if(!(s instanceof HTMLElement))return;const i=s.querySelector("pre code");i instanceof HTMLElement&&this.copyCode(i.textContent,e)},this.onFormattedCopy=t=>{t.clipboardData===null||!oc(ic(this))||(t.clipboardData.setData("text/plain",this.text),t.preventDefault(),t.stopPropagation())}}render(){return d`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${ll(Jl(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.title="Copy code block",i.setAttribute("aria-label","Copy code block");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",i.append(r),t.before(s),s.append(t,i)})}async copyCode(t,e){const s=await nc(t);this.setCopyButtonState(e,s?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(e,"idle")},1200)}setCopyButtonState(t,e){const s=t.querySelector("span");s!==null&&(s.textContent=e==="copied"?"✓":"⧉");const i=e==="copied"?"Copied code block":e==="failed"?"Failed to copy code block":"Copy code block";t.title=i,t.setAttribute("aria-label",i)}};pt.styles=Aa;Wi([h()],pt.prototype,"text",2);pt=Wi([W("formatted-text")],pt);function ic(t){const e=t.getRootNode();return typeof ShadowRoot<"u"&&e instanceof ShadowRoot&&rc(e)?e.getSelection():t.ownerDocument.getSelection()}function rc(t){return"getSelection"in t&&typeof t.getSelection=="function"}function oc(t){return t!==null&&!t.isCollapsed&&t.toString()!==""}async function nc(t){try{return await navigator.clipboard.writeText(t),!0}catch{return!1}}var ac=Object.defineProperty,lc=Object.getOwnPropertyDescriptor,E=(t,e,s,i)=>{for(var r=i>1?void 0:i?lc(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&&ac(e,s,r),r};const cc=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),dc=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"});function pc(t){return typeof t=="object"&&t!==null&&"offset"in t&&typeof t.offset=="number"&&("key"in t&&typeof t.key=="string"||"index"in t&&typeof t.index=="number")}let T=class extends R{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.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){window.clearTimeout(this.saveScrollTimer),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),window.removeEventListener("resize",this.onViewportResize),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}willUpdate(t){t.has("sessionId")&&(this.openGroupKeys=this.readOpenGroupKeys()),t.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(t){const e=this.isPrependingMessages(t)?this.capturePrependScrollAnchor():void 0;super.update(t),e!==void 0&&this.restorePrependScrollAnchor(e)}updated(t){t.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),t.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),!t.has("sessionId")&&t.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(t.has("messages")||t.has("hasMore")||t.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){return d`
518
+ <div class="chat-wrap">
519
+ ${this.renderHistoryIndicator()}
520
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
521
+ ${this.renderHistoryBoundary()}
522
+ ${Ka(this.groupedMessages(),t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupAnchorKey(t.endIndex),t=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex))}
523
+ ${this.renderQueuedMessages()}
524
+ ${this.renderSessionActivity()}
525
+ </div>
526
+ ${this.renderActivityDock()}
527
+ </div>
528
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Ga(this.messages,this.messageStart),this.groupedMessagesCache)}renderActivityDock(){const t=this.activityState();if(t===void 0)return null;const e=t!=="idle"||this.activity?.phase==="active";return d`
529
+ <div class=${e?"activity-dock active":"activity-dock"} aria-live="polite">
530
+ <span class="dot"></span>
531
+ <span class="activity-text">${this.activityText(t)}</span>
532
+ </div>
533
+ `}renderQueuedMessages(){const t=this.status?.queuedMessages??[];return t.length===0?null:d`
534
+ <aside class="queued-messages" aria-live="polite">
535
+ <div class="queued-header">
536
+ <strong>Queued messages</strong>
537
+ <small>${t.length} pending · Stop clears the queue</small>
538
+ </div>
539
+ ${t.map((e,s)=>d`
540
+ <div class="queued-message">
541
+ <span class="queued-kind">${e.kind==="steer"?"Steer":"Follow-up"} ${String(s+1)}</span>
542
+ <formatted-text .text=${e.text}></formatted-text>
543
+ </div>
544
+ `)}
545
+ </aside>
546
+ `}renderSessionActivity(){return this.isReceivingPartialStream?d`
547
+ <aside class="session-activity receiving" aria-live="polite">
548
+ <strong>Receiving answer…</strong>
549
+ <span>This session was reconnected mid-response. The answer will appear when complete.</span>
550
+ </aside>
551
+ `:this.isCompacting?d`
552
+ <aside class="session-activity compacting" aria-live="polite">
553
+ <strong>Compacting history…</strong>
554
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
555
+ ${this.pendingMessageCount>0?d`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
556
+ </aside>
557
+ `: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 d`
558
+ <div class="history-indicator">
559
+ <div>${i}</div>
560
+ </div>
561
+ `}renderHistoryBoundary(){const t=this.historyRangeLabel();return this.loadingMore?d`<div class="history-boundary"><span>Loading earlier messages…</span>${t}</div>`:this.hasMore?d`
562
+ <div class="history-boundary">
563
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
564
+ <span>Scroll up to load earlier messages</span>
565
+ ${t}
566
+ </div>
567
+ `:this.messages.length?d`<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 d`<small>Showing messages ${t}–${e} of ${this.messageTotal}</small>`}renderMessage(t,e){return d`
568
+ ${this.renderScrollMarker(this.messageScrollMarkerId(e))}
569
+ <article class="msg ${t.role}" data-index=${e} data-anchor-key=${this.messageAnchorKey(e)}>
570
+ ${this.renderMessageHeader(t,String(e))}
571
+ ${t.parts.map(s=>this.renderPart(s,t))}
572
+ </article>
573
+ `}renderMessageGroup(t,e,s){const i=this.groupKey(s);return d`
574
+ ${this.renderScrollMarker(this.groupScrollMarkerId(s))}
575
+ <details class="msg event-group" data-index=${e} data-anchor-key=${this.groupAnchorKey(s)} ?open=${this.openGroupKeys.has(i)} @toggle=${r=>{this.onGroupToggle(i,r)}}>
576
+ <summary>
577
+ <b class="label">events</b>
578
+ <span>${Qa(t)}</span>
579
+ </summary>
580
+ <div class="group-body">
581
+ ${t.map((r,o)=>d`
582
+ <section class="group-msg ${r.role}">
583
+ ${this.renderMessageHeader(r,`${String(e)}:${String(o)}`)}
584
+ ${r.parts.map(n=>this.renderPart(n,r))}
585
+ </section>
586
+ `)}
587
+ </div>
588
+ </details>
589
+ `}renderScrollMarker(t){return d`<span class="scroll-marker" data-marker-id=${t} aria-hidden="true"></span>`}renderMessageHeader(t,e){const s=this.messageMetaLabel(t),i=this.expandedMetaKey===e;return d`
590
+ <div class="msg-header">
591
+ <b class="label">${t.role}</b>
592
+ <div class="msg-header-trailing">
593
+ ${this.renderMessageActions(t,e)}
594
+ <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>
595
+ </div>
596
+ </div>
597
+ `}renderMessageActions(t,e){if(!this.isCopyableMessage(t))return null;const s=this.copiedMessageKey===e;return d`
598
+ <div class="msg-actions" aria-label="Message actions">
599
+ <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)}}>
600
+ <span aria-hidden="true">${s?"✓":"⧉"}</span>
601
+ </button>
602
+ </div>
603
+ `}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){const e=this.messageCopyTextCache.get(t);if(e!==void 0)return e;const s=t.parts.filter(i=>i.type==="text").map(i=>i.text.trim()).filter(i=>i!=="").join(`
604
+
605
+ `);return this.messageCopyTextCache.set(t,s),s}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=this.messageMetaCache.get(t);if(e!==void 0)return e;const s=t.meta?.timestamp,i=this.modelLabel(t);if(s===void 0&&i===void 0){const l={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(t,l),l}const r=s===void 0?void 0:this.formatTimestamp(s),o=[r?.short,i].filter(l=>l!==void 0&&l!==""),n=[r?.full,i===void 0?void 0:`Model: ${i}`].filter(l=>l!==void 0&&l!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(t,a),a}formatTimestamp(t){const e=new Date(t);if(Number.isFinite(e.getTime()))return{short:cc.format(e),full:dc.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"?d`<pre class="part shell-output">${t.text}</pre>`:t.type==="text"?d`<formatted-text class="part" .text=${t.text}></formatted-text>`:t.type==="thinking"?d`<details class="part"><summary>thinking</summary><formatted-text .text=${t.text}></formatted-text></details>`:t.type==="skillInvocation"?d`
606
+ <details class="part skill-invocation">
607
+ <summary><b>[skill]</b> ${t.name}</summary>
608
+ <small>${t.location}</small>
609
+ <formatted-text .text=${t.content}></formatted-text>
610
+ </details>
611
+ `:t.type==="skillRead"?d`
612
+ <div class="part skill-read">
613
+ <strong>Loaded ${t.name}</strong>
614
+ <small>read ${t.path}</small>
615
+ </div>
616
+ `:t.type==="toolCall"?d`<div class="part tool-line">▶ ${t.toolName}<span class="summary">${t.summary}</span></div>`:t.type==="toolResult"?d`
617
+ <details class="part" ?open=${t.isError}>
618
+ <summary>${t.isError?"✖":"✓"} ${t.toolName} result</summary>
619
+ <formatted-text .text=${t.text}></formatted-text>
620
+ </details>
621
+ `: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.requestLoadMoreIfNeeded(),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=this.didChatHeightChange(),s=this.pinnedToBottom,i=t.scrollTop<this.lastScrollTop;if(e&&s){this.lastClientHeight=t.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:i?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=t.scrollTop,this.lastClientHeight=t.clientHeight}didChatHeightChange(){const t=this.chat;return t!==void 0&&this.lastClientHeight!==0&&t.clientHeight!==this.lastClientHeight}isPrependingMessages(t){const e=t.get("messageStart");return typeof e=="number"&&this.messageStart<e}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const t=this.chat;t&&ol({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}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(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const t=this.chat;t&&this.withSuppressedScrollSave(()=>{t.scrollTop=t.scrollHeight,this.lastScrollTop=t.scrollTop,this.lastClientHeight=t.clientHeight})}))}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);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 Ja(t,this.scrollMarkers())}restorePrependScrollAnchor(t){if(!this.chat||!t)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let e=0;const s=()=>{const i=this.chat;if(i){if(Ya(i,t,t.markerId===void 0?void 0:this.scrollMarkerAt(t.markerId)),this.lastScrollTop=i.scrollTop,e+=1,e<Za){requestAnimationFrame(s);return}requestAnimationFrame(()=>{this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1})}};s()}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={key:s.dataset.anchorKey,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 pc(e)?e:void 0}catch{return}}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(t){return this.scrollMarkers().find(e=>e.dataset.markerId===t)}firstVisibleArticle(){const t=this.chat;if(!t)return;const e=s=>{const i=t.getBoundingClientRect();return Array.from(this.renderRoot.querySelectorAll(s)).find(r=>{const o=r.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})};return e("article.msg")??e("article.msg, details.msg")}articleAt(t){const e=this.articles(),s=t.key===void 0?void 0:e.find(i=>i.dataset.anchorKey===t.key);return s!==void 0?s:e.find(i=>Number(i.dataset.index)===t.index)}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}withSuppressedScrollSave(t){this.suppressScrollSave=!0,t(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}withSuppressedLoadMoreRequests(t){this.suppressLoadMoreRequests=!0,t(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressLoadMoreRequests=!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)}`}messageAnchorKey(t){return`m:${String(t)}`}groupAnchorKey(t){return`g:${String(t)}`}messageScrollMarkerId(t){return`m:${String(t)}`}groupScrollMarkerId(t){return`g:${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{}}};T.styles=Ta;E([h({attribute:!1})],T.prototype,"messages",2);E([h()],T.prototype,"sessionId",2);E([h({type:Number})],T.prototype,"messageStart",2);E([h({type:Number})],T.prototype,"messageTotal",2);E([h({type:Boolean})],T.prototype,"hasMore",2);E([h({type:Boolean})],T.prototype,"loadingMore",2);E([h({type:Boolean})],T.prototype,"isReceivingPartialStream",2);E([h({type:Boolean})],T.prototype,"isCompacting",2);E([h({type:Number})],T.prototype,"pendingMessageCount",2);E([h({attribute:!1})],T.prototype,"status",2);E([h({attribute:!1})],T.prototype,"activity",2);E([h({attribute:!1})],T.prototype,"onLoadMore",2);E([fe(".chat")],T.prototype,"chat",2);E([$()],T.prototype,"pinnedToBottom",2);E([$()],T.prototype,"openGroupKeys",2);E([$()],T.prototype,"expandedMetaKey",2);E([$()],T.prototype,"copiedMessageKey",2);E([$()],T.prototype,"loadMoreRequested",2);T=E([W("chat-view")],T);class hc extends Zt{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Gt.ELEMENT}update(e,[s,i]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(s&&(!this.wasSelected||i!==this.previousKey)){const r="element"in e?e.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=s,this.previousKey=i}render(e,s){}}const ns=Qt(hc);var uc=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,yt=(t,e,s,i)=>{for(var r=i>1?void 0:i?fc(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&&uc(e,s,r),r};let ke=class extends R{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?d`
622
+ <div class="menu">
623
+ ${this.items.map((t,e)=>d`
624
+ <button class=${e===this.selectedIndex?"selected":""} ${ns(e===this.selectedIndex,t)} @mousedown=${s=>{s.preventDefault(),this.onPick?.(t)}}>
625
+ <strong>${t.insertText}</strong>
626
+ <span>${t.detail}</span>
627
+ ${t.description!==void 0&&t.description!==""?d`<small>${t.description}</small>`:null}
628
+ </button>
629
+ `)}
630
+ </div>
631
+ `:null}};ke.styles=Ma;yt([h({attribute:!1})],ke.prototype,"items",2);yt([h({type:Number})],ke.prototype,"selectedIndex",2);yt([h({attribute:!1})],ke.prototype,"onPick",2);ke=yt([W("autocomplete-menu")],ke);var gc=Object.defineProperty,mc=Object.getOwnPropertyDescriptor,N=(t,e,s,i)=>{for(var r=i>1?void 0:i?mc(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&&gc(e,s,r),r};let _=class extends R{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,this.editableCompartment=new ls,this.readOnlyCompartment=new ls}willUpdate(t){if(!t.has("sessionId"))return;const e=t.get("sessionId");e!==void 0&&e!==""&&Tt(e,this.draft),this.draft=this.sessionId!==void 0&&this.sessionId!==""?fi(this.sessionId):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(t){t.has("disabled")&&this.updateEditorDisabledState(),(t.has("draft")||t.has("sessionId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const t=mi(this.draft),e=t.kind==="shell",s=this.canSteer||this.isCompacting;return d`
632
+ <footer class=${e?"shell-mode":""}>
633
+ <div class="editor-wrap">
634
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
635
+ ${e?d`<div class="mode-hint">Shell command${t.excludeFromContext?" · excluded from context":""}</div>`:null}
636
+ ${this.isCompacting&&!e?d`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
637
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${i=>{this.pick(i)}}></autocomplete-menu>
638
+ </div>
639
+ <div class="actions">
640
+ ${this.renderCompactStatus()}
641
+ <button ?disabled=${this.disabled} title=${s?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${s?"Queue":"Send"}</button>
642
+ ${this.canSteer&&!this.isCompacting?d`<button ?disabled=${this.disabled} title="Steer the current response before the next model call" @click=${()=>{this.send("steer")}}>Steer</button>`:null}
643
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</button>
644
+ </div>
645
+ </footer>
646
+ `}focusInput(){this.editor?.focus()}renderCompactStatus(){const t=this.status;if(t===void 0)return null;const e=t.model?.id??"no model",s=t.model?.provider!==void 0&&t.model.provider!==""?`${t.model.provider}/`:"";return d`
647
+ <div class="compact-status" aria-label="Session status">
648
+ <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${s}${e}</button>
649
+ <button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${t.thinkingLevel??"off"}</button>
650
+ </div>
651
+ `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ie({parent:this.editorHost,state:xt.create({doc:this.draft,extensions:[Hi(),tr(),Vi(),Ki.of(" "),Gi(er,{fallback:!0}),Ie.lineWrapping,Qi("Message pi... Use / for commands, @ for files"),this.editableCompartment.of(Ie.editable.of(!this.disabled)),this.readOnlyCompartment.of(xt.readOnly.of(this.disabled)),Ie.updateListener.of(t=>{t.docChanged&&this.updateDraft(t.state.doc.toString())}),Zi.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:t=>sr(t)||Xi(t)},{key:"Tab",run:t=>this.handleEditorTab(t)},{key:"Shift-Tab",run:t=>cs.shift?.(t)??!1},{key:"Backspace",run:t=>ir(t)},...Ji,...Yi])]})}))}syncEditorDoc(){const t=this.editor;if(!t)return;const e=t.state.doc.toString();e!==this.draft&&t.dispatch({changes:{from:0,to:e.length,insert:this.draft},selection:ds.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Ie.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(xt.readOnly.of(this.disabled))]})}updateDraft(t){this.draft=t,this.sessionId!==void 0&&this.sessionId!==""&&Tt(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 D.commands(this.sessionId).catch(yc);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 D.files(this.cwd,t.query,t.fileKind,t.fileMode).catch(wc);if(e!==this.requestVersion)return;this.completions=s.slice(0,12).map(i=>{const r=bc(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.editor?.state.selection.main.head??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(`
652
+ `))+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}}moveCompletion(t){return this.completions.length?(this.selectedIndex=(this.selectedIndex+t+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const t=this.completions[this.selectedIndex];return t!==void 0&&this.pick(t),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(t){if(this.completions.length){const s=this.completions[this.selectedIndex];return s!==void 0&&this.pick(s),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):cs.run?.(t)??!1}pick(t){const e=this.editor;if(!e)return;const s=t.kind==="file"&&(t.insertText.endsWith("/")||t.cursorOffset!==void 0)?"":" ",i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+s.length,r=t.insertText.endsWith('"')&&this.draft.slice(t.replaceTo).startsWith('"')?t.replaceTo+1:t.replaceTo;e.dispatch({changes:{from:t.replaceFrom,to:r,insert:`${t.insertText}${s}`},selection:ds.cursor(i),scrollIntoView:!0}),this.completions=[]}send(t){const e=this.draft.trim();e===""||this.disabled||(this.draft="",this.sessionId!==void 0&&this.sessionId!==""&&Ut(this.sessionId),this.completions=[],this.onSend?.(e,this.canSteer||this.isCompacting?t:void 0))}};_.styles=Ra;N([h({type:Boolean})],_.prototype,"disabled",2);N([h()],_.prototype,"sessionId",2);N([h()],_.prototype,"cwd",2);N([h({type:Boolean})],_.prototype,"canSteer",2);N([h({type:Boolean})],_.prototype,"isCompacting",2);N([h({type:Boolean})],_.prototype,"canStop",2);N([h({attribute:!1})],_.prototype,"status",2);N([h({attribute:!1})],_.prototype,"onSend",2);N([h({attribute:!1})],_.prototype,"onStop",2);N([h({attribute:!1})],_.prototype,"onSelectModel",2);N([h({attribute:!1})],_.prototype,"onSelectThinking",2);N([fe(".markdown-editor")],_.prototype,"editorHost",2);N([$()],_.prototype,"draft",2);N([$()],_.prototype,"completions",2);N([$()],_.prototype,"selectedIndex",2);_=N([W("prompt-editor")],_);function bc(t,e,s){const i=e?"":"@";return!s&&!t.includes(" ")?`${i}${t}`:`${i}"${t}"`}function yc(){return[]}function wc(){return[]}function Je(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 vc(t){return!Number.isFinite(t)||t===0?"$0":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}var xc=Object.defineProperty,Sc=Object.getOwnPropertyDescriptor,wt=(t,e,s,i)=>{for(var r=i>1?void 0:i?Sc(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&&xc(e,s,r),r};let $e=class extends R{constructor(){super(...arguments),this.workspaceLabelItems=[]}render(){const t=this.status;if(t===void 0)return d`<div class="bar muted">No session status yet</div>`;const e=t.contextUsage,s=e?e.percent==null?`context ${Je(e.contextWindow)}`:`${e.percent.toFixed(1)}%/${Je(e.contextWindow)}`:"context unknown",i=t.tokens;return d`
653
+ <div class="bar">
654
+ <span>${Ai(this.workspace?.label??"workspace",this.workspaceLabelItems,this.workspace?.path)}</span>
655
+ <span>↑${Je(i.input)}</span>
656
+ <span>↓${Je(i.output)}</span>
657
+ <span>${s}</span>
658
+ <span>${vc(t.cost)}</span>
659
+ ${t.pendingMessageCount>0?d`<span>${String(t.pendingMessageCount)} queued</span>`:null}
660
+ </div>
661
+ `}};$e.styles=Ia;wt([h({attribute:!1})],$e.prototype,"status",2);wt([h({attribute:!1})],$e.prototype,"workspace",2);wt([h({attribute:!1})],$e.prototype,"workspaceLabelItems",2);$e=wt([W("status-bar")],$e);var kc=Object.defineProperty,$c=Object.getOwnPropertyDescriptor,ee=(t,e,s,i)=>{for(var r=i>1?void 0:i?$c(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&&kc(e,s,r),r};let G=class extends R{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const t=this.filteredOptions();return d`
662
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
663
+ <section @mousedown=${e=>{e.stopPropagation()}}>
664
+ <header>
665
+ <strong>${this.title}</strong>
666
+ <button @click=${()=>this.onCancel?.()}>×</button>
667
+ </header>
668
+ ${this.searchable?d`<input placeholder="Search" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>`:null}
669
+ <div class="options" @keydown=${e=>{this.handleKeyDown(e)}} tabindex="0">
670
+ ${t.map((e,s)=>d`
671
+ <button class=${s===this.selectedIndex?"selected":""} ${ns(s===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
672
+ <span>${e.label}</span>
673
+ ${e.description!==void 0&&e.description!==""?d`<small>${e.description}</small>`:null}
674
+ </button>
675
+ `)}
676
+ ${t.length===0?d`<div class="empty">No matching options</div>`:null}
677
+ </div>
678
+ </section>
679
+ </div>
680
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const t=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);t>=0&&(this.selectedIndex=t)}handleSearchInput(t){t.target instanceof HTMLInputElement&&(this.query=t.target.value,this.selectedIndex=0)}filteredOptions(){const t=this.query.trim().toLowerCase();return t===""?this.options:this.options.filter(e=>`${e.label} ${e.description??""} ${e.value}`.toLowerCase().includes(t))}handleKeyDown(t){const e=this.filteredOptions();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&&this.onPick?.(s.value)}}};G.styles=Ti;ee([h()],G.prototype,"title",2);ee([h({type:Boolean})],G.prototype,"searchable",2);ee([h({attribute:!1})],G.prototype,"options",2);ee([h({attribute:!1})],G.prototype,"selectedValue",2);ee([h({attribute:!1})],G.prototype,"onPick",2);ee([h({attribute:!1})],G.prototype,"onCancel",2);ee([$()],G.prototype,"selectedIndex",2);ee([$()],G.prototype,"query",2);G=ee([W("command-picker")],G);var Pc=Object.defineProperty,Cc=Object.getOwnPropertyDescriptor,be=(t,e,s,i)=>{for(var r=i>1?void 0:i?Cc(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&&Pc(e,s,r),r};let X=class extends R{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const t=this.filteredActions();return d`
681
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
682
+ <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
683
+ <header>
684
+ <input
685
+ .value=${this.queryText}
686
+ placeholder="Search actions..."
687
+ @input=${e=>{e.target instanceof HTMLInputElement&&(this.queryText=e.target.value,this.selectedIndex=0)}}
688
+ >
689
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
690
+ </header>
691
+ <div class="options">
692
+ ${t.length===0?d`<div class="empty">No actions found.</div>`:t.map((e,s)=>d`
693
+ <button class=${s===this.selectedIndex?"selected":""} ${ns(s===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
694
+ <span class="main">
695
+ <strong>${e.title}</strong>
696
+ ${e.description!==void 0&&e.description!==""?d`<small>${e.description}</small>`:null}
697
+ </span>
698
+ ${e.shortcut!==void 0?d`<kbd>${Hn(e.shortcut)}</kbd>`:null}
699
+ ${e.group!==void 0&&e.group!==""?d`<small class="group">${e.group}</small>`:null}
700
+ </button>
701
+ `)}
702
+ </div>
703
+ </section>
704
+ </div>
705
+ `}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)}};X.styles=Ea;be([h({attribute:!1})],X.prototype,"actions",2);be([h({attribute:!1})],X.prototype,"onRun",2);be([h({attribute:!1})],X.prototype,"onCancel",2);be([fe("input")],X.prototype,"input",2);be([$()],X.prototype,"queryText",2);be([$()],X.prototype,"selectedIndex",2);X=be([W("action-palette")],X);var Tc=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor,H=(t,e,s,i)=>{for(var r=i>1?void 0:i?Ac(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&&Tc(e,s,r),r};let z=class extends R{render(){const t=this.state;return t===void 0?null:d`
706
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
707
+ <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
708
+ <header>
709
+ <strong>${this.dialogTitle(t)}</strong>
710
+ <button title="Close" @click=${()=>{this.cancel()}}>×</button>
711
+ </header>
712
+ ${this.renderBody(t)}
713
+ </section>
714
+ </div>
715
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(t){switch(t.step){case"method":return"Configure provider authentication";case"providers":return t.authType===void 0?"Select provider authentication":t.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${t.provider.name}`;case"oauth":return`Login to ${t.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(t){switch(t.step){case"method":return d`
716
+ <div class="options">
717
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
718
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
719
+ </div>
720
+ `;case"providers":return d`<div class="options">${t.providers.length===0?d`<div class="empty">No providers available.</div>`:t.providers.map(e=>this.renderProviderButton(e))}</div>`;case"apiKey":return d`
721
+ <div class="form">
722
+ <p>Enter the API key for <strong>${t.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
723
+ <input type="password" autocomplete="off" placeholder="API key" .value=${t.value} @input=${e=>{e.target instanceof HTMLInputElement&&this.onApiKeyInput?.(e.target.value)}}>
724
+ ${t.error!==void 0&&t.error!==""?d`<div class="error-text">${t.error}</div>`:null}
725
+ <div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${t.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${t.saving===!0?"Saving…":"Save API key"}</button></div>
726
+ </div>
727
+ `;case"oauth":return this.renderOAuth(t);case"logout":return d`<div class="options">${t.providers.length===0?d`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:t.providers.map(e=>d`
728
+ <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${ei(e.authType)}</small></button>
729
+ `)}</div>`}}renderProviderButton(t){return d`
730
+ <button @click=${()=>{this.onSelectProvider?.(t.id,t.authType)}}>
731
+ <span>${t.name}${t.status.source!==void 0?d` <em>${Mc(t)}</em>`:null}</span>
732
+ <small>${t.id} · ${ei(t.authType)}</small>
733
+ </button>
734
+ `}renderOAuth(t){const e=t.flow,s=e.prompt,i=e.select;return d`
735
+ <div class="form">
736
+ ${e.auth!==void 0?d`
737
+ <p>Open this authorization link:</p>
738
+ <p><a href=${e.auth.url} target="_blank" rel="noreferrer">${e.auth.url}</a></p>
739
+ ${e.auth.instructions!==void 0?d`<p class="warning">${e.auth.instructions}</p>`:null}
740
+ `:d`<p>Starting login flow…</p>`}
741
+ ${e.progress.length>0?d`<ul class="progress">${e.progress.map(r=>d`<li>${r}</li>`)}</ul>`:null}
742
+ ${s!==void 0?d`
743
+ <label>${s.message}</label>
744
+ <input .value=${t.inputValue??""} placeholder=${s.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
745
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${t.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
746
+ `:null}
747
+ ${i!==void 0?d`
748
+ <p>${i.message}</p>
749
+ <div class="inline-options">${i.options.map(r=>d`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
750
+ `:null}
751
+ ${t.error!==void 0&&t.error!==""?d`<div class="error-text">${t.error}</div>`:null}
752
+ ${e.status==="error"||e.status==="cancelled"?d`<div class="error-text">${e.error??e.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
753
+ ${s===void 0&&i===void 0&&e.status==="running"?d`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
754
+ </div>
755
+ `}focusInputIfNeeded(){const t=Ic(this.state);if(t===void 0){this.lastFocusedInputKey=void 0;return}t!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=t,this.input?.focus())}handleKeyDown(t){if(t.key==="Escape"){t.preventDefault(),this.cancel();return}if(t.key!=="Enter")return;const e=this.state;e?.step==="apiKey"?(t.preventDefault(),this.onSaveApiKey?.()):e?.step==="oauth"&&e.flow.prompt!==void 0&&(t.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};z.styles=[Ti,B`
756
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
757
+ .form p { margin: 0; color: #c9d1d9; overflow-wrap: anywhere; }
758
+ .form a { color: #58a6ff; overflow-wrap: anywhere; }
759
+ .form code { border: 1px solid #30363d; border-radius: 4px; background: #161b22; padding: 1px 4px; }
760
+ label { color: #8b949e; }
761
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
762
+ .actions button, .inline-options button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; }
763
+ .actions button.primary { border-color: #238636; background: #0f2a16; color: #3fb950; }
764
+ .actions button:disabled { opacity: .6; cursor: wait; }
765
+ .warning { color: #d29922; }
766
+ .error-text { color: #ff7b72; }
767
+ .progress { margin: 0; padding-left: 18px; color: #8b949e; }
768
+ .inline-options { display: grid; gap: 8px; }
769
+ em { color: #3fb950; font-style: normal; font-size: 12px; }
770
+ `];H([h({attribute:!1})],z.prototype,"state",2);H([h({attribute:!1})],z.prototype,"onChooseMethod",2);H([h({attribute:!1})],z.prototype,"onSelectProvider",2);H([h({attribute:!1})],z.prototype,"onApiKeyInput",2);H([h({attribute:!1})],z.prototype,"onSaveApiKey",2);H([h({attribute:!1})],z.prototype,"onLogoutProvider",2);H([h({attribute:!1})],z.prototype,"onOAuthInput",2);H([h({attribute:!1})],z.prototype,"onOAuthRespond",2);H([h({attribute:!1})],z.prototype,"onOAuthCancel",2);H([h({attribute:!1})],z.prototype,"onCancel",2);H([fe("input")],z.prototype,"input",2);z=H([W("auth-dialog")],z);function ei(t){return t==="oauth"?"subscription":"API key"}function Ic(t){if(t?.step==="apiKey")return`api-key:${t.provider.authType}:${t.provider.id}`;if(t?.step==="oauth"&&t.flow.prompt!==void 0)return`oauth:${t.flow.flowId}:${t.flow.prompt.requestId}`}function Mc(t){if(t.status.source===void 0)return"";switch(t.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${t.status.label===void 0?"":`: ${t.status.label}`}`;case"runtime":return"✓ runtime";case"fallback":return"✓ custom key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}var Ec=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,te=(t,e,s,i)=>{for(var r=i>1?void 0:i?Rc(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&&Ec(e,s,r),r};let Q=class extends R{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 D.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 d`
771
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
772
+ <section @click=${t=>{t.stopPropagation()}}>
773
+ <header>
774
+ <strong>Add project</strong>
775
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
776
+ </header>
777
+ <div class="body">
778
+ <label>
779
+ Project folder
780
+ <input .value=${this.path} @input=${t=>{this.onPathInput(t)}} @keydown=${t=>{this.onKeyDown(t)}} placeholder="/path/to/project or ~/code/project" autofocus />
781
+ </label>
782
+ <div class="suggestions">
783
+ ${this.loading?d`<div class="hint">Loading folders…</div>`:null}
784
+ ${this.suggestions.map((t,e)=>d`
785
+ <button class=${e===this.selected?"selected":""} @click=${()=>{this.pick(t)}}>
786
+ ${t.path}
787
+ </button>
788
+ `)}
789
+ ${!this.loading&&this.suggestions.length===0?d`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
790
+ </div>
791
+ <label class="check">
792
+ <input type="checkbox" .checked=${this.createMissing} @change=${t=>{this.onCreateMissingChange(t)}} />
793
+ Create the folder if it does not exist
794
+ </label>
795
+ </div>
796
+ <footer>
797
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
798
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
799
+ </footer>
800
+ </section>
801
+ </div>
802
+ `}};Q.styles=B`
803
+ :host { position: fixed; inset: 0; z-index: 30; color: #e6edf3; font: 14px system-ui, sans-serif; }
804
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: #0008; }
805
+ 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; }
806
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid #30363d; }
807
+ footer { border-top: 1px solid #30363d; border-bottom: 0; justify-content: end; }
808
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
809
+ label { display: grid; gap: 6px; color: #8b949e; }
810
+ 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; }
811
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: #e6edf3; }
812
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid #30363d; border-radius: 8px; background: #161b22; }
813
+ .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; }
814
+ .suggestions button.selected, .suggestions button:hover { background: #0d2847; }
815
+ .hint { padding: 12px; color: #8b949e; }
816
+ button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
817
+ header button { border: 0; background: transparent; color: #8b949e; font-size: 22px; padding: 0 8px; }
818
+ .primary { border-color: #238636; background: #238636; }
819
+ button:disabled { opacity: .5; cursor: not-allowed; }
820
+ `;te([h({attribute:!1})],Q.prototype,"onSubmit",2);te([h({attribute:!1})],Q.prototype,"onCancel",2);te([$()],Q.prototype,"path",2);te([$()],Q.prototype,"createMissing",2);te([$()],Q.prototype,"suggestions",2);te([$()],Q.prototype,"selected",2);te([$()],Q.prototype,"loading",2);te([fe("input")],Q.prototype,"pathInput",2);Q=te([W("project-dialog")],Q);var _c=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor,P=(t,e,s,i)=>{for(var r=i>1?void 0:i?Dc(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&&_c(e,s,r),r};let k=class extends R{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],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=()=>{},this.activeTerminalCount=0,this.terminalAutoStart=!1}render(){const t=this.workspace;if(t===void 0)return d`<section class="empty">Select a workspace.</section>`;const e=this.panels,s=e.find(r=>r.id===this.tool)??e[0],i=this.createPanelContext(t);return d`
821
+ <header>
822
+ ${this.hideToolTabs?null:d`
823
+ <div class="tabs">
824
+ ${e.map(r=>d`
825
+ <button class=${s?.id===r.id?"selected":""} @click=${()=>{this.onSelectTool(r.id)}}>${this.renderPanelTitle(r,i)}</button>
826
+ `)}
827
+ </div>
828
+ `}
829
+ <small>${Ai(t.label,this.workspaceLabelItems,t.path)}</small>
830
+ </header>
831
+ ${s===void 0?d`<section class="empty">No workspace panels registered.</section>`:d`
832
+ <div class="panel-content">
833
+ ${s.render(i)}
834
+ </div>
835
+ `}
836
+ `}renderPanelTitle(t,e){const s=t.badge?.(e);return s===void 0||s===""?d`${t.title}`:d`${t.title} <span class="tab-badge">${s}</span>`}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,activeTerminalCount:this.activeTerminalCount,terminalAutoStart:this.terminalAutoStart,onRefreshFiles:this.onRefreshFiles,onExpandDir:this.onExpandDir,onSelectFile:this.onSelectFile,onRefreshGit:this.onRefreshGit,onSelectDiff:this.onSelectDiff}}};k.styles=Ca;P([h({attribute:!1})],k.prototype,"workspace",2);P([h()],k.prototype,"tool",2);P([h({attribute:!1})],k.prototype,"panels",2);P([h({attribute:!1})],k.prototype,"workspaceLabelItems",2);P([h({type:Boolean})],k.prototype,"hideToolTabs",2);P([h({attribute:!1})],k.prototype,"fileTree",2);P([h({attribute:!1})],k.prototype,"expandedDirs",2);P([h({attribute:!1})],k.prototype,"selectedFilePath",2);P([h({attribute:!1})],k.prototype,"selectedFileContent",2);P([h({type:Boolean})],k.prototype,"fileTreeStale",2);P([h({attribute:!1})],k.prototype,"gitStatus",2);P([h({attribute:!1})],k.prototype,"selectedDiffPath",2);P([h({attribute:!1})],k.prototype,"selectedDiff",2);P([h({attribute:!1})],k.prototype,"selectedStagedDiff",2);P([h({type:Boolean})],k.prototype,"gitStale",2);P([h({attribute:!1})],k.prototype,"onSelectTool",2);P([h({attribute:!1})],k.prototype,"onRefreshFiles",2);P([h({attribute:!1})],k.prototype,"onExpandDir",2);P([h({attribute:!1})],k.prototype,"onSelectFile",2);P([h({attribute:!1})],k.prototype,"onRefreshGit",2);P([h({attribute:!1})],k.prototype,"onSelectDiff",2);P([h({type:Number})],k.prototype,"activeTerminalCount",2);P([h({type:Boolean})],k.prototype,"terminalAutoStart",2);k=P([W("workspace-panel")],k);var Oc=Object.defineProperty,Lc=Object.getOwnPropertyDescriptor,He=(t,e,s,i)=>{for(var r=i>1?void 0:i?Lc(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&&Oc(e,s,r),r};let ue=class extends R{constructor(){super(...arguments),this.state=xo(),this.sessions=new Ln(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.auth=new So(()=>this.state,t=>{this.setState(t)},t=>{this.sessions.applySessionStatus(t)}),this.workspaces=new Wn(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()},this.sessions),this.projects=new Mo(()=>this.state,t=>{this.setState(t)},this.workspaces),this.files=new Co(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.git=new Io(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.keyboard=new Bn,this.realtime=new Tn,this.activeTerminalIds=new Set,this.mobileNavigationMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(max-width: 760px)"):void 0,this.plugins=jc(),this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.onPopState=()=>{this.withChatScrollTransition(()=>this.restoreRoute(!1))},this.onFocus=()=>{this.sessions.refreshSelectedSession()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&this.sessions.refreshSelectedSession()},this.onMobileNavigationMediaChange=t=>{this.isMobileNavigationLayout=t.matches},this.onKeyDown=t=>{this.keyboard.handle(t,this.getActions())&&(t.preventDefault(),t.stopPropagation())}}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.connectRealtime(),this.loadExternalPlugins(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.git.dispose(),super.disconnectedCallback()}setState(t){if(!Nc(this.state,t))return;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=wa(),s=Ts(st("core:workspace.files"),"file"),i=Ts(st("core:workspace.git"),"diff");if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:e.view??this.defaultRouteView(),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 Fc(),this.chatView?.restoreScrollPosition(),this.promptEditor?.focusInput()}async withChatPrependTransition(t){await t(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}updateUrl(t){va({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)}openWorkspaceTool(t){t==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:t,mainView:t}),this.updateUrl(),this.refreshSelectedWorkspaceTool(t),this.git.updatePolling()}selectMainView(t){if(t!=="navigation"&&t!=="chat"){this.openWorkspaceTool(t);return}this.setState({mainView:t}),this.updateUrl(),this.git.updatePolling()}handleWorkspaceChange(t,e){t.selectedWorkspace?.id!==e.selectedWorkspace?.id&&(this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear(),this.setState({activeTerminalCount:0}),e.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(e.selectedWorkspace),this.refreshSelectedWorkspaceTool(e.workspaceTool),this.git.updatePolling()))}connectRealtime(){this.realtime.connect(t=>{this.handleRealtimeEvent(t)},()=>{const t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)})}handleRealtimeEvent(t){qc(t)?this.applyTerminalEvent(t):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(t){const e=this.state.selectedWorkspace;e===void 0||(t.type==="terminal.closed"?t.cwd:t.terminal.cwd)!==e.path||(t.type==="terminal.created"&&!t.terminal.exited?this.activeTerminalIds.add(t.terminal.id):this.activeTerminalIds.delete(t.type==="terminal.closed"?t.terminalId:t.terminal.id),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(t){try{const e=await pi.terminals(t.projectId,t.id);if(this.state.selectedWorkspace?.id!==t.id)return;this.activeTerminalIds.clear();for(const s of e)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(t,e){const s=ti(t.status),i=ti(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(){const t=this.state.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(this.state,this.state.selectedWorkspace);return d`<workspace-panel .workspace=${this.state.selectedWorkspace} .tool=${this.state.workspaceTool} .panels=${this.visibleWorkspacePanels()} .workspaceLabelItems=${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} .activeTerminalCount=${this.state.activeTerminalCount} .terminalAutoStart=${this.terminalAutoStartWorkspaceId===this.state.selectedWorkspace?.id} .onSelectTool=${e=>{this.openWorkspaceTool(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 d`
837
+ <header>
838
+ <strong>Pi Web</strong>
839
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.setState({actionPaletteOpen:!0})}}>Actions</button>
840
+ </header>
841
+ <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>
842
+ <workspace-list .workspaces=${this.state.workspaces} .selected=${this.state.selectedWorkspace} .workspaceLabelItems=${s=>this.plugins.getWorkspaceLabelItems(this.state,s)} .onSelect=${s=>this.withChatScrollTransition(()=>this.workspaces.selectWorkspace(s))}></workspace-list>
843
+ <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))} .onDelete=${s=>this.sessions.deleteCachedNewSession(s)} .onDetachParent=${s=>this.sessions.detachParent(s)}></session-list>
844
+ `}visibleWorkspacePanels(){const t=this.state.selectedWorkspace;return this.plugins.getWorkspacePanels().filter(e=>t===void 0||(e.visible?.({workspace:t,state:this.state})??!0))}renderMobilePanelTitle(t){const e=this.state.selectedWorkspace;if(e===void 0)return t.title;const s=t.badge?.(this.createWorkspacePanelContext(e));return s===void 0||s===""?t.title:d`${t.title} <span class="tab-badge">${s}</span>`}createWorkspacePanelContext(t){return{workspace: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,activeTerminalCount:this.state.activeTerminalCount,terminalAutoStart:this.terminalAutoStartWorkspaceId===t.id,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)}}}getActions(){return this.plugins.getActions(this.createPluginRuntimeContext())}async loadExternalPlugins(){try{for(const t of await pa())this.plugins.register(t);this.requestUpdate()}catch(t){console.warn("Failed to load external Pi Web plugins",t)}}createPluginRuntimeContext(){return{state:this.state,openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),selectMainView:t=>{this.selectMainView(t)},selectWorkspaceTool:t=>{this.openWorkspaceTool(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()}async openModelDialog(){const t=await this.sessions.listModels(),e=this.state.status?.model?.provider,s=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...e!==void 0&&s!==void 0?{selectedValue:`${e}/${s}`}:{},options:t.map(i=>{const r=i.provider??"",o=i.id??"",n=r===e&&o===s;return{value:`${r}/${o}`,label:`${o}${n?" ✓ current":""}`,description:r}})}})}async pickModel(t){this.setState({modelDialog:void 0});const e=t.indexOf("/");e<=0||await this.sessions.setModel(t.slice(0,e),t.slice(e+1))}async openThinkingDialog(){const t=await this.sessions.listThinkingLevels(),e=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:e,options:t.map(s=>({value:s,label:`${s}${s===e?" ✓ current":""}`,description:Wc(s)}))}})}async pickThinking(t){this.setState({thinkingDialog:void 0}),zc(t)&&await this.sessions.setThinkingLevel(t)}sendPrompt(t,e){e===void 0&&this.auth.handleSlashCommand(t)||this.sessions.send(t,e)}render(){const t=this.state;return d`
845
+ <div class=${`shell ${t.mainView==="navigation"?"navigation-view":t.mainView==="chat"?"chat-view":"workspace-view"}`}>
846
+ <aside>${this.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
847
+ <main class=${t.mainView==="chat"?"chat-view":t.mainView==="navigation"?"navigation-view":"workspace-view"}>
848
+ <div class="mobile-tabs">
849
+ <button class=${t.mainView==="navigation"?"mobile-navigation-tab selected":"mobile-navigation-tab"} @click=${()=>{this.selectMainView("navigation")}}>Sessions</button>
850
+ <button class=${t.mainView==="chat"?"selected":""} @click=${()=>{this.selectMainView("chat")}}>Chat</button>
851
+ ${this.visibleWorkspacePanels().map(e=>d`
852
+ <button class=${t.mainView===e.id?"selected":""} @click=${()=>{this.openWorkspaceTool(e.id)}}>${this.renderMobilePanelTitle(e)}</button>
853
+ `)}
854
+ </div>
855
+ ${t.error?d`<div class="error">${t.error}</div>`:null}
856
+ <div class="mobile-navigation-panel">${this.isMobileNavigationLayout?this.renderNavigationPanel(!0):null}</div>
857
+ ${t.selectedSession?d`
858
+ <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>
859
+ <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||(t.status?.pendingMessageCount??0)>0} .status=${t.status} .onSend=${(e,s)=>{this.sendPrompt(e,s)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
860
+ <status-bar .status=${t.status} .workspace=${t.selectedWorkspace} .workspaceLabelItems=${t.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(t,t.selectedWorkspace)}></status-bar>
861
+ ${t.commandDialog!==void 0?d`<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}
862
+ ${t.modelDialog!==void 0?d`<command-picker title=${t.modelDialog.title} .searchable=${!0} .options=${t.modelDialog.options} .selectedValue=${t.modelDialog.selectedValue} .onPick=${e=>{this.pickModel(e)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
863
+ ${t.thinkingDialog!==void 0?d`<command-picker title=${t.thinkingDialog.title} .options=${t.thinkingDialog.options} .selectedValue=${t.thinkingDialog.selectedValue} .onPick=${e=>{this.pickThinking(e)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
864
+ ${t.authDialog!==void 0?d`<auth-dialog .state=${t.authDialog} .onChooseMethod=${e=>{this.auth.chooseLoginMethod(e)}} .onSelectProvider=${(e,s)=>{this.auth.selectLoginProvider(e,s)}} .onApiKeyInput=${e=>{this.auth.updateApiKey(e)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${e=>{this.auth.logoutProvider(e)}} .onOAuthInput=${e=>{this.auth.updateOAuthInput(e)}} .onOAuthRespond=${e=>{this.auth.respondOAuth(e)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
865
+ `:d`<div class="empty">Select or start a session.</div>`}
866
+ </main>
867
+ ${this.renderWorkspacePanel()}
868
+ ${t.actionPaletteOpen?d`<action-palette .actions=${this.getActions()} .onRun=${e=>{this.setState({actionPaletteOpen:!1}),this.runAction(e)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
869
+ ${t.projectDialogOpen?d`<project-dialog .onSubmit=${(e,s)=>this.projects.addProject(e,s)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
870
+ </div>
871
+ `}};ue.styles=Pa;He([$()],ue.prototype,"state",2);He([fe("chat-view")],ue.prototype,"chatView",2);He([fe("prompt-editor")],ue.prototype,"promptEditor",2);He([$()],ue.prototype,"isMobileNavigationLayout",2);ue=He([W("pi-web-app")],ue);function jc(){const t=new ya;return t.register({id:"core",plugin:da}),t}function Nc(t,e){return Object.entries(e).some(([s,i])=>Reflect.get(t,s)!==i)}function ti(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}function qc(t){return t.type==="terminal.created"||t.type==="terminal.exited"||t.type==="terminal.closed"}function Fc(){return new Promise(t=>requestAnimationFrame(()=>{t()}))}function zc(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="xhigh"}function Wc(t){switch(t){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)"}}export{B as a,d as b,pi as c,Yc as d,fe as e,R as i,h as n,$ as r,W as t};