@jmfederico/pi-web 1.202605.7 → 1.202605.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1049 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-BJm9p3hj.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-DMOCBUgN.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Si,w as _e,J as It,R as mr,S as br,G as vr,U as wr,V as yr,A as xr,W as Sr,X as kr,Y as $r,Z as ki,x as $i,_ as Pr}from"./vendor-editor-core-B4Sq6exx.js";import{m as Tr,i as Cr,d as Ar}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(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"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(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 s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const st=globalThis,Ut=st.ShadowRoot&&(st.ShadyCSS===void 0||st.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Vt=Symbol(),Pi=new WeakMap;let Ss=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Vt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(Ut&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Pi.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Pi.set(i,t))}return t}toString(){return this.cssText}};const Ir=e=>new Ss(typeof e=="string"?e:e+"",void 0,Vt),H=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(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)+e[o+1],e[0]);return new Ss(i,e,Vt)},Mr=(e,t)=>{if(Ut)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=st.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},Ti=Ut?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Ir(i)})(e):e;const{is:Rr,defineProperty:Er,getOwnPropertyDescriptor:_r,getOwnPropertyNames:Dr,getOwnPropertySymbols:Lr,getPrototypeOf:Or}=Object,xt=globalThis,Ci=xt.trustedTypes,Nr=Ci?Ci.emptyScript:"",jr=xt.reactiveElementPolyfillSupport,ze=(e,t)=>e,at={toAttribute(e,t){switch(t){case Boolean:e=e?Nr:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Kt=(e,t)=>!Rr(e,t),Ai={attribute:!0,type:String,converter:at,reflect:!1,useDefault:!1,hasChanged:Kt};Symbol.metadata??=Symbol("metadata"),xt.litPropertyMetadata??=new WeakMap;let $e=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=Ai){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Er(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=_r(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ai}static _$Ei(){if(this.hasOwnProperty(ze("elementProperties")))return;const t=Or(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ze("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ze("properties"))){const i=this.properties,s=[...Dr(i),...Lr(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const r of s)i.unshift(Ti(r))}else t!==void 0&&i.push(Ti(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Mr(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:at).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:at;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Kt)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!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 s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};$e.elementStyles=[],$e.shadowRootOptions={mode:"open"},$e[ze("elementProperties")]=new Map,$e[ze("finalized")]=new Map,jr?.({ReactiveElement:$e}),(xt.reactiveElementVersions??=[]).push("2.1.2");const Gt=globalThis,Ii=e=>e,lt=Gt.trustedTypes,Mi=lt?lt.createPolicy("lit-html",{createHTML:e=>e}):void 0,ks="$lit$",ce=`lit$${Math.random().toFixed(9).slice(2)}$`,$s="?"+ce,Wr=`<${$s}>`,be=document,qe=()=>be.createComment(""),He=e=>e===null||typeof e!="object"&&typeof e!="function",Qt=Array.isArray,Fr=e=>Qt(e)||typeof e?.[Symbol.iterator]=="function",Mt=`[
3
+ \f\r]`,De=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ri=/-->/g,Ei=/>/g,he=RegExp(`>|${Mt}(?:([^\\s"'>=/]+)(${Mt}*=${Mt}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),_i=/'/g,Di=/"/g,Ps=/^(?:script|style|textarea|title)$/i,zr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),d=zr(1),de=Symbol.for("lit-noChange"),I=Symbol.for("lit-nothing"),Li=new WeakMap,ge=be.createTreeWalker(be,129);function Ts(e,t){if(!Qt(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Mi!==void 0?Mi.createHTML(t):t}const qr=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=De;for(let a=0;a<i;a++){const l=e[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===De?u[1]==="!--"?n=Ri:u[1]!==void 0?n=Ei:u[2]!==void 0?(Ps.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=he):u[3]!==void 0&&(n=he):n===he?u[0]===">"?(n=r??De,p=-1):u[1]===void 0?p=-2:(p=n.lastIndex-u[2].length,c=u[1],n=u[3]===void 0?he:u[3]==='"'?Di:_i):n===Di||n===_i?n=he:n===Ri||n===Ei?n=De:(n=he,r=void 0);const m=n===he&&e[a+1].startsWith("/>")?" ":"";o+=n===De?l+Wr:p>=0?(s.push(c),l.slice(0,p)+ks+l.slice(p)+ce+m):l+ce+(p===-2?a:m)}return[Ts(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Be{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,l=this.parts,[c,u]=qr(t,i);if(this.el=Be.createElement(c,s),ge.currentNode=this.el.content,i===2||i===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(r=ge.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const p of r.getAttributeNames())if(p.endsWith(ks)){const f=u[n++],m=r.getAttribute(p).split(ce),b=/([.?@])?(.*)/.exec(f);l.push({type:1,index:o,name:b[2],strings:m,ctor:b[1]==="."?Br:b[1]==="?"?Ur:b[1]==="@"?Vr:St}),r.removeAttribute(p)}else p.startsWith(ce)&&(l.push({type:6,index:o}),r.removeAttribute(p));if(Ps.test(r.tagName)){const p=r.textContent.split(ce),f=p.length-1;if(f>0){r.textContent=lt?lt.emptyScript:"";for(let m=0;m<f;m++)r.append(p[m],qe()),ge.nextNode(),l.push({type:2,index:++o});r.append(p[f],qe())}}}else if(r.nodeType===8)if(r.data===$s)l.push({type:2,index:o});else{let p=-1;for(;(p=r.data.indexOf(ce,p+1))!==-1;)l.push({type:7,index:o}),p+=ce.length-1}o++}}static createElement(t,i){const s=be.createElement("template");return s.innerHTML=t,s}}function Te(e,t,i=e,s){if(t===de)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=He(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=Te(e,r._$AS(e,t.values),r,s)),t}class Hr{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??be).importNode(i,!0);ge.currentNode=r;let o=ge.nextNode(),n=0,a=0,l=s[0];for(;l!==void 0;){if(n===l.index){let c;l.type===2?c=new Ie(o,o.nextSibling,this,t):l.type===1?c=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(c=new Kr(o,this,t)),this._$AV.push(c),l=s[++a]}n!==l?.index&&(o=ge.nextNode(),n++)}return ge.currentNode=be,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class Ie{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=I,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=Te(this,t,i),He(t)?t===I||t==null||t===""?(this._$AH!==I&&this._$AR(),this._$AH=I):t!==this._$AH&&t!==de&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Fr(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==I&&He(this._$AH)?this._$AA.nextSibling.data=t:this.T(be.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Be.createElement(Ts(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Hr(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Li.get(t.strings);return i===void 0&&Li.set(t.strings,i=new Be(t)),i}k(t){Qt(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new Ie(this.O(qe()),this.O(qe()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Ii(t).nextSibling;Ii(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let St=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=I,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=I}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=Te(this,t,i,0),n=!He(t)||t!==this._$AH&&t!==de,n&&(this._$AH=t);else{const a=t;let l,c;for(t=o[0],l=0;l<o.length-1;l++)c=Te(this,a[s+l],i,l),c===de&&(c=this._$AH[l]),n||=!He(c)||c!==this._$AH[l],c===I?t=I:t!==I&&(t+=(c??"")+o[l+1]),this._$AH[l]=c}n&&!r&&this.j(t)}j(t){t===I?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Br=class extends St{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===I?void 0:t}},Ur=class extends St{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==I)}},Vr=class extends St{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=Te(this,t,i,0)??I)===de)return;const s=this._$AH,r=t===I&&s!==I||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==I&&(s===I||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class Kr{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){Te(this,t)}}const Gr={I:Ie},Qr=Gt.litHtmlPolyfillSupport;Qr?.(Be,Ie),(Gt.litHtmlVersions??=[]).push("3.3.2");const Zr=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new Ie(t.insertBefore(qe(),o),o,void 0,i??{})}return r._$AI(e),r};const Zt=globalThis;let M=class extends $e{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Zr(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return de}};M._$litElement$=!0,M.finalized=!0,Zt.litElementHydrateSupport?.({LitElement:M});const Jr=Zt.litElementPolyfillSupport;Jr?.({LitElement:M});(Zt.litElementVersions??=[]).push("4.2.2");const F=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Yr={attribute:!0,type:String,converter:at,reflect:!1,hasChanged:Kt},Xr=(e=Yr,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const l=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,l,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const l=this[n];t.call(this,a),this.requestUpdate(n,l,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function h(e){return(t,i)=>typeof i=="object"?Xr(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function S(e){return h({...e,state:!0,attribute:!1})}const eo=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function oe(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return eo(i,s,{get(){return o(this)}})}}async function w(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const r=await fetch(e,{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(to(n)??r.statusText)}const o=await r.json();return t(o)}function to(e){if(io(e))return typeof e.error=="string"?e.error:void 0}function io(e){return typeof e=="object"&&e!==null}function so(e){return typeof e=="object"&&e!==null}function v(e){if(!so(e))throw new Error("Expected object response");return e}function g(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function k(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function B(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function N(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function ro(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function oo(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=v(e);return{messages:ro(t.messages),start:B(t,"start"),total:B(t,"total")}}function Oi(e){const t=v(e);return{id:g(t,"id"),name:g(t,"name"),path:g(t,"path"),createdAt:g(t,"createdAt")}}function no(e){const t=v(e),i=k(t,"branch");return{id:g(t,"id"),projectId:g(t,"projectId"),path:g(t,"path"),label:g(t,"label"),...i===void 0?{}:{branch:i},isMain:N(t,"isMain"),isGitRepo:N(t,"isGitRepo"),isGitWorktree:N(t,"isGitWorktree")}}function Dt(e){const t=v(e),i=k(t,"name"),s=k(t,"parentSessionPath"),r=k(t,"archivedAt");return{id:g(t,"id"),path:g(t,"path"),cwd:g(t,"cwd"),...i===void 0?{}:{name:i},created:g(t,"created"),modified:g(t,"modified"),messageCount:B(t,"messageCount"),firstMessage:g(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Le(e){const t=v(e);return{sessionId:g(t,"sessionId"),isStreaming:N(t,"isStreaming"),isCompacting:N(t,"isCompacting"),isBashRunning:N(t,"isBashRunning"),pendingMessageCount:B(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(ao)(t.queuedMessages),tokens:lo(t.tokens),cost:B(t,"cost"),...co(t.model),...ko(t.contextUsage),...y("thinkingLevel",k(t,"thinkingLevel"))}}function ao(e){const t=v(e),i=g(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:g(t,"text")}}function lo(e){const t=v(e);return{input:B(t,"input"),output:B(t,"output"),cacheRead:B(t,"cacheRead"),cacheWrite:B(t,"cacheWrite"),total:B(t,"total")}}function Cs(e){const t=v(e);return{...y("provider",k(t,"provider")),...y("id",k(t,"id")),...y("name",k(t,"name")),...y("contextWindow",Ue(t,"contextWindow")),...y("reasoning",t.reasoning)}}function co(e){return e===void 0?{}:{model:Cs(e)}}function po(e){const t=v(e);return{models:j(Cs)(t.models)}}function ho(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function uo(e){const t=v(e);return{levels:j(ho)(t.levels)}}function fo(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function go(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function mo(e){const t=v(e),i=t.source===void 0?void 0:go(t.source);return{configured:N(t,"configured"),...y("source",i),...y("label",k(t,"label"))}}function bo(e){const t=v(e);return{id:g(t,"id"),name:g(t,"name"),authType:fo(t.authType),status:mo(t.status)}}function vo(e){const t=v(e);return{providers:j(bo)(t.providers)}}function Je(e){const t=v(e);return{flowId:g(t,"flowId"),providerId:g(t,"providerId"),providerName:g(t,"providerName"),status:wo(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...y("error",k(t,"error")),...y("auth",yo(t.auth)),...y("prompt",xo(t.prompt)),...y("select",So(t.select))}}function wo(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function yo(e){if(e===void 0)return;const t=v(e);return{url:g(t,"url"),...y("instructions",k(t,"instructions"))}}function xo(e){if(e===void 0)return;const t=v(e),i=g(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:g(t,"requestId"),message:g(t,"message"),kind:i,...y("placeholder",k(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function So(e){if(e===void 0)return;const t=v(e);return{requestId:g(t,"requestId"),message:g(t,"message"),options:j(Is)(t.options)}}function ko(e){if(e===void 0)return{};const t=v(e);return{contextUsage:{tokens:zi(t,"tokens"),contextWindow:B(t,"contextWindow"),percent:zi(t,"percent")}}}function $o(e){const t=v(e),i=g(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:g(t,"name"),source:i,...y("description",k(t,"description"))}}function As(e){const t=v(e),i=g(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:g(t,"path"),kind:i}}function Po(e){const t=v(e);return{path:g(t,"path"),entries:j(To)(t.entries),scannedAt:g(t,"scannedAt"),truncated:N(t,"truncated")}}function To(e){const t=v(e),i=g(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:g(t,"name"),path:g(t,"path"),type:i,...y("size",Ue(t,"size")),...y("modifiedAt",k(t,"modifiedAt"))}}function Co(e){const t=v(e),i=g(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:g(t,"path"),...y("language",k(t,"language")),encoding:i,size:B(t,"size"),modifiedAt:g(t,"modifiedAt"),content:g(t,"content"),truncated:N(t,"truncated"),binary:N(t,"binary")}}function Ao(e){const t=v(e);return{isGitRepo:N(t,"isGitRepo"),hash:g(t,"hash"),...y("branch",k(t,"branch")),...y("upstream",k(t,"upstream")),...y("ahead",Ue(t,"ahead")),...y("behind",Ue(t,"behind")),files:j(Io)(t.files)}}function Io(e){const t=v(e);return{path:g(t,"path"),...y("oldPath",k(t,"oldPath")),index:Ni(t.index),workingTree:Ni(t.workingTree)}}function Ni(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function Mo(e){const t=v(e);return{...y("path",k(t,"path")),staged:N(t,"staged"),hash:g(t,"hash"),diff:g(t,"diff"),truncated:N(t,"truncated")}}function ji(e){const t=v(e);return{id:g(t,"id"),cwd:g(t,"cwd"),name:g(t,"name"),createdAt:g(t,"createdAt"),exited:N(t,"exited"),...y("exitCode",Ue(t,"exitCode"))}}function Ro(e){const t=v(e);return{packageName:g(t,"packageName"),generatedAt:g(t,"generatedAt"),components:Eo(t.components),release:Do(t.release),commands:Lo(t.commands),messages:j(Oo)(t.messages)}}function Eo(e){const t=v(e);return{web:Wi(t.web),sessiond:Wi(t.sessiond)}}function Wi(e){const t=v(e);return{component:No(t.component),label:g(t,"label"),...y("runtimeVersion",k(t,"runtimeVersion")),...y("installedVersion",k(t,"installedVersion")),stale:N(t,"stale"),available:N(t,"available"),...y("installation",_o(t.installation)),...y("error",k(t,"error"))}}function _o(e){if(e===void 0)return;const t=v(e),i=g(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid Pi Web installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid Pi Web installation scope");return{kind:i,...y("path",k(t,"path")),...y("source",k(t,"source")),...s===void 0?{}:{scope:s},...y("npmRoot",k(t,"npmRoot"))}}function Do(e){const t=v(e);return{packageName:g(t,"packageName"),...y("latestVersion",k(t,"latestVersion")),updateAvailable:N(t,"updateAvailable"),...y("checkedAt",k(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...y("error",k(t,"error"))}}function Lo(e){const t=v(e);return{update:g(t,"update"),restart:g(t,"restart"),restartSystemd:g(t,"restartSystemd"),restartDev:g(t,"restartDev")}}function Oo(e){const t=v(e);return{id:g(t,"id"),severity:jo(t.severity),title:g(t,"title"),body:g(t,"body"),...y("command",k(t,"command"))}}function No(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid Pi Web service component");return e}function jo(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid Pi Web status severity");return e}function Fi(e){const t=v(e),i=g(t,"type");if(i==="unsupported")return{type:i,message:g(t,"message")};if(i==="select")return{type:i,requestId:g(t,"requestId"),title:g(t,"title"),options:j(Is)(t.options)};if(i==="done")return{type:i,...y("message",k(t,"message")),...Wo(t.session)};throw new Error("Invalid command result type")}function Is(e){const t=v(e);return{value:g(t,"value"),label:g(t,"label"),...y("description",k(t,"description"))}}function Wo(e){return e===void 0?{}:{session:Dt(e)}}function Ye(e){if(v(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Ms(e){if(v(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Fo(e){if(v(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function zo(e){if(v(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function qo(e){if(v(e).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function Ho(e){if(v(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Bo(e){if(v(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Ue(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function zi(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function y(e,t){return t===void 0?{}:{[e]:t}}function Uo(e,t,i){const s=new URLSearchParams;i?.path!==void 0&&s.set("path",i.path),i?.staged===!0&&s.set("staged","true");const r=s.toString();return`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/diff${r?`?${r}`:""}`}function Vo(e,t){const i=new URLSearchParams;t?.limit!==void 0&&i.set("limit",String(t.limit)),t?.before!==void 0&&i.set("before",String(t.before));const s=i.toString();return`/api/sessions/${e}/messages${s?`?${s}`:""}`}const Rs={piWebStatus:()=>w("/api/pi-web/status",Ro)},Ko={projects:()=>w("/api/projects",j(Oi)),addProject:(e,t,i)=>w("/api/projects",Oi,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:e=>w(`/api/projects/${encodeURIComponent(e)}`,Ms,{method:"DELETE"}),projectDirectories:e=>w(`/api/project-directories?q=${encodeURIComponent(e)}`,j(As))},Go={workspaces:e=>w(`/api/projects/${e}/workspaces`,j(no)),workspaceTree:(e,t,i="")=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Po),workspaceFile:(e,t,i)=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Co)},Qo={sessions:e=>w(`/api/sessions?cwd=${encodeURIComponent(e)}`,j(Dt)),startSession:e=>w("/api/sessions",Dt,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t)=>w(Vo(e,t),oo),status:e=>w(`/api/sessions/${e}/status`,Le),models:e=>w(`/api/sessions/${e}/models`,po),setModel:(e,t,i)=>w(`/api/sessions/${e}/model`,Le,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t)=>w(`/api/sessions/${e}/model/cycle`,Le,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:e=>w(`/api/sessions/${e}/thinking-levels`,uo),setThinkingLevel:(e,t)=>w(`/api/sessions/${e}/thinking-level`,Le,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:e=>w(`/api/sessions/${e}/thinking-level/cycle`,Le,{method:"POST"}),commands:e=>w(`/api/sessions/${e}/commands`,j($o)),prompt:(e,t,i)=>w(`/api/sessions/${e}/prompt`,Ye,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t)=>w(`/api/sessions/${e}/shell`,Ye,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t)=>w(`/api/sessions/${e}/commands/run`,Fi,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i)=>w(`/api/sessions/${e}/commands/respond`,Fi,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:e=>w(`/api/sessions/${e}/abort`,Fo,{method:"POST"}),stop:e=>w(`/api/sessions/${e}/stop`,zo,{method:"POST"}),archive:e=>w(`/api/sessions/${e}/archive`,qo,{method:"POST"}),restore:e=>w(`/api/sessions/${e}/restore`,Ho,{method:"POST"}),detachParent:e=>w(`/api/sessions/${e}/detach-parent`,Bo,{method:"POST"}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return w(`/api/auth/providers${i===""?"":`?${i}`}`,vo)},saveApiKey:(e,t)=>w("/api/auth/api-key",Ye,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:e=>w("/api/auth/logout",Ye,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:e=>w("/api/auth/oauth",Je,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:e=>w(`/api/auth/oauth/${encodeURIComponent(e)}`,Je),respondOAuthFlow:(e,t,i)=>w(`/api/auth/oauth/${encodeURIComponent(e)}/respond`,Je,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:e=>w(`/api/auth/oauth/${encodeURIComponent(e)}/cancel`,Je,{method:"POST"})},Es={terminals:(e,t)=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ji)),startTerminal:(e,t,i)=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ji,{method:"POST",body:JSON.stringify(i??{})}),closeTerminal:(e,t,i)=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Ms,{method:"DELETE"})},Zo={files:(e,t,i,s)=>w(`/api/files?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}${i!==void 0?`&kind=${encodeURIComponent(i)}`:""}${s!==void 0?`&mode=${encodeURIComponent(s)}`:""}`,j(As))},Jo={gitStatus:(e,t)=>w(`/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ao),gitDiff:(e,t,i)=>w(Uo(e,t,i),Mo)},O={...Rs,...Ko,...Go,...Qo,...Es,...Zo,...Jo};function Yo(e){return new WebSocket(`${Jt()}/api/sessions/${e}/events`)}function cp(e,t,i,s){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Jt()}/api/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Xo(){return new WebSocket(`${Jt()}/api/events`)}function Jt(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function en(){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,themeDialog: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,piWebStatus:void 0,error:""}}class tn{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??O,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=sn(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout"});if(t!==void 0&&t!==""){const s=i.find(r=>r.id===t);s!==void 0?await this.logoutProvider(s.id):this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){try{await this.api.logoutProvider(t),this.closeDialog(),this.refreshStatus()}catch(i){this.setState({error:String(i)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r);this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId)}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login"}),s=i.filter(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){try{const i=await this.api.startOAuthLogin(t.id);this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",l=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:l}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function sn(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function ct(e){return e.replaceAll(":",".")}function rn(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function qi(e,t){const i=rn(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function dt(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));on(r,s)}function on(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Hi=ct("core:workspace.files");class nn{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await O.workspaceTree(t.id,i.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await O.workspaceTree(t.id,i.id,o)).entries})),this.setState({fileTree:s.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:ln(this.getState().expandedDirs,t)});return}try{const r=await O.workspaceTree(i.id,s.id,t);this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),dt(Hi,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const r=await O.workspaceFile(i.id,s.id,t);this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(an(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),dt(Hi,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function an(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function ln(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Bi=ct("core:workspace.git");class cn{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await O.gitStatus(t.id,i.id);this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),dt(Bi,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),dt(Bi,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([O.gitDiff(i.id,s.id,{path:t}),O.gitDiff(i.id,s.id,{path:t,staged:!0})]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class dn{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){this.setState({error:""});try{this.setState({projects:await O.projects()})}catch(t){this.setState({error:String(t)})}}async addProject(t,i){if(t.trim()!=="")try{const s=await O.addProject(t.trim(),void 0,i),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await O.closeProject(t),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Lt="pi-web:cached-new-sessions:v1",pn="browserCachedNew";function Ke(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ui(e,t=Ke()){if(e.messageCount!==0||e.archived===!0)return;const i=Yt(t).filter(s=>s.id!==e.id);Xt([Ot(e),...i],t)}function Ot(e){return{...e,browserCachedNew:!0}}function Vi(e,t=Ke()){const i=Yt(t).filter(s=>s.id!==e);Xt(i,t)}function hn(e,t,i=Ke()){const s=new Set(t.map(a=>a.id)),r=Yt(i),o=r.filter(a=>!s.has(a.id));return o.length!==r.length&&Xt(o,i),[...o.filter(a=>a.cwd===e),...t]}function Pe(e){return e===void 0?!1:gn(e)&&e.browserCachedNew===!0}function un(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Yt(e=Ke()){try{const t=e?.getItem(Lt);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>fn(s)):[]}catch{return[]}}function Xt(e,t=Ke()){try{e.length===0?t?.removeItem(Lt):t?.setItem(Lt,JSON.stringify(e))}catch{}}function fn(e){if(!mn(e))return[];const t=ke(e,"id"),i=ke(e,"path"),s=ke(e,"cwd"),r=ke(e,"created"),o=ke(e,"modified"),n=ke(e,"firstMessage"),a=bn(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const l=Ki(e,"name"),c=Ki(e,"parentSessionPath");return[{id:t,path:i,cwd:s,...l===void 0?{}:{name:l},created:r,modified:o,messageCount:a,firstMessage:n,...c===void 0?{}:{parentSessionPath:c},browserCachedNew:!0}]}function gn(e){return pn in e}function mn(e){return typeof e=="object"&&e!==null}function ke(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ki(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function bn(e,t){const i=e[t];return typeof i=="number"?i:void 0}function vn(e){return _n(e.flatMap(ei)).filter(t=>t.parts.length>0)}function ee(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Xe(e,t){const i=Pn(t);return i===void 0?e:{...e,meta:i}}function wn(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,ee(t,i)]}function yn(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function ei(e){if(xn(e))return[e];if(C(e,"role")==="bashExecution")return[Xe(An(e),e)];const t=In(C(e,"role")),i=Mn(U(e,"content"),e),s=t==="user"?Sn(i):void 0;if(s!==void 0)return s.map(a=>Xe(a,e));const r=$n(e);if(t==="tool")return[Xe({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":t;return o.length>0?[Xe({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[]}function xn(e){const t=C(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(U(e,"parts"))}function Sn(e){if(e.length!==1||e[0]?.type!=="text")return;const t=kn(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function kn(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function $n(e){const t=C(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Pn(e){const t=Tn(U(e,"timestamp")),i=Cn(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Tn(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Cn(e){if(C(e,"role")!=="assistant")return;const t=C(e,"provider"),i=C(e,"model"),s=C(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function An(e){const t=C(e,"command")??"",i=rt(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=U(e,"output");s!=null&&i.push("",ht(s));const r=U(e,"exitCode");r!=null&&i.push("",`exit ${ht(r)}`),rt(e,"cancelled")===!0&&i.push("","cancelled"),rt(e,"truncated")===!0&&i.push("","output truncated");const o=C(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function In(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Mn(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=C(i,"type"),r=C(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=C(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=C(i,"name")??"tool",n=U(i,"arguments"),a=o==="read"?En(C(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const l=C(i,"id");return[{type:"toolCall",...l===void 0?{}:{toolCallId:l},toolName:o,summary:Ge(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:Gi(i)}).map(i=>i.type==="text"&&C(t,"role")==="toolResult"?Rn(i.text,t):i):Gi(e)}function Rn(e,t){const i=C(t,"toolCallId"),s=U(t,"content"),r=U(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:C(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:rt(t,"isError")===!0}}function En(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function _n(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const l=Dn(a),c=t.length;t.push({role:"tool",parts:[l],...o}),l.toolCallId!==void 0&&i.set(l.toolCallId,{lineIndex:c,partIndex:0});continue}if(a.type==="toolResult"){const l=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(l!==void 0&&Ln(t,l,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Dn(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function Ln(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=pt(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function pt(e){const t=U(e,"preview");if(!ti(t))return;const i=C(t,"diff"),s=C(t,"error"),r=Nn(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function Gi(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Ge(e)}]:[{type:"text",text:ht(e)}]}function Ge(e){if(!ti(e))return ht(e);const t=C(e,"command");if(t!==void 0)return t;const i=C(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${On(n)}`).join(" · ")}function On(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function ti(e){return typeof e=="object"&&e!==null}function U(e,t){return ti(e)?e[t]:void 0}function C(e,t){const i=U(e,t);return typeof i=="string"?i:void 0}function rt(e,t){const i=U(e,t);return typeof i=="boolean"?i:void 0}function Nn(e,t){const i=U(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function ht(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const jn="pi-web:prompt-draft:";function ut(e){return`${jn}${e}`}function kt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function _s(e,t=kt()){try{return t?.getItem(ut(e))??""}catch{return""}}function Nt(e,t,i=kt()){try{t?i?.setItem(ut(e),t):i?.removeItem(ut(e))}catch{}}function ii(e,t=kt()){try{t?.removeItem(ut(e))}catch{}}function Wn(e,t,i=kt()){const s=_s(e,i);s!==""&&(Nt(t,s,i),ii(e,i))}function Fn(e,t){return ee("bash",`${t===!0?`excluded from context
6
+
7
+ `:""}$ ${e}`)}function zn(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,ee("bash",t)];const r=Hn(s.text)?"":`
8
+
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function qn(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
10
+
11
+ `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash command failed"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`full output: ${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
+
13
+ ${r.join(`
14
+ `)}`}]}]}function Hn(e){const t=e.lastIndexOf(`
15
+
16
+ `),i=e.lastIndexOf("$ ");return t>i}function Bn(e,t){if(t.type==="message.append")return ea(e,t.message);if(t.type==="assistant.delta")return wn(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return yn(e,t.text);if(t.type==="tool.start")return Gn(e,t);if(t.type==="tool.update")return Ls(e,t.toolCallId,i=>Qn(i,t));if(t.type==="tool.end")return Ds(e,t.toolCallId,t.toolName,Ge(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Fn(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return zn(e,t.chunk);if(t.type==="shell.end")return qn(e,t);if(t.type==="command.output")return[...e,ee(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,ee("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Un(e,t.message)}function Un(e,t){const i=Zn(t);if(i!==void 0)return Ds(e,i.toolCallId,i.toolName,Ge(i.content),i.text,i.isError,i.content,i.details);const s=ei(t)[0];if(s===void 0)return;const r=s.role==="assistant"?Vn(s):s;if(r.parts.length===0)return e;const o=Jn(e,r);if(o>=0)return[...e.slice(0,o),r,...e.slice(o+1)];const n=e.at(-1);return n?.role!==r.role?[...e,r]:r.role==="assistant"||Xn(n,r)?[...e.slice(0,-1),r]:[...e,r]}function Vn(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Kn(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function Gn(e,t){const i=t.toolName==="read"?Kn(me(t.args,"path")):void 0;if(i!==void 0)return ta(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Ge(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function Qn(e,t){const i=pt(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Ds(e,t,i,s,r,o,n,a){const l=Ls(e,t,p=>{const f=pt(a)??p.preview;return{...p,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(l!==e)return l;const c=pt(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...c===void 0?{}:{preview:c}};return[...e,{role:"tool",parts:[u]}]}function Ls(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(l=>l.type==="toolExecution"&&l.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Zn(e){if(me(e,"role")!=="toolResult")return;const t=me(e,"toolCallId"),i=gt(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:me(e,"toolName")??"tool",text:Os(i),isError:sa(e,"isError")===!0,content:i,details:gt(e,"details")}}function Os(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Os).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=me(e,"text")??me(e,"content")??me(e,"output");if(t!==void 0)return t}return""}function Jn(e,t){const i=ft(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r?.role!=="skill")continue;const o=ft(r);if(Ns(o,i))return s}return-1}function ft(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Ns(e,t){return e.length===t.length&&e.every((i,s)=>Yn(i,t[s]))}function Yn(e,t){return t===void 0?!1:Qi(e.path)===Qi(t.path)||e.name===t.name}function Qi(e){return e.replace(/\\/g,"/")}function Xn(e,t){return Zi(e)===Zi(t)}function Zi(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
+
19
+ `)}function ea(e,t){const i=ei(t);return i.length===0?e:[...e,...i]}function ta(e,t){const i=e.at(-1);return t.role==="skill"&&Ns(ft(i),ft(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function ia(e){return typeof e=="object"&&e!==null}function gt(e,t){return ia(e)?e[t]:void 0}function me(e,t){const i=gt(e,t);return typeof i=="string"?i:void 0}function sa(e,t){const i=gt(e,t);return typeof i=="boolean"?i:void 0}const ra="pi-web:chat-history:v2:",oa=1800*1e3;function na(e){try{const t=sessionStorage.getItem(jt(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!pa(i))return;if(Date.now()-i.savedAt>oa){sessionStorage.removeItem(jt(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function aa(e,t){try{sessionStorage.setItem(jt(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function la(e,t){if(e===void 0||!Wt(e))return t;if(!Wt(t))return e;if(ca(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),r=new Array(s-i);return Ji(r,i,e),Ji(r,i,t),da(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function ca(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function da(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Ji(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function jt(e){return`${ra}${e}`}function pa(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&Wt({messages:t,start:i,total:s})}function Wt(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(ha)}function ha(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const ua={read:na,write:aa};class fa{constructor(t=ua){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Yi(this.rawHistoryPage(t))}mergeHistory(t,i){const s=la(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Yi(s)}applyLiveEvent(t,i){return Bn(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Yi(e){return{messages:vn(e?.messages??[]),messagePageStart:e?.start??0,messagePageTotal:e?.total??0}}function js(e){const t=e.trimStart();return t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Ws(e).startsWith("/")?{kind:"command"}:ma(e)?{kind:"file"}:{kind:"normal"}}function ga(e){return js(e).kind==="shell"}function Ws(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
20
+ `))+1;return e.slice(t)}function ma(e){const t=Ws(e);if(t.startsWith("@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const r=e.slice(0,s);return r.endsWith("@")||r.endsWith("@ ")}class ba{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1}connect(t,i,s){this.close(),this.sessionId=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),zs(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 t=Yo(this.sessionId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Fs(t);wa(i)&&this.onEvent?.(i)}}class va{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(t,i){this.close(),this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),zs(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const t=Xo();this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Fs(t);xa(i)&&this.onEvent?.(i)}}function wa(e){const t=si(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","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(t)}function ya(e){const t=si(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function xa(e){const t=si(e);return ya(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"}function si(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Fs(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function zs(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}class Sa{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function ka(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return $a(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function $a(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Pa(e,t,i){return e.map(s=>s.id===t?{...s,archived:!0,archivedAt:i}:s)}function Ta(e,t,i){if(t!==i)return{type:"unchanged"};const s=e.find(r=>r.id!==i&&r.archived!==!0);return s===void 0?{type:"clear"}:{type:"select",session:s}}const Oe=100;class Ca{constructor(t,i,s,r=new Sa,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new ba,this.api=o.api??O,this.transcripts=o.transcripts??new fa}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.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 t=this.getState().selectedWorkspace;if(t)try{const i=await this.api.startSession(t.path);Ui(i);const s=Ot(i);this.setState({sessions:[s,...this.getState().sessions]}),await this.selectSession(s)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return ka(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(t)})}async selectSession(t,i){this.sessionSelection.rememberSession(t);const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=this.transcripts.cachedView(t.id);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t.id,{limit:Oe});if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(t.id,u);this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const o=[];this.socket.connect(t.id,u=>o.push(u),()=>{this.refreshSelectedSession(t.id)});const[n,a]=await Promise.all([this.api.messages(t.id,{limit:Oe}),this.api.status(t.id)]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const l=this.transcripts.mergeHistory(t.id,n),c=a.isStreaming;this.catchupStreamSessionId=c?t.id:void 0,this.setState({...l,isLoadingEarlierMessages:!1,isReceivingPartialStream:c,status:a,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(a);for(const u of o)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(o){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Pe(t)&&Ma(o)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(o)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i.id,{before:t.messagePageStart,limit:Oe});if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(i.id,s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(ga(t))return this.runShell(t);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,t,i),this.markCachedNewSessionPersisted(r)}catch(o){this.setState({error:String(o)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ee("user",t)]});try{await this.api.shell(i.id,t),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ee("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ee("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t)),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ee("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Pe(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id);const i=this.getState(),s=Pa(i.sessions,t.id,new Date().toISOString()),r=Ta(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&(this.clearActiveSession(),this.updateUrl())}catch(i){this.setState({error:String(i)})}}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Pe(t))return;this.api.stop(t.id).catch(()=>{}),Vi(t.id),ii(t.id);const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t.id);const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id);const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t.id)).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s.id,t,i))}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i.id,t))}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t.id)).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t.id))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id)}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,r]=await Promise.all([this.api.messages(t,{limit:Oe}),this.api.status(t)]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(t,s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=await this.api.startSession(t.cwd);Ui(s),Wn(t.id,s.id),Vi(t.id);const r=Ot(s);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){Pe(t)&&this.replaceSession(un(t))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,ee(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){this.setState({sessionStatuses:{...this.getState().sessionStatuses,[t.sessionId]:t},status:this.getState().selectedSession?.id===t.sessionId?t:this.getState().status}),this.catchupStreamSessionId===t.sessionId&&!t.isStreaming&&this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Aa(t))return}if(Ia(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:Oe});if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(t,i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Aa(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function Ia(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Ma(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ra{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Ea(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class _a{constructor(t,i,s,r,o=new Ra){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o}clearSelection(t){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:""}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(t)}async selectProject(t,i){this.sessions.clearActiveSession(),this.setState({selectedProject:t,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 s=await O.workspaces(t.id);this.setState({workspaces:s});const r=Ea(s,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(t.id)});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(s){this.setState({error:String(s)})}}async selectWorkspace(t,i){this.workspaceSelection.rememberWorkspace(t),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,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 s=hn(t.path,await O.sessions(t.path));this.setState({sessions:s});const r=this.sessions.preferredSession(t.path,s,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(s){this.setState({error:String(s)})}}}const Da=1200;class La{constructor(){this.pendingTokens=[]}handle(t,i){const s=Na(t);if(s===void 0||!Xi(s))return!1;const r=i.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:qs(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!Xi(s)?[...this.pendingTokens,s]:[s],n=r.find(l=>Wa(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>Hs(l.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Da)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Oa(e){return qs(e).map(t=>t.split("+").map(i=>i==="mod"?es()?"⌘":"Ctrl":i==="shift"?"Shift":i==="alt"?es()?"⌥":"Alt":i==="ctrl"?"Ctrl":i==="enter"?"Enter":i==="escape"?"Esc":i==="."?".":i.length===1?i.toUpperCase():`${i.charAt(0).toUpperCase()}${i.slice(1)}`).join("+")).join(" ")}function Na(e){if(e.isComposing)return;const t=ja(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function qs(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t!=="").map(t=>t.split("+").filter(i=>i!=="").join("+"))}function ja(e){if(e===" ")return"space";if(e.length===1)return e.toLowerCase();const t=e.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(t))return t}function Wa(e,t){return e.length===t.length&&Hs(e,t)}function Hs(e,t){return t.every((i,s)=>e[s]===i)}function Xi(e){return e.includes("+")}function es(){return navigator.userAgent.toLowerCase().includes("mac")}const Rt="themes:current",Bs="pi-web-app-theme",Fa=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],za=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function qa(){try{const e=window.localStorage.getItem(Bs);return Ha(e)?e:void 0}catch{return}}function ts(e,t={}){const i=document.documentElement;i.dataset.piWebTheme=e.id,i.style.colorScheme=e.colorScheme;for(const s of Fa){const r=e.tokens[s];typeof r=="string"&&r!==""?i.style.setProperty(s,r):i.style.removeProperty(s)}if(t.persist!==!1)try{window.localStorage.setItem(Bs,e.id)}catch{}}function Ha(e){return e!==null&&za.test(e)}function Ba(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",group:"General",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the Pi Web color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.selectMainView("chat")}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:et,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:is,run:e=>{e.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:et,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:is,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:et,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:et,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&e.state.selectedSession.archived!==!0,run:e=>e.archiveSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ua(e.state.status),run:e=>e.stopActiveWork()}]}function et(e){return e.state.selectedWorkspace!==void 0}function is(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Ua(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0}const Va="modulepreload",Ka=function(e){return"/"+e},ss={},Us=function(t,i,s){let r=Promise.resolve();if(i&&i.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(i.map(c=>{if(c=Ka(c),c in ss)return;ss[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":Va,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((m,b)=>{f.addEventListener("load",m),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 t().catch(o)})};function Ga(){return[{id:"workspace.files",title:"Files",order:10,render:Qa},{id:"workspace.git",title:"Git",order:20,visible:({workspace:e})=>e.isGitRepo,render:Xa},{id:"workspace.terminal",title:"Terminal",order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Ya}]}function Qa(e){return d`
21
+ <section class="toolbar">
22
+ <strong>Files</strong>
23
+ ${e.fileTreeStale?d`<span class="stale">stale</span>`:null}
24
+ <button @click=${e.onRefreshFiles}>Refresh</button>
25
+ </section>
26
+ <section class="split">
27
+ <div class="list tree">
28
+ ${e.fileTree.length===0?d`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Vs(e,t,0))}
29
+ </div>
30
+ <div class="viewer">
31
+ ${Ja(e)}
32
+ </div>
33
+ </section>
34
+ `}function Vs(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0;return d`
35
+ <button class="row" style=${`--depth:${String(i)}`} @click=${()=>{Za(e,t)}}>
36
+ <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
37
+ <span>${t.name}</span>
38
+ </button>
39
+ ${r?s.map(o=>Vs(e,o,i+1)):null}
40
+ `}function Za(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function Ja(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?d`<p class="muted">Select a file.</p>`:t===void 0?d`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.binary?d`<p class="muted">Binary file: ${t.path}</p>`:(Ks(),d`
41
+ <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
42
+ <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
43
+ `)}function Ya(e){return il(),d`<terminal-panel .workspace=${e.workspace} .autoStart=${e.terminalAutoStart}></terminal-panel>`}function Xa(e){const t=e.gitStatus;return d`
44
+ <section class="toolbar">
45
+ <strong>Git</strong>
46
+ ${e.gitStale?d`<span class="stale">stale</span>`:null}
47
+ <button @click=${e.onRefreshGit}>Refresh</button>
48
+ </section>
49
+ <section class="split">
50
+ <div class="list">
51
+ ${t===void 0?d`<p class="muted">No status loaded.</p>`:t.isGitRepo?d`
52
+ <p class="summary">${sl(t)}</p>
53
+ ${t.files.length===0?d`<p class="muted">No changes.</p>`:t.files.map(i=>d`
54
+ <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
55
+ <span>${rl(i.index,i.workingTree)}</span>
56
+ <span>${i.path}</span>
57
+ </button>
58
+ `)}
59
+ `:d`<p class="muted">Not a git repository.</p>`}
60
+ </div>
61
+ <div class="viewer">
62
+ ${el(e)}
63
+ </div>
64
+ </section>
65
+ `}function el(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return d`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return d`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?d`<p class="muted">No staged or unstaged diff.</p>`:d`
66
+ <div class=${s.length===1?"diffs single":"diffs"}>
67
+ ${s.map(r=>tl(r))}
68
+ </div>
69
+ `}function tl(e){return Ks(),d`
70
+ <section class="diff-section">
71
+ <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
72
+ <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
73
+ </section>
74
+ `}function Ks(){Us(()=>import("./CodeViewer-BJm9p3hj.js"),__vite__mapDeps([0,1,2,3]))}function il(){Us(()=>import("./TerminalPanel-DMOCBUgN.js"),__vite__mapDeps([4,5,6,1,2]))}function sl(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function rl(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const ol={apiVersion:1,name:"Pi Web Core",activate:()=>({contributions:{actions:Ba(),workspacePanels:Ga()}})},nl={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},al={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#3d4a78","--pi-selection-bg":"#151b31","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},ll={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},cl={apiVersion:1,name:"Pi Web Themes",activate:()=>({contributions:{themes:[{id:"current",name:"Pi Web Current",description:"The original Pi Web dark palette.",order:10,colorScheme:"dark",tokens:nl},{id:"docs-dark",name:"Docs Dark",description:"Dark theme based on the Pi Web docs site.",order:20,colorScheme:"dark",tokens:al},{id:"docs-light",name:"Docs Light",description:"Light theme based on the Pi Web docs site.",order:30,colorScheme:"light",tokens:ll}]}})};async function dl(e="/pi-web-plugins/manifest.json"){const t=await pl(e);if(t===void 0)return[];const i=[];for(const s of t.plugins)try{const r=new URL(s.module,new URL(e,window.location.href)).toString(),o=await import(r),n=ul(o,r);i.push({id:s.id,plugin:n})}catch(r){console.warn(`Failed to load Pi Web plugin ${s.module}`,r)}return i}async function pl(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return hl(await t.json())}}function hl(e){if(!mt(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!mt(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module}})}}function ul(e,t){if(!mt(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!fl(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function fl(e){return mt(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function mt(e){return typeof e=="object"&&e!==null}const gl=/^[a-z][a-z0-9.-]*$/u,ml=/^[a-z][a-z0-9.-]*$/u;class bl{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.pluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const n=s.activate({apiVersion:1,pluginId:i,html:d}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a));for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a))}getActions(t){return this.actions.map(i=>{const s=i.enabled?.(t),r={id:i.id,pluginId:i.pluginId,localId:i.localId,title:i.title,run:()=>i.run(t)};return i.description!==void 0&&(r.description=i.description),i.shortcut!==void 0&&(r.shortcut=i.shortcut),i.group!==void 0&&(r.group=i.group),s!==void 0&&(r.enabled=s),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t,i){const s={state:t,workspace:i};return[...this.workspaceLabels].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>r.visible?.(s)===!1?[]:r.items(s))}qualifyAction(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyWorkspacePanel(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyWorkspaceLabelContribution(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}validatePluginId(t){if(!gl.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!ml.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function vl(){const e=new URLSearchParams(window.location.search);return{projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:yl(e.get("tool")),view:xl(e.get("view"))}}function wl(e,t){const i=new URL(window.location.href);i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function yl(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Gs(e)?e:void 0}function xl(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Gs(e)?e:void 0}function Gs(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}const Sl=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Qs(e){return e.composedPath().some(t=>kl(t,Sl))}function kl(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function ri(e,t){Qs(e)||t()}function oi(e,t){e.key!=="Enter"&&e.key!==" "||Qs(e)||(e.preventDefault(),t())}const $l=H`
75
+ :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: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
76
+ .shell { display: grid; grid-template-columns: 340px minmax(420px, 1fr) minmax(360px, 42vw); height: 100%; min-height: 0; }
77
+ aside { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--pi-border); overflow: hidden; }
78
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
79
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; overflow: auto; border-bottom: 1px solid var(--pi-border-muted); }
80
+ session-list { flex: 1 1 auto; min-height: 0; overflow: auto; }
81
+ main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
82
+ .mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
83
+ .mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
84
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
85
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
86
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
87
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; -webkit-overflow-scrolling: touch; }
88
+ .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
89
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
90
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
91
+ .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
92
+ workspace-panel { min-width: 0; min-height: 0; border-left: 1px solid var(--pi-border); overflow: hidden; }
93
+ @media (max-width: 1180px) {
94
+ .shell { grid-template-columns: 340px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
95
+ aside { grid-row: 1 / 3; }
96
+ main { grid-column: 2; grid-row: 1 / 3; }
97
+ .mobile-tabs-frame { display: flex; }
98
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
99
+ .shell.workspace-view > workspace-panel { grid-column: 2; grid-row: 2; display: flex; border-left: 0; }
100
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
101
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
102
+ main.workspace-view .empty { display: none; }
103
+ main.workspace-view { overflow: hidden; }
104
+ }
105
+ @media (max-width: 760px) {
106
+ .shell { grid-template-columns: minmax(0, 1fr); }
107
+ aside { display: none; }
108
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
109
+ .mobile-navigation-tab { display: block; }
110
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
111
+ main.navigation-view .empty { display: none; }
112
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
113
+ main.navigation-view .mobile-navigation-panel project-list,
114
+ main.navigation-view .mobile-navigation-panel workspace-list,
115
+ main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: auto; }
116
+ main.navigation-view .mobile-navigation-panel project-list[collapsed],
117
+ main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
118
+ main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
119
+ }
120
+ status-bar { flex: 0 0 auto; }
121
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
122
+ prompt-editor, chat-composer { flex: 0 0 auto; }
123
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
124
+ .empty { margin: auto; color: var(--pi-muted); }
125
+ .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
126
+ `,Pl=H`
127
+ :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; }
128
+ header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
129
+ .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
130
+ .workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
131
+ .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
132
+ .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
133
+ .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
134
+ .workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; -webkit-overflow-scrolling: touch; }
135
+ .tabs { flex: 0 0 auto; display: flex; gap: 6px; }
136
+ .tabs button { flex: 0 0 auto; white-space: nowrap; }
137
+ button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
138
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
139
+ .tab-badge { display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
140
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
141
+ small, .muted { color: var(--pi-muted); }
142
+ header small { flex: 0 0 auto; min-width: max-content; overflow: visible; text-overflow: clip; white-space: nowrap; }
143
+ header .workspace-label { width: max-content; max-width: none; overflow: visible; }
144
+ header .workspace-label-base, header .workspace-label-item, header .workspace-label-render { overflow: visible; text-overflow: clip; }
145
+ @media (max-width: 1180px) { .tabs { display: none; } }
146
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
147
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
148
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
149
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
150
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
151
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
152
+ .toolbar button { margin-left: auto; }
153
+ .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
154
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
155
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
156
+ .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); }
157
+ .row:hover, .row.selected { background: var(--pi-selection-bg); }
158
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
159
+ .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
160
+ .viewer { min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
161
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
162
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
163
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
164
+ .diff-section:last-child { border-bottom: 0; }
165
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
166
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
167
+ code-viewer { flex: 1 1 auto; min-height: 0; }
168
+ 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; }
169
+ p { margin: 10px; }
170
+ `,ni=H`
171
+ :host { display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
172
+ :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
173
+ section { padding: 10px; }
174
+ h2 { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
175
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
176
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
177
+ .subheading { margin-top: 14px; }
178
+ .section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-transform: inherit; }
179
+ .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
180
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
181
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
182
+ .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
183
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
184
+ .action-row.archived .action-main { color: var(--pi-muted); }
185
+ .action-main { box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
186
+ .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
187
+ .workspace-row .action-main { border-radius: 8px; }
188
+ .tree-marker { color: var(--pi-dim); margin-right: 5px; }
189
+ .badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
190
+ .action-menu { position: relative; align-self: stretch; }
191
+ .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
192
+ .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
193
+ .action-menu-panel { position: fixed; z-index: 50; min-width: 120px; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
194
+ .action-menu-panel button { display: block; width: 100%; text-align: left; border: 0; background: transparent; color: var(--pi-text); }
195
+ .action-menu-panel button:hover { background: var(--pi-selection-bg); }
196
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
197
+ button:disabled { opacity: .5; cursor: not-allowed; }
198
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
199
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
200
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
201
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
202
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
203
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
204
+ `,Tl=H`
205
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
206
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
207
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
208
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
209
+ .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 var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
210
+ .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
211
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
212
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
213
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
214
+ .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
215
+ .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
216
+ .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
217
+ .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
218
+ .msg.system { color: var(--pi-danger); }
219
+ .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
220
+ .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
221
+ .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
222
+ .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
223
+ .msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
224
+ .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
225
+ .msg.event-group > summary .label { margin: 0; }
226
+ .group-body { padding: 0 12px 12px; }
227
+ .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
228
+ .group-msg.tool { color: var(--pi-warning); }
229
+ .group-msg.tool-execution-shell { color: var(--pi-text); }
230
+ .group-msg.system { color: var(--pi-danger); }
231
+ .group-msg.bash { color: var(--pi-success); }
232
+ .history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
233
+ .history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
234
+ .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
235
+ .history-load-button:disabled { cursor: default; opacity: .55; }
236
+ .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 var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
237
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
238
+ .queued-header strong { color: var(--pi-warning); }
239
+ .queued-header small { color: var(--pi-muted); }
240
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
241
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
242
+ .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
243
+ .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 var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
244
+ .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
245
+ .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
246
+ .session-activity strong { color: var(--pi-purple); }
247
+ .session-activity.receiving strong { color: var(--pi-success); }
248
+ .session-activity span, .session-activity small { color: var(--pi-muted); }
249
+ .history-boundary small { color: var(--pi-dim); }
250
+ .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
251
+ .msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
252
+ .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
253
+ .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
254
+ .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
255
+ .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
256
+ .group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
257
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
258
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
259
+ .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
260
+ .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
261
+ .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; }
262
+ .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
263
+ .msg-header .label { margin: 0; }
264
+ .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); 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; }
265
+ .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; }
266
+ .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
267
+ @media (hover: none) {
268
+ .msg-actions { opacity: 1; }
269
+ .msg-meta { opacity: .75; max-width: 26px; }
270
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
271
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
272
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
273
+ }
274
+ formatted-text.part { display: block; }
275
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
276
+ .part + .part { margin-top: 10px; }
277
+ .tool-line { color: var(--pi-warning); }
278
+ .summary { color: var(--pi-muted); margin-left: 6px; }
279
+ .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
280
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
281
+ .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
282
+ .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
283
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
284
+ summary { cursor: pointer; color: var(--pi-muted); }
285
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
286
+ .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
287
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
288
+ `,Cl=H`
289
+ :host { display: block; }
290
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
291
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
292
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
293
+ ul, ol { padding-left: 22px; }
294
+ li + li { margin-top: 3px; }
295
+ code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
296
+ .code-block-wrapper { position: relative; }
297
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
298
+ pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
299
+ pre code { border: 0; padding: 0; background: transparent; }
300
+ .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 var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
301
+ .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
302
+ blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
303
+ a { color: var(--pi-accent); }
304
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
305
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
306
+ h1 { font-size: 20px; }
307
+ h2 { font-size: 17px; }
308
+ h3 { font-size: 15px; }
309
+ h4 { font-size: 14px; }
310
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
311
+ th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
312
+ th { background: var(--pi-surface); }
313
+ `,Al=H`
314
+ :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
315
+ .bar { display: flex; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
316
+ span { overflow: hidden; text-overflow: ellipsis; }
317
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
318
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
319
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
320
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
321
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
322
+ .bar > span:first-child { flex: 1 1 auto; min-width: 80px; }
323
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
324
+ .activity.active { color: var(--pi-success); }
325
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
326
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
327
+ .muted { color: var(--pi-dim); }
328
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
329
+ `,Il=H`
330
+ :host { display: block; }
331
+ .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
332
+ button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
333
+ button:last-child { border-bottom: 0; }
334
+ button.selected, button:hover { background: var(--pi-selection-bg); }
335
+ span { color: var(--pi-muted); font-size: 12px; }
336
+ small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
337
+ `,Zs=H`
338
+ :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
339
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
340
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
341
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
342
+ .options { min-height: 0; overflow: auto; outline: none; }
343
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
344
+ header button { font-size: 20px; color: var(--pi-muted); }
345
+ input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
346
+ input:focus { border-color: var(--pi-accent); }
347
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
348
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
349
+ small { display: block; margin-top: 4px; color: var(--pi-muted); }
350
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
351
+ `,Ml=H`
352
+ :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
353
+ .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: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
354
+ 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 var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
355
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
356
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
357
+ input::placeholder { color: var(--pi-dim); }
358
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
359
+ header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
360
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; -webkit-overflow-scrolling: touch; }
361
+ .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
362
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
363
+ .main { min-width: 0; }
364
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
365
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
366
+ .group { grid-column: 1 / -1; font-size: 12px; }
367
+ kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
368
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
369
+ `,Rl=H`
370
+ :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
371
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
372
+ footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
373
+ .editor-wrap { position: relative; min-width: 0; }
374
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
375
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
376
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
377
+ .select-model { max-width: min(42vw, 320px); }
378
+ .select-thinking { max-width: 110px; }
379
+ 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 var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
380
+ textarea { overflow-y: auto; padding: 8px; }
381
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
382
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
383
+ .markdown-editor .cm-line { padding: 0; }
384
+ .markdown-editor .cm-placeholder { color: var(--pi-dim); }
385
+ .markdown-editor .cm-focused { outline: none; }
386
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
387
+ .mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
388
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
389
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
390
+ @media (max-width: 640px) {
391
+ footer { gap: 8px; padding: 8px; }
392
+ .actions { gap: 6px; }
393
+ .compact-status { flex: 1 1 220px; gap: 4px; }
394
+ .select-model { max-width: min(58vw, 260px); }
395
+ button { padding: 6px 8px; }
396
+ }
397
+ @media (max-width: 430px) {
398
+ .compact-status { flex-basis: 170px; font-size: 11px; }
399
+ .select-model { max-width: 48vw; }
400
+ .select-thinking { max-width: 70px; }
401
+ button { padding: 5px 7px; }
402
+ }
403
+ `;var El=Object.defineProperty,_l=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?_l(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&El(t,i,r),r};let V=class extends M{constructor(){super(...arguments),this.projects=[],this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}render(){return d`
404
+ <section>
405
+ <h2>${this.renderHeading()}</h2>
406
+ ${this.collapsed?null:this.projects.map(e=>d`
407
+ <div
408
+ class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
409
+ tabindex="0"
410
+ title=${e.path}
411
+ @click=${t=>{ri(t,()=>this.onSelect?.(e))}}
412
+ @keydown=${t=>{oi(t,()=>this.onSelect?.(e))}}
413
+ >
414
+ <div class="action-main">
415
+ <span>${e.name}</span><small>${e.path}</small>
416
+ </div>
417
+ <div class="action-menu">
418
+ <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${e.name}`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
419
+ ${this.openMenuProjectId===e.id?d`
420
+ <div class="action-menu-panel" style=${this.menuStyle}>
421
+ <button title="Close project" @click=${()=>{this.close(e)}}>Close</button>
422
+ </div>
423
+ `:null}
424
+ </div>
425
+ </div>
426
+ `)}
427
+ </section>
428
+ `}renderHeading(){return this.collapsible?d`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span>${this.collapsed?"▸":"▾"} Projects</span><small>${this.projects.length}</small></button>`:"Projects"}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}if(t instanceof HTMLElement){const i=t.getBoundingClientRect();this.menuStyle=`top: ${String(i.bottom+4)}px; right: ${String(window.innerWidth-i.right)}px;`}this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
429
+
430
+ This only removes it from Pi Web; it will not change the project folder.`)&&this.onClose?.(e)}};V.styles=ni;ie([h({attribute:!1})],V.prototype,"projects",2);ie([h({attribute:!1})],V.prototype,"selected",2);ie([h({type:Boolean,reflect:!0})],V.prototype,"collapsible",2);ie([h({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);ie([h({attribute:!1})],V.prototype,"onSelect",2);ie([h({attribute:!1})],V.prototype,"onClose",2);ie([h({attribute:!1})],V.prototype,"onToggleCollapsed",2);ie([S()],V.prototype,"openMenuProjectId",2);ie([S()],V.prototype,"menuStyle",2);V=ie([F("project-list")],V);function Js(e,t=[],i){return d`
431
+ <span class="workspace-label">
432
+ <span class="workspace-label-base" title=${i??e}>${e}</span>
433
+ ${Ys(t)}
434
+ </span>
435
+ `}function Ys(e=[]){return e.map(t=>d`<span class="workspace-label-separator">·</span>${Dl(t)}`)}function Dl(e){if(e.type==="render")return d`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Ll(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return d`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return d`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Ll(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Ol=Object.defineProperty,Nl=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Nl(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ol(t,i,r),r};let te=class extends M{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[]}updated(e){(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}render(){return d`
436
+ <section>
437
+ <h2>${this.renderHeading()}</h2>
438
+ ${this.collapsed?null:this.workspaces.map(e=>{const t=`${e.label}${e.isMain?" · main":""}`;return d`
439
+ <div
440
+ class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
441
+ tabindex="0"
442
+ title=${e.path}
443
+ @click=${i=>{ri(i,()=>this.onSelect?.(e))}}
444
+ @keydown=${i=>{oi(i,()=>this.onSelect?.(e))}}
445
+ >
446
+ <div class="action-main">
447
+ <span class="workspace-label">
448
+ <span class="workspace-label-base">${t}</span>
449
+ ${Ys(this.workspaceLabelItems(e))}
450
+ </span>
451
+ <small>${e.path}</small>
452
+ </div>
453
+ </div>
454
+ `})}
455
+ </section>
456
+ `}renderHeading(){return this.collapsible?d`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span>${this.collapsed?"▸":"▾"} Workspaces</span><small>${this.workspaces.length}</small></button>`:"Workspaces"}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};te.styles=ni;pe([h({attribute:!1})],te.prototype,"workspaces",2);pe([h({attribute:!1})],te.prototype,"selected",2);pe([h({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);pe([h({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);pe([h({attribute:!1})],te.prototype,"workspaceLabelItems",2);pe([h({attribute:!1})],te.prototype,"onSelect",2);pe([h({attribute:!1})],te.prototype,"onToggleCollapsed",2);te=pe([F("workspace-list")],te);var jl=Object.defineProperty,Wl=Object.getOwnPropertyDescriptor,L=(e,t,i,s)=>{for(var r=s>1?void 0:s?Wl(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&jl(t,i,r),r};function Fl(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends M{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){if(e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(t=>t.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(t=>t.archived===!0)&&(this.archivedExpanded=!1),this.selected?.archived===!0&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}render(){const e=zl(this.sessions),t=new Set(e.map(s=>s.session.id)),i=Xs(this.sessions.filter(s=>s.archived===!0&&!t.has(s.id)));return d`
457
+ <section>
458
+ ${this.renderHeading(e.length+i.length)}
459
+ ${this.collapsed?null:e.map(s=>this.renderSession(s))}
460
+ ${this.collapsed?null:i.length>0?d`
461
+ <h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span><small>${i.length}</small></button></h2>
462
+ ${this.archivedExpanded?i.map(s=>this.renderSession(s)):null}
463
+ `:null}
464
+ </section>
465
+ `}renderHeading(e){return this.collapsible?d`
466
+ <h2>
467
+ <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span>${this.collapsed?"▸":"▾"} Sessions</span><small>${e}</small></button>
468
+ <button ?disabled=${!this.canStart} @click=${t=>{t.stopPropagation(),this.onStart?.()}}>+</button>
469
+ </h2>
470
+ `:d`<h2>Sessions <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`}renderSession(e){const{session:t}=e,i=Math.min(e.depth,2);return d`
471
+ <div
472
+ class="action-row ${this.selected?.id===t.id?"selected":""} ${t.archived===!0?"archived":""}"
473
+ style=${`--depth:${String(i)}`}
474
+ tabindex="0"
475
+ title=${t.path}
476
+ @click=${s=>{ri(s,()=>this.onSelect?.(t))}}
477
+ @keydown=${s=>{oi(s,()=>this.onSelect?.(t))}}
478
+ >
479
+ <div class="action-main">
480
+ <span>${e.depth>0?d`<span class="tree-marker">↳</span>`:null}${Fl(t)}${e.depth>2?d` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?d` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderStatus(t)}${String(t.messageCount)} messages</small>
481
+ </div>
482
+ <div class="action-menu">
483
+ <button class="action-menu-toggle" title="Session actions" @click=${s=>{s.stopPropagation(),this.toggleMenu(t.id,s.currentTarget)}}>⋯</button>
484
+ ${this.openMenuSessionId===t.id?d`
485
+ <div class="action-menu-panel" style=${this.menuStyle}>
486
+ ${t.parentSessionPath!==void 0?d`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(t)}}>Detach from parent</button>`:null}
487
+ ${Pe(t)?d`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(t)}}>Delete</button>`:t.archived===!0?d`<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(t)}}>Restore</button>`:d`<button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(t)}}>Archive</button>`}
488
+ </div>
489
+ `:null}
490
+ </div>
491
+ </div>
492
+ `}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}if(t instanceof HTMLElement){const i=t.getBoundingClientRect();this.menuStyle=`top: ${String(i.bottom+4)}px; right: ${String(window.innerWidth-i.right)}px;`}this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0)}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(e){if(Pe(e))return"new · ";if(e.archived===!0)return"read-only · ";const t=this.statuses[e.id],i=this.activities[e.id];return i?.phase==="active"?`● ${i.label} · `:t===void 0?"":t.isStreaming?"● streaming · ":t.isBashRunning?"● bash · ":t.isCompacting?"● compacting · ":t.pendingMessageCount>0?`● ${String(t.pendingMessageCount)} pending · `:""}};R.styles=ni;L([h({attribute:!1})],R.prototype,"sessions",2);L([h({attribute:!1})],R.prototype,"statuses",2);L([h({attribute:!1})],R.prototype,"activities",2);L([h({attribute:!1})],R.prototype,"selected",2);L([h({type:Boolean})],R.prototype,"canStart",2);L([h({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);L([h({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);L([h({attribute:!1})],R.prototype,"onSelect",2);L([h({attribute:!1})],R.prototype,"onStart",2);L([h({attribute:!1})],R.prototype,"onToggleCollapsed",2);L([S()],R.prototype,"openMenuSessionId",2);L([S()],R.prototype,"menuStyle",2);L([S()],R.prototype,"archivedExpanded",2);L([h({attribute:!1})],R.prototype,"onArchive",2);L([h({attribute:!1})],R.prototype,"onRestore",2);L([h({attribute:!1})],R.prototype,"onDelete",2);L([h({attribute:!1})],R.prototype,"onDetachParent",2);R=L([F("session-list")],R);function zl(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return Xs(e.filter(s=>i.has(s.id)))}function Xs(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,l=a===void 0?void 0:t.get(a);if(l===void 0){s.push(n);continue}const c=i.get(l.path)??[];c.push(n),i.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&&!t.has(c)});const u=new Set(l);u.add(n.path);for(const p of i.get(n.path)??[])o(p,a+1,u)};for(const n of s)o(n,0,new Set);return r}const ai={CHILD:2,ELEMENT:6},li=e=>(...t)=>({_$litDirective$:e,values:t});let ci=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:ql}=Gr,rs=e=>e,os=()=>document.createComment(""),Ne=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(os(),r),n=s.insertBefore(os(),r);i=new ql(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let l;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(l=e._$AU)!==n._$AU&&i._$AP(l)}if(o!==r||a){let l=i._$AA;for(;l!==o;){const c=rs(l).nextSibling;rs(s).insertBefore(l,r),l=c}}}return i},ue=(e,t,i=e)=>(e._$AI(t,i),e),Hl={},Bl=(e,t=Hl)=>e._$AH=t,Ul=e=>e._$AH,Et=e=>{e._$AR(),e._$AA.remove()};const ns=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Vl=li(class extends ci{constructor(e){if(super(e),e.type!==ai.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=Ul(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],l=[];let c,u,p=0,f=r.length-1,m=0,b=o.length-1;for(;p<=f&&m<=b;)if(r[p]===null)p++;else if(r[f]===null)f--;else if(a[p]===n[m])l[m]=ue(r[p],o[m]),p++,m++;else if(a[f]===n[b])l[b]=ue(r[f],o[b]),f--,b--;else if(a[p]===n[b])l[b]=ue(r[p],o[b]),Ne(e,l[b+1],r[p]),p++,b--;else if(a[f]===n[m])l[m]=ue(r[f],o[m]),Ne(e,r[p],r[f]),f--,m++;else if(c===void 0&&(c=ns(n,m,b),u=ns(a,p,f)),c.has(a[p]))if(c.has(a[f])){const _=u.get(n[m]),Se=_!==void 0?r[_]:null;if(Se===null){const Re=Ne(e,r[p]);ue(Re,o[m]),l[m]=Re}else l[m]=ue(Se,o[m]),Ne(e,r[p],Se),r[_]=null;m++}else Et(r[f]),f--;else Et(r[p]),p++;for(;m<=b;){const _=Ne(e,l[b+1]);ue(_,o[m]),l[m++]=_}for(;p<=f;){const _=r[p++];_!==null&&Et(_)}return this.ut=n,Bl(e,l),de}});function Kl(e,t=0){const i=[];let s=[],r=0;const o=(a,l)=>{s.length||(r=l),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,l)=>{const c=a.parts.filter(m=>as(a,m)),u=a.parts.filter(m=>!as(a,m)),p=t+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 m=c.every(b=>b.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:m,parts:c,...f},index:p})}}),n(),i}function Gl(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function as(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Ql=30;function Zl(e,t){const i=Yl(tc(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Jl(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Xl(s,t.markerOffset);return}e.scrollTop=ec(e.scrollHeight,t.distanceFromBottom)}function Yl(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function Xl(e,t){return e-t}function ec(e,t){return Math.max(0,e-t)}function tc(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const ic=600,sc=1;function rc(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:oc(e)||nc(e)}function oc(e){return e.scrollTop<(e.topThreshold??Math.max(ic,e.clientHeight))}function nc(e){return e.scrollHeight<=e.clientHeight+sc}var ac=Object.defineProperty,lc=Object.getOwnPropertyDescriptor,di=(e,t,i,s)=>{for(var r=s>1?void 0:s?lc(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ac(t,i,r),r};let Ve=class extends M{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=ls(this.positionPercent),t=ls(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return d`
493
+ <div
494
+ class="meter"
495
+ style=${`--position:${e.toFixed(2)}%;`}
496
+ role="meter"
497
+ aria-label=${i}
498
+ aria-valuemin="0"
499
+ aria-valuemax="100"
500
+ aria-valuenow=${String(Math.round(e))}
501
+ title=${i}
502
+ >
503
+ <div class="track" aria-hidden="true">
504
+ <div class="progress"></div>
505
+ <div class="marker"></div>
506
+ </div>
507
+ </div>
508
+ `}};Ve.styles=H`
509
+ :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
510
+ :host(:hover), :host(:focus-within) { opacity: .92; }
511
+ .meter { height: 100%; }
512
+ .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
513
+ .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
514
+ .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
515
+ `;di([h({type:Number})],Ve.prototype,"positionPercent",2);di([h({type:Number})],Ve.prototype,"loadedPercent",2);Ve=di([F("conversation-meter")],Ve);function ls(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ft extends ci{constructor(t){if(super(t),this.it=I,t.type!==ai.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===I||t==null)return this._t=void 0,this.it=t;if(t===de)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}Ft.directiveName="unsafeHTML",Ft.resultType=1;const cc=li(Ft);function pi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ye=pi();function er(e){ye=e}var fe={exec:()=>null};function x(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(W.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var dc=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),W={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},pc=/^(?:[ \t]*(?:\n|$))+/,hc=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,uc=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Qe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,fc=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hi=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,tr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ir=x(tr).replace(/bull/g,hi).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(),gc=x(tr).replace(/bull/g,hi).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(),ui=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,mc=/^[^\n]+/,fi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,bc=x(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),vc=x(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,hi).getRegex(),$t="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",gi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,wc=x("^ {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",gi).replace("tag",$t).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),sr=x(ui).replace("hr",Qe).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",$t).getRegex(),yc=x(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",sr).getRegex(),mi={blockquote:yc,code:hc,def:bc,fences:uc,heading:fc,hr:Qe,html:wc,lheading:ir,list:vc,newline:pc,paragraph:sr,table:fe,text:mc},cs=x("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Qe).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",$t).getRegex(),xc={...mi,lheading:gc,table:cs,paragraph:x(ui).replace("hr",Qe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",cs).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",$t).getRegex()},Sc={...mi,html:x(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",gi).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:fe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:x(ui).replace("hr",Qe).replace("heading",` *#{1,6} *[^
516
+ ]`).replace("lheading",ir).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},kc=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$c=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,rr=/^( {2,}|\\)\n(?!\s*$)/,Pc=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Me=/[\p{P}\p{S}]/u,Pt=/[\s\p{P}\p{S}]/u,bi=/[^\s\p{P}\p{S}]/u,Tc=x(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Pt).getRegex(),or=/(?!~)[\p{P}\p{S}]/u,Cc=/(?!~)[\s\p{P}\p{S}]/u,Ac=/(?:[^\s\p{P}\p{S}]|~)/u,Ic=x(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",dc?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),nr=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Mc=x(nr,"u").replace(/punct/g,Me).getRegex(),Rc=x(nr,"u").replace(/punct/g,or).getRegex(),ar="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ec=x(ar,"gu").replace(/notPunctSpace/g,bi).replace(/punctSpace/g,Pt).replace(/punct/g,Me).getRegex(),_c=x(ar,"gu").replace(/notPunctSpace/g,Ac).replace(/punctSpace/g,Cc).replace(/punct/g,or).getRegex(),Dc=x("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,bi).replace(/punctSpace/g,Pt).replace(/punct/g,Me).getRegex(),Lc=x(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Me).getRegex(),Oc="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Nc=x(Oc,"gu").replace(/notPunctSpace/g,bi).replace(/punctSpace/g,Pt).replace(/punct/g,Me).getRegex(),jc=x(/\\(punct)/,"gu").replace(/punct/g,Me).getRegex(),Wc=x(/^<(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(),Fc=x(gi).replace("(?:-->|$)","-->").getRegex(),zc=x("^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",Fc).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),bt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,qc=x(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",bt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),lr=x(/^!?\[(label)\]\[(ref)\]/).replace("label",bt).replace("ref",fi).getRegex(),cr=x(/^!?\[(ref)\](?:\[\])?/).replace("ref",fi).getRegex(),Hc=x("reflink|nolink(?!\\()","g").replace("reflink",lr).replace("nolink",cr).getRegex(),ds=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,vi={_backpedal:fe,anyPunctuation:jc,autolink:Wc,blockSkip:Ic,br:rr,code:$c,del:fe,delLDelim:fe,delRDelim:fe,emStrongLDelim:Mc,emStrongRDelimAst:Ec,emStrongRDelimUnd:Dc,escape:kc,link:qc,nolink:cr,punctuation:Tc,reflink:lr,reflinkSearch:Hc,tag:zc,text:Pc,url:fe},Bc={...vi,link:x(/^!?\[(label)\]\((.*?)\)/).replace("label",bt).getRegex(),reflink:x(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",bt).getRegex()},zt={...vi,emStrongRDelimAst:_c,emStrongLDelim:Rc,delLDelim:Lc,delRDelim:Nc,url:x(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ds).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:x(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ds).getRegex()},Uc={...zt,br:x(rr).replace("{2,}","*").getRegex(),text:x(zt.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},tt={normal:mi,gfm:xc,pedantic:Sc},je={normal:vi,gfm:zt,breaks:Uc,pedantic:Bc},Vc={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ps=e=>Vc[e];function X(e,t){if(t){if(W.escapeTest.test(e))return e.replace(W.escapeReplace,ps)}else if(W.escapeTestNoEncode.test(e))return e.replace(W.escapeReplaceNoEncode,ps);return e}function hs(e){try{e=encodeURI(e).replace(W.percentDecode,"%")}catch{return null}return e}function us(e,t){let i=e.replace(W.findPipe,(o,n,a)=>{let l=!1,c=n;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),s=i.split(W.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(W.slashPipe,"|");return s}function le(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function fs(e){let t=e.split(`
517
+ `),i=t.length-1;for(;i>=0&&W.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
518
+ `)}function Kc(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function Gc(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function gs(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}function Qc(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
519
+ `).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
520
+ `)}var vt=class{options;rules;lexer;constructor(e){this.options=e||ye}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:fs(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=Qc(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=le(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:le(t[0],`
521
+ `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:le(t[0],`
522
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=le(t[0],`
523
+ `).split(`
524
+ `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],l;for(l=0;l<i.length;l++)if(this.rules.other.blockquoteStart.test(i[l]))a.push(i[l]),n=!0;else if(!n)a.push(i[l]);else break;i=i.slice(l);let c=a.join(`
525
+ `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
526
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
527
+ ${c}`:c,r=r?`${r}
528
+ ${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,i.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,b=m.raw+`
529
+ `+i.join(`
530
+ `),_=this.blockquote(b);o[o.length-1]=_,s=s.substring(0,s.length-m.raw.length)+_.raw,r=r.substring(0,r.length-m.text.length)+_.text;break}else if(f?.type==="list"){let m=f,b=m.raw+`
531
+ `+i.join(`
532
+ `),_=this.list(b);o[o.length-1]=_,s=s.substring(0,s.length-f.raw.length)+_.raw,r=r.substring(0,r.length-m.raw.length)+_.raw,i=b.substring(o.at(-1).raw.length).split(`
533
+ `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let l=!1,c="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let p=Gc(t[2].split(`
534
+ `,1)[0],t[1].length),f=e.split(`
535
+ `,1)[0],m=!p.trim(),b=0;if(this.options.pedantic?(b=2,u=p.trimStart()):m?b=t[1].length+1:(b=p.search(this.rules.other.nonSpaceChar),b=b>4?1:b,u=p.slice(b),b+=t[1].length),m&&this.rules.other.blankLine.test(f)&&(c+=f+`
536
+ `,e=e.substring(f.length+1),l=!0),!l){let _=this.rules.other.nextBulletRegex(b),Se=this.rules.other.hrRegex(b),Re=this.rules.other.fencesBeginRegex(b),xi=this.rules.other.headingBeginRegex(b),fr=this.rules.other.htmlBeginRegex(b),gr=this.rules.other.blockquoteBeginRegex(b);for(;e;){let At=e.split(`
537
+ `,1)[0],Ee;if(f=At,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),Ee=f):Ee=f.replace(this.rules.other.tabCharGlobal," "),Re.test(f)||xi.test(f)||fr.test(f)||gr.test(f)||_.test(f)||Se.test(f))break;if(Ee.search(this.rules.other.nonSpaceChar)>=b||!f.trim())u+=`
538
+ `+Ee.slice(b);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Re.test(p)||xi.test(p)||Se.test(p))break;u+=`
539
+ `+f}m=!f.trim(),c+=At+`
540
+ `,e=e.substring(At.length+1),p=Ee.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(e){let t=this.rules.block.html.exec(e);if(t){let i=fs(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:le(t[0],`
541
+ `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=us(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
542
+ `):[],o={type:"table",raw:le(t[0],`
543
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)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<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(us(n,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:le(t[0],`
544
+ `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
545
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let o=le(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=Kc(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),gs(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return gs(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,l=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){l+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+l);let u=[...s[0]][0].length,p=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let m=p.slice(1,-1);return{type:"em",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}let f=p.slice(2,-2);return{type:"strong",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(s=l.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let c=[...s[0]][0].length,u=e.slice(0,r+s.index+c+n),p=u.slice(r,-r);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},Q=class qt{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ye,this.options.tokenizer=this.options.tokenizer||new vt,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 i={other:W,block:tt.normal,inline:je.normal};this.options.pedantic?(i.block=tt.pedantic,i.inline=je.pedantic):this.options.gfm&&(i.block=tt.gfm,this.options.breaks?i.inline=je.breaks:i.inline=je.gfm),this.tokenizer.rules=i}static get rules(){return{block:tt,inline:je}}static lex(t,i){return new qt(i).lex(t)}static lexInline(t,i){return new qt(i).inlineTokens(t)}lex(t){t=t.replace(W.carriageReturn,`
546
+ `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(W.tabCharGlobal," ").replace(W.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
547
+ `:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
548
+ `)?"":`
549
+ `)+o.raw,a.text+=`
550
+ `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
551
+ `)?"":`
552
+ `)+o.raw,a.text+=`
553
+ `+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},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,l=t.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=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
554
+ `)?"":`
555
+ `)+o.raw,a.text+=`
556
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
557
+ `)?"":`
558
+ `)+o.raw,a.text+=`
559
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,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(s))!==null;)c.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let c;if(this.options.extensions?.inline?.some(p=>(c=p.call({lexer:this},t,i))?(t=t.substring(c.raw.length),i.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let p=i.at(-1);c.type==="text"&&p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):i.push(c);continue}if(c=this.tokenizer.emStrong(t,s,a)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.del(t,s,a)){t=t.substring(c.raw.length),i.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),i.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),i.push(c);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,f=t.slice(1),m;this.options.extensions.startInline.forEach(b=>{m=b.call({lexer:this},f),typeof m=="number"&&m>=0&&(p=Math.min(p,m))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(c=this.tokenizer.inlineText(u)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),n=!0;let p=i.at(-1);p?.type==="text"?(p.raw+=c.raw,p.text+=c.text):i.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},wt=class{options;parser;constructor(e){this.options=e||ye}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(W.notSpaceStart)?.[0],r=e.replace(W.endingNewline,"")+`
560
+ `;return s?'<pre><code class="language-'+X(s)+'">'+(i?r:X(r,!0))+`</code></pre>
561
+ `:"<pre><code>"+(i?r:X(r,!0))+`</code></pre>
562
+ `}blockquote({tokens:e}){return`<blockquote>
563
+ ${this.parser.parse(e)}</blockquote>
564
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
565
+ `}hr(e){return`<hr>
566
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`>
567
+ `+s+"</"+r+`>
568
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
569
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
570
+ `}table(e){let t="",i="";for(let r=0;r<e.header.length;r++)i+=this.tablecell(e.header[r]);t+=this.tablerow({text:i});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];i="";for(let n=0;n<o.length;n++)i+=this.tablecell(o[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
571
+ <thead>
572
+ `+t+`</thead>
573
+ `+s+`</table>
574
+ `}tablerow({text:e}){return`<tr>
575
+ ${e}</tr>
576
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
577
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${X(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),r=hs(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+X(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=hs(e);if(r===null)return X(i);e=r;let o=`<img src="${e}" alt="${X(i)}"`;return t&&(o+=` title="${X(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:X(e.text)}},wi=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Z=class Ht{options;renderer;textRenderer;constructor(t){this.options=t||ye,this.options.renderer=this.options.renderer||new wt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new wi}static parse(t,i){return new Ht(i).parse(t)}static parseInline(t,i){return new Ht(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];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)){i+=a||"";continue}}let o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=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 i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<t.length;r++){let o=t[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)){s+=a||"";continue}}let n=o;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.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 s}},Fe=class{options;block;constructor(e){this.options=e||ye}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Q.lex:Q.lexInline}provideParser(e=this.block){return e?Z.parse:Z.parseInline}},Zc=class{defaults=pi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Z;Renderer=wt;TextRenderer=wi;Lexer=Q;Tokenizer=vt;Hooks=Fe;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.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=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new wt(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],l=r[n];r[n]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new vt(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],l=r[n];r[n]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Fe;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],l=r[n];Fe.passThroughHooks.has(o)?r[n]=c=>{if(this.defaults.async&&Fe.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}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.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,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Q.lex(e,t??this.defaults)}parser(e,t){return Z.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.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 t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Q.lex:Q.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(e):e?Z.parse:Z.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Q.lex:Q.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Z.parse:Z.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
578
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+X(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},ve=new Zc;function $(e,t){return ve.parse(e,t)}$.options=$.setOptions=function(e){return ve.setOptions(e),$.defaults=ve.defaults,er($.defaults),$};$.getDefaults=pi;$.defaults=ye;$.use=function(...e){return ve.use(...e),$.defaults=ve.defaults,er($.defaults),$};$.walkTokens=function(e,t){return ve.walkTokens(e,t)};$.parseInline=ve.parseInline;$.Parser=Z;$.parser=Z.parse;$.Renderer=wt;$.TextRenderer=wi;$.Lexer=Q;$.lexer=Q.lex;$.Tokenizer=vt;$.Hooks=Fe;$.parse=$;$.options;$.setOptions;$.use;$.walkTokens;$.parseInline;Z.parse;Q.lex;const dr=new $.Renderer;dr.html=({text:e})=>Xc(e);const Jc=300,We=new Map;function Yc(e){const t=We.get(e);if(t!==void 0)return t;const i=$.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:dr}),s=ed(i);if(We.set(e,s),We.size>Jc){const r=We.keys().next().value;r!==void 0&&We.delete(r)}return s}function Xc(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function ed(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!td(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function td(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var id=Object.defineProperty,sd=Object.getOwnPropertyDescriptor,pr=(e,t,i,s)=>{for(var r=s>1?void 0:s?sd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&id(t,i,r),r};let yt=class extends M{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)},this.onFormattedCopy=e=>{e.clipboardData===null||!nd(rd(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return d`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${cc(Yc(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="Copy code block",s.setAttribute("aria-label","Copy code block");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await ad(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"Copied code block":t==="failed"?"Failed to copy code block":"Copy code block";e.title=s,e.setAttribute("aria-label",s)}};yt.styles=Cl;pr([h()],yt.prototype,"text",2);yt=pr([F("formatted-text")],yt);function rd(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&od(t)?t.getSelection():e.ownerDocument.getSelection()}function od(e){return"getSelection"in e&&typeof e.getSelection=="function"}function nd(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function ad(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var ld=Object.defineProperty,cd=Object.getOwnPropertyDescriptor,Ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?cd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ld(t,i,r),r};const ms=180;let we=class extends M{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=dd(e.args),s=pd(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:hd(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,l=e.status==="error"?e.resultText:r?.error,c=o===void 0?e.resultText:void 0;return d`
579
+ <section class=${`tool-card ${e.status}`}>
580
+ <div class="tool-header">
581
+ <div class="tool-title">
582
+ <span class="status-icon" aria-hidden="true">${fd(e.status)}</span>
583
+ <strong>${e.toolName}</strong>
584
+ ${i===void 0?d`<span class="summary">${e.summary}</span>`:d`<span class="path">${i}</span>`}
585
+ </div>
586
+ <div class="tool-meta">
587
+ ${bs(e)===void 0?null:d`<span>${bs(e)}</span>`}
588
+ ${n===void 0?null:d`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
589
+ <span class="status-label">${gd(e.status)}</span>
590
+ </div>
591
+ </div>
592
+
593
+ ${a?d`<p class="notice">Applied diff differs from the preview.</p>`:null}
594
+ ${l===void 0||l===""?null:d`<pre class="error-text">${l}</pre>`}
595
+ ${o===void 0?this.renderTextBody(c,e.status==="error"):this.renderDiffBody(o,s===void 0?"Preview diff":"Applied diff")}
596
+ ${!t&&o===void 0&&(c===void 0||c==="")?d`<p class="muted">${e.summary}</p>`:null}
597
+ </section>
598
+ `}renderTextBody(e,t){return e===void 0||e===""?null:d`
599
+ <details class="text-body" ?open=${t}>
600
+ <summary>Result</summary>
601
+ <pre>${e}</pre>
602
+ </details>
603
+ `}renderDiffBody(e,t){const i=e.split(`
604
+ `),s=!this.showFullDiff&&i.length>ms,r=s?i.slice(0,ms):i;return d`
605
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
606
+ <summary>
607
+ <span>${t}</span>
608
+ <small>${String(i.length)} ${i.length===1?"line":"lines"}</small>
609
+ </summary>
610
+ <div class="diff-toolbar">
611
+ <span>${s?`Showing ${String(r.length)} of ${String(i.length)} lines`:"Full diff"}</span>
612
+ <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
613
+ </div>
614
+ <pre class="diff" aria-label=${t}>${r.map(o=>d`<span class=${ud(o)}>${o}</span>`)}</pre>
615
+ ${s?d`
616
+ <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
617
+ Show all ${String(i.length)} diff lines
618
+ </button>
619
+ `:null}
620
+ </details>
621
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};we.styles=H`
622
+ :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
623
+ .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
624
+ .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
625
+ .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
626
+ .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
627
+ .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
628
+ .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
629
+ .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
630
+ strong { color: var(--pi-text); }
631
+ .path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
632
+ .summary { color: var(--pi-muted); font-family: inherit; }
633
+ .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
634
+ .diff-stats { display: inline-flex; gap: 3px; }
635
+ .added, .diff .added { color: var(--pi-success); }
636
+ .removed, .diff .removed { color: var(--pi-danger); }
637
+ .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
638
+ .notice { margin: 0; color: var(--pi-warning); }
639
+ .muted { margin: 0; color: var(--pi-muted); }
640
+ .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
641
+ .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
642
+ .text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
643
+ .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
644
+ .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
645
+ .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
646
+ .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
647
+ .diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
648
+ .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
649
+ button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
650
+ button:hover, button:focus { border-color: var(--pi-accent); }
651
+ .diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
652
+ .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
653
+ .diff .context { color: var(--pi-muted); }
654
+ .diff .hunk { color: var(--pi-accent); }
655
+ .diff .file { color: var(--pi-dim); }
656
+ .diff .meta { color: var(--pi-dim); }
657
+ .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
658
+ .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
659
+ .show-more { justify-self: start; }
660
+ `;Ze([h({attribute:!1})],we.prototype,"execution",2);Ze([S()],we.prototype,"showFullDiff",2);Ze([S()],we.prototype,"copied",2);Ze([S()],we.prototype,"diffOpen",2);we=Ze([F("tool-execution-view")],we);function dd(e){return Bt(e,"path")??Bt(e,"file_path")}function bs(e){if(e.toolName!=="edit")return;const t=ot(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof ot(e.args,"oldText")=="string"&&typeof ot(e.args,"newText")=="string")return"1 edit"}function pd(e){return Bt(e,"diff")}function hd(e){let t=0,i=0;for(const s of e.split(`
661
+ `))hr(s)?t++:ur(s)&&i++;return{added:t,removed:i}}function ud(e){return hr(e)?"added":ur(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function hr(e){return e.startsWith("+")&&!e.startsWith("+++")}function ur(e){return e.startsWith("-")&&!e.startsWith("---")}function fd(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function gd(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function md(e){return typeof e=="object"&&e!==null}function ot(e,t){return md(e)?e[t]:void 0}function Bt(e,t){const i=ot(e,t);return typeof i=="string"?i:void 0}var bd=Object.defineProperty,vd=Object.getOwnPropertyDescriptor,E=(e,t,i,s)=>{for(var r=s>1?void 0:s?vd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&bd(t,i,r),r};const wd=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),yd=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),_t=["You opened this chat while the assistant was already replying. The complete answer will appear shortly.","We joined mid-sentence. Holding the curtain until the full reply is ready.","The assistant started before this tab arrived. We’ll show the full answer when it lands.","Catching the reply in one piece — no spoilers, no half-answers.","The tokens are still assembling themselves. Full answer incoming.","We arrived fashionably late to this response. The complete version will appear soon."];function vs(){return _t[Math.floor(Math.random()*_t.length)]??_t[0]}function xd(e){return typeof e=="object"&&e!==null&&"offset"in e&&typeof e.offset=="number"&&("key"in e&&typeof e.key=="string"||"index"in e&&typeof e.index=="number")}function ws(e){return nt(e,0,100)}function nt(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let A=class extends M{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),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}willUpdate(e){e.has("sessionId")&&(this.openGroupKeys=this.readOpenGroupKeys()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return d`
662
+ <div class="chat-wrap">
663
+ ${this.renderConversationRail()}
664
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
665
+ ${this.renderHistoryBoundary()}
666
+ ${Vl(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupAnchorKey(t.endIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
667
+ ${this.renderQueuedMessages()}
668
+ ${this.renderSessionActivity()}
669
+ </div>
670
+ ${this.renderActivityDock()}
671
+ </div>
672
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Kl(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return d`
673
+ <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
674
+ <span class="dot"></span>
675
+ <span class="activity-text">${this.activityText(e)}</span>
676
+ </div>
677
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:d`
678
+ <aside class="queued-messages" aria-live="polite">
679
+ <div class="queued-header">
680
+ <strong>Queued messages</strong>
681
+ <small>${e.length} pending · Stop clears the queue</small>
682
+ </div>
683
+ ${e.map((t,i)=>d`
684
+ <div class="queued-message">
685
+ <span class="queued-kind">${t.kind==="steer"?"Steer":"Follow-up"} ${String(i+1)}</span>
686
+ <formatted-text .text=${t.text}></formatted-text>
687
+ </div>
688
+ `)}
689
+ </aside>
690
+ `}renderSessionActivity(){return this.isReceivingPartialStream?d`
691
+ <aside class="session-activity receiving" aria-live="polite">
692
+ <strong>Catching up…</strong>
693
+ <span>${this.currentPartialStreamNoticeBody()}</span>
694
+ </aside>
695
+ `:this.isCompacting?d`
696
+ <aside class="session-activity compacting" aria-live="polite">
697
+ <strong>Compacting history…</strong>
698
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
699
+ ${this.pendingMessageCount>0?d`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
700
+ </aside>
701
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?vs():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=vs(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;return t===void 0||e!=="idle"&&t.phase==="idle"?e:t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?ws(this.messages.length/e*100):100;return d`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=nt(this.currentConversationIndex??t,0,e-1);return ws(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?d`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?d`
702
+ <div class="history-boundary">
703
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
704
+ <span>Scroll up to load earlier messages</span>
705
+ ${e}
706
+ </div>
707
+ `:this.messages.length?d`<div class="history-boundary"><span>Beginning of session</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.messageStart+this.messages.length;return d`<small>Showing messages ${e}–${t} of ${this.messageTotal}</small>`}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return d`
708
+ ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
709
+ <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-anchor-key=${this.messageAnchorKey(t)}>
710
+ ${i?null:this.renderMessageHeader(e,String(t))}
711
+ ${e.parts.map(s=>this.renderPart(s,e))}
712
+ </article>
713
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const r=this.groupKey(i),o=s||this.openGroupKeys.has(r);return d`
714
+ ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
715
+ <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-anchor-key=${this.groupAnchorKey(i)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
716
+ <summary>
717
+ <b class="label">${s?"live events":"events"}</b>
718
+ <span>${Gl(e)}</span>
719
+ </summary>
720
+ <div class="group-body">
721
+ ${e.map((n,a)=>{const l=this.isToolExecutionOnlyMessage(n);return d`
722
+ <section class=${l?"group-msg tool-execution-shell":`group-msg ${n.role}`}>
723
+ ${l?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
724
+ ${n.parts.map(c=>this.renderPart(c,n))}
725
+ </section>
726
+ `})}
727
+ </div>
728
+ </details>
729
+ `}renderScrollMarker(e){return d`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return d`
730
+ <div class="msg-header">
731
+ <b class="label">${e.role}</b>
732
+ <div class="msg-header-trailing">
733
+ ${this.renderMessageActions(e,t)}
734
+ <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
735
+ </div>
736
+ </div>
737
+ `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return d`
738
+ <div class="msg-actions" aria-label="Message actions">
739
+ <button type="button" class="msg-action" title=${i?"Copied":"Copy message"} aria-label=${`${i?"Copied":"Copy"} ${e.role} message`} @click=${s=>{this.copyMessage(e,t,s)}}>
740
+ <span aria-hidden="true">${i?"✓":"⧉"}</span>
741
+ </button>
742
+ </div>
743
+ `}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
744
+
745
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const l={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,l),l}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(l=>l!==void 0&&l!==""),n=[r?.full,s===void 0?void 0:`Model: ${s}`].filter(l=>l!==void 0&&l!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:wd.format(t),full:yd.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?d`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?d`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?d`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?d`
746
+ <details class="part skill-invocation">
747
+ <summary><b>[skill]</b> ${e.name}</summary>
748
+ <small>${e.location}</small>
749
+ <formatted-text .text=${e.content}></formatted-text>
750
+ </details>
751
+ `:e.type==="skillRead"?d`
752
+ <div class="part skill-read">
753
+ <strong>Loaded ${e.name}</strong>
754
+ <small>read ${e.path}</small>
755
+ </div>
756
+ `:e.type==="toolCall"?d`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?d`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?d`
757
+ <details class="part" ?open=${e.isError}>
758
+ <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
759
+ <formatted-text .text=${e.text}></formatted-text>
760
+ </details>
761
+ `:null}onGroupToggle(e,t,i){const s=t.currentTarget;if(!(s instanceof HTMLDetailsElement)||i&&s.open)return;const r=new Set(this.openGroupKeys),o=r.has(e);s.open?r.add(e):r.delete(e),r.has(e)!==o&&(this.openGroupKeys=r,this.saveOpenGroupKeys())}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&rc({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?this.distanceFromBottom(e)<48:!0}isAtBottom(){const e=this.chat;return e?this.distanceFromBottom(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}distanceFromBottom(e){return e.scrollHeight-e.scrollTop-e.clientHeight}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){requestAnimationFrame(()=>{const e=this.chat,t=this.readStoredScrollPosition();if(!e||!t){this.withSuppressedScrollSave(()=>{e&&(e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop)});return}const i=this.articleAt(t);if(!i){this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop});return}this.withSuppressedScrollSave(()=>{const s=e.getBoundingClientRect().top,r=i.getBoundingClientRect().top-s;e.scrollTop+=r-t.offset,this.lastScrollTop=e.scrollTop})})}capturePrependScrollAnchor(){const e=this.chat;if(e)return Zl(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=0;const i=()=>{const s=this.chat;if(s){if(Jl(s,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=s.scrollTop,t+=1,t<Ql){requestAnimationFrame(i);return}requestAnimationFrame(()=>{this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1})}};i()}saveScrollPosition(e=this.sessionId){const t=this.chat;if(!(!t||!e))try{if(this.isNearBottom()){localStorage.removeItem(this.storageKey(e));return}const i=this.firstVisibleArticle();if(!i){localStorage.removeItem(this.storageKey(e));return}const s=t.getBoundingClientRect().top,r={key:i.dataset.anchorKey,index:Number(i.dataset.index??0),offset:i.getBoundingClientRect().top-s};localStorage.setItem(this.storageKey(e),JSON.stringify(r))}catch{}}scheduleScrollPositionSave(){window.clearTimeout(this.saveScrollTimer),this.saveScrollTimer=window.setTimeout(()=>{this.saveScrollPosition()},180)}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=nt(i,0,Math.max(0,e-1));return}this.currentConversationIndex=nt(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}readStoredScrollPosition(){if(this.sessionId!=="")try{const e=localStorage.getItem(this.storageKey());if(e===null||e==="")return;const t=JSON.parse(e);return xd(t)?t:void 0}catch{return}}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(!e)return;const t=i=>{const s=e.getBoundingClientRect();return Array.from(this.renderRoot.querySelectorAll(i)).find(r=>{const o=r.getBoundingClientRect();return o.bottom>=s.top&&o.top<=s.bottom})};return t("article.msg")??t("article.msg, details.msg")}articleAt(e){const t=this.articles(),i=e.key===void 0?void 0:t.find(s=>s.dataset.anchorKey===e.key);return i!==void 0?i:t.find(s=>Number(s.dataset.index)===e.index)}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}withSuppressedLoadMoreRequests(e){this.suppressLoadMoreRequests=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressLoadMoreRequests=!1})})}storageKey(e=this.sessionId){return`pi-web:chat-scroll:${e}`}groupStorageKey(e=this.sessionId){return`pi-web:chat-groups:${e}`}groupKey(e){return`${this.sessionId}:${String(e)}`}messageAnchorKey(e){return`m:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}readOpenGroupKeys(){if(this.sessionId==="")return new Set;try{const e=localStorage.getItem(this.groupStorageKey()),t=e!==null&&e!==""?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(i=>typeof i=="string"):[])}catch{return new Set}}saveOpenGroupKeys(){if(this.sessionId!=="")try{localStorage.setItem(this.groupStorageKey(),JSON.stringify([...this.openGroupKeys]))}catch{}}};A.styles=Tl;E([h({attribute:!1})],A.prototype,"messages",2);E([h()],A.prototype,"sessionId",2);E([h({type:Number})],A.prototype,"messageStart",2);E([h({type:Number})],A.prototype,"messageTotal",2);E([h({type:Boolean})],A.prototype,"hasMore",2);E([h({type:Boolean})],A.prototype,"loadingMore",2);E([h({type:Boolean})],A.prototype,"isReceivingPartialStream",2);E([h({type:Boolean})],A.prototype,"isCompacting",2);E([h({type:Number})],A.prototype,"pendingMessageCount",2);E([h({attribute:!1})],A.prototype,"status",2);E([h({attribute:!1})],A.prototype,"activity",2);E([h({attribute:!1})],A.prototype,"onLoadMore",2);E([oe(".chat")],A.prototype,"chat",2);E([S()],A.prototype,"pinnedToBottom",2);E([S()],A.prototype,"openGroupKeys",2);E([S()],A.prototype,"expandedMetaKey",2);E([S()],A.prototype,"copiedMessageKey",2);E([S()],A.prototype,"currentConversationIndex",2);E([S()],A.prototype,"loadMoreRequested",2);A=E([F("chat-view")],A);class Sd extends ci{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===ai.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const yi=li(Sd);var kd=Object.defineProperty,$d=Object.getOwnPropertyDescriptor,Tt=(e,t,i,s)=>{for(var r=s>1?void 0:s?$d(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kd(t,i,r),r};let Ce=class extends M{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?d`
762
+ <div class="menu">
763
+ ${this.items.map((e,t)=>d`
764
+ <button class=${t===this.selectedIndex?"selected":""} ${yi(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
765
+ <strong>${e.insertText}</strong>
766
+ <span>${e.detail}</span>
767
+ ${e.description!==void 0&&e.description!==""?d`<small>${e.description}</small>`:null}
768
+ </button>
769
+ `)}
770
+ </div>
771
+ `:null}};Ce.styles=Il;Tt([h({attribute:!1})],Ce.prototype,"items",2);Tt([h({type:Number})],Ce.prototype,"selectedIndex",2);Tt([h({attribute:!1})],Ce.prototype,"onPick",2);Ce=Tt([F("autocomplete-menu")],Ce);var Pd=Object.defineProperty,Td=Object.getOwnPropertyDescriptor,z=(e,t,i,s)=>{for(var r=s>1?void 0:s?Td(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Pd(t,i,r),r};let D=class extends M{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 Si,this.readOnlyCompartment=new Si}willUpdate(e){if(!e.has("sessionId"))return;const t=e.get("sessionId");t!==void 0&&t!==""&&Nt(t,this.draft),this.draft=this.sessionId!==void 0&&this.sessionId!==""?_s(this.sessionId):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=js(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return d`
772
+ <footer class=${t?"shell-mode":""}>
773
+ <div class="editor-wrap">
774
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
775
+ ${t?d`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
776
+ ${this.isCompacting&&!t?d`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
777
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
778
+ </div>
779
+ <div class="actions">
780
+ ${this.renderCompactStatus()}
781
+ <button ?disabled=${this.disabled} title=${i?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${i?"Queue":"Send"}</button>
782
+ ${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}
783
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</button>
784
+ </div>
785
+ </footer>
786
+ `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"no model",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return d`
787
+ <div class="compact-status" aria-label="Session status">
788
+ <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
789
+ <button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${e.thinkingLevel??"off"}</button>
790
+ </div>
791
+ `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new _e({parent:this.editorHost,state:It.create({doc:this.draft,extensions:[mr(),Tr(),br(),vr.of(" "),wr(Pr,{fallback:!0}),_e.lineWrapping,yr("Message pi... Use / for commands, @ for files"),this.editableCompartment.of(_e.editable.of(!this.disabled)),this.readOnlyCompartment.of(It.readOnly.of(this.disabled)),_e.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),xr.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:e=>Cr(e)||$r(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>ki.shift?.(e)??!1},{key:"Backspace",run:e=>Ar(e)},...Sr,...kr])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:$i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(_e.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(It.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e,this.sessionId!==void 0&&this.sessionId!==""&&Nt(this.sessionId,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const i=await O.commands(this.sessionId).catch(Ad);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await O.files(this.cwd,e.query,e.fileKind,e.fileMode).catch(Id);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Cd(s.path,e.fileMode==="path",e.quoted===!0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
792
+ `))+1,r=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:r,from:s,to:e,fileMode:"path"};if(r.startsWith("/")&&s===0)return{kind:"command",query:r.slice(1),from:s,to:e};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:s,to:e}}currentQuotedTrigger(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:i,to:t,fileMode:"path",quoted:!0}}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):ki.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:$i.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();t===""||this.disabled||(this.draft="",this.sessionId!==void 0&&this.sessionId!==""&&ii(this.sessionId),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0))}};D.styles=Rl;z([h({type:Boolean})],D.prototype,"disabled",2);z([h()],D.prototype,"sessionId",2);z([h()],D.prototype,"cwd",2);z([h({type:Boolean})],D.prototype,"canSteer",2);z([h({type:Boolean})],D.prototype,"isCompacting",2);z([h({type:Boolean})],D.prototype,"canStop",2);z([h({attribute:!1})],D.prototype,"status",2);z([h({attribute:!1})],D.prototype,"onSend",2);z([h({attribute:!1})],D.prototype,"onStop",2);z([h({attribute:!1})],D.prototype,"onSelectModel",2);z([h({attribute:!1})],D.prototype,"onSelectThinking",2);z([oe(".markdown-editor")],D.prototype,"editorHost",2);z([S()],D.prototype,"draft",2);z([S()],D.prototype,"completions",2);z([S()],D.prototype,"selectedIndex",2);D=z([F("prompt-editor")],D);function Cd(e,t,i){const s=t?"":"@";return!i&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Ad(){return[]}function Id(){return[]}function it(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function Md(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Rd=Object.defineProperty,Ed=Object.getOwnPropertyDescriptor,Ct=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ed(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Rd(t,i,r),r};let Ae=class extends M{constructor(){super(...arguments),this.workspaceLabelItems=[]}render(){const e=this.status;if(e===void 0)return d`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${it(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${it(t.contextWindow)}`:"context unknown",s=e.tokens;return d`
793
+ <div class="bar">
794
+ <span>${Js(this.workspace?.label??"workspace",this.workspaceLabelItems,this.workspace?.path)}</span>
795
+ <span>↑${it(s.input)}</span>
796
+ <span>↓${it(s.output)}</span>
797
+ <span>${i}</span>
798
+ <span>${Md(e.cost)}</span>
799
+ ${e.pendingMessageCount>0?d`<span>${String(e.pendingMessageCount)} queued</span>`:null}
800
+ </div>
801
+ `}};Ae.styles=Al;Ct([h({attribute:!1})],Ae.prototype,"status",2);Ct([h({attribute:!1})],Ae.prototype,"workspace",2);Ct([h({attribute:!1})],Ae.prototype,"workspaceLabelItems",2);Ae=Ct([F("status-bar")],Ae);var _d=Object.defineProperty,Dd=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&_d(t,i,r),r};let J=class extends M{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return d`
802
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
803
+ <section @mousedown=${t=>{t.stopPropagation()}}>
804
+ <header>
805
+ <strong>${this.title}</strong>
806
+ <button @click=${()=>this.onCancel?.()}>×</button>
807
+ </header>
808
+ ${this.searchable?d`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
809
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
810
+ ${e.map((t,i)=>d`
811
+ <button class=${i===this.selectedIndex?"selected":""} ${yi(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
812
+ <span>${t.label}</span>
813
+ ${t.description!==void 0&&t.description!==""?d`<small>${t.description}</small>`:null}
814
+ </button>
815
+ `)}
816
+ ${e.length===0?d`<div class="empty">No matching options</div>`:null}
817
+ </div>
818
+ </section>
819
+ </div>
820
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};J.styles=Zs;ne([h()],J.prototype,"title",2);ne([h({type:Boolean})],J.prototype,"searchable",2);ne([h({attribute:!1})],J.prototype,"options",2);ne([h({attribute:!1})],J.prototype,"selectedValue",2);ne([h({attribute:!1})],J.prototype,"onPick",2);ne([h({attribute:!1})],J.prototype,"onCancel",2);ne([S()],J.prototype,"selectedIndex",2);ne([S()],J.prototype,"query",2);J=ne([F("command-picker")],J);var Ld=Object.defineProperty,Od=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Od(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ld(t,i,r),r};let re=class extends M{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return d`
821
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
822
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
823
+ <header>
824
+ <input
825
+ .value=${this.queryText}
826
+ placeholder="Search actions..."
827
+ @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
828
+ >
829
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
830
+ </header>
831
+ <div class="options">
832
+ ${e.length===0?d`<div class="empty">No actions found.</div>`:e.map((t,i)=>d`
833
+ <button class=${i===this.selectedIndex?"selected":""} ${yi(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
834
+ <span class="main">
835
+ <strong>${t.title}</strong>
836
+ ${t.description!==void 0&&t.description!==""?d`<small>${t.description}</small>`:null}
837
+ </span>
838
+ ${t.shortcut!==void 0?d`<kbd>${Oa(t.shortcut)}</kbd>`:null}
839
+ ${t.group!==void 0&&t.group!==""?d`<small class="group">${t.group}</small>`:null}
840
+ </button>
841
+ `)}
842
+ </div>
843
+ </section>
844
+ </div>
845
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e.id)}};re.styles=Ml;xe([h({attribute:!1})],re.prototype,"actions",2);xe([h({attribute:!1})],re.prototype,"onRun",2);xe([h({attribute:!1})],re.prototype,"onCancel",2);xe([oe("input")],re.prototype,"input",2);xe([S()],re.prototype,"queryText",2);xe([S()],re.prototype,"selectedIndex",2);re=xe([F("action-palette")],re);var Nd=Object.defineProperty,jd=Object.getOwnPropertyDescriptor,G=(e,t,i,s)=>{for(var r=s>1?void 0:s?jd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Nd(t,i,r),r};let q=class extends M{render(){const e=this.state;return e===void 0?null:d`
846
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
847
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
848
+ <header>
849
+ <strong>${this.dialogTitle(e)}</strong>
850
+ <button title="Close" @click=${()=>{this.cancel()}}>×</button>
851
+ </header>
852
+ ${this.renderBody(e)}
853
+ </section>
854
+ </div>
855
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"Configure provider authentication";case"providers":return e.authType===void 0?"Select provider authentication":e.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${e.provider.name}`;case"oauth":return`Login to ${e.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(e){switch(e.step){case"method":return d`
856
+ <div class="options">
857
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
858
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
859
+ </div>
860
+ `;case"providers":return d`<div class="options">${e.providers.length===0?d`<div class="empty">No providers available.</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return d`
861
+ <div class="form">
862
+ <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
863
+ <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
864
+ ${e.error!==void 0&&e.error!==""?d`<div class="error-text">${e.error}</div>`:null}
865
+ <div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"Saving…":"Save API key"}</button></div>
866
+ </div>
867
+ `;case"oauth":return this.renderOAuth(e);case"logout":return d`<div class="options">${e.providers.length===0?d`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>d`
868
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${ys(t.authType)}</small></button>
869
+ `)}</div>`}}renderProviderButton(e){return d`
870
+ <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
871
+ <span>${e.name}${e.status.source!==void 0?d` <em>${Fd(e)}</em>`:null}</span>
872
+ <small>${e.id} · ${ys(e.authType)}</small>
873
+ </button>
874
+ `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return d`
875
+ <div class="form">
876
+ ${t.auth!==void 0?d`
877
+ <p>Open this authorization link:</p>
878
+ <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
879
+ ${t.auth.instructions!==void 0?d`<p class="warning">${t.auth.instructions}</p>`:null}
880
+ `:d`<p>Starting login flow…</p>`}
881
+ ${t.progress.length>0?d`<ul class="progress">${t.progress.map(r=>d`<li>${r}</li>`)}</ul>`:null}
882
+ ${i!==void 0?d`
883
+ <label>${i.message}</label>
884
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
885
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
886
+ `:null}
887
+ ${s!==void 0?d`
888
+ <p>${s.message}</p>
889
+ <div class="inline-options">${s.options.map(r=>d`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
890
+ `:null}
891
+ ${e.error!==void 0&&e.error!==""?d`<div class="error-text">${e.error}</div>`:null}
892
+ ${t.status==="error"||t.status==="cancelled"?d`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
893
+ ${i===void 0&&s===void 0&&t.status==="running"?d`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
894
+ </div>
895
+ `}focusInputIfNeeded(){const e=Wd(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};q.styles=[Zs,H`
896
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
897
+ .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
898
+ .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
899
+ .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
900
+ label { color: var(--pi-muted); }
901
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
902
+ .actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
903
+ .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
904
+ .actions button:disabled { opacity: .6; cursor: wait; }
905
+ .warning { color: var(--pi-warning); }
906
+ .error-text { color: var(--pi-danger); }
907
+ .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
908
+ .inline-options { display: grid; gap: 8px; }
909
+ em { color: var(--pi-success); font-style: normal; font-size: 12px; }
910
+ `];G([h({attribute:!1})],q.prototype,"state",2);G([h({attribute:!1})],q.prototype,"onChooseMethod",2);G([h({attribute:!1})],q.prototype,"onSelectProvider",2);G([h({attribute:!1})],q.prototype,"onApiKeyInput",2);G([h({attribute:!1})],q.prototype,"onSaveApiKey",2);G([h({attribute:!1})],q.prototype,"onLogoutProvider",2);G([h({attribute:!1})],q.prototype,"onOAuthInput",2);G([h({attribute:!1})],q.prototype,"onOAuthRespond",2);G([h({attribute:!1})],q.prototype,"onOAuthCancel",2);G([h({attribute:!1})],q.prototype,"onCancel",2);G([oe("input")],q.prototype,"input",2);q=G([F("auth-dialog")],q);function ys(e){return e==="oauth"?"subscription":"API key"}function Wd(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Fd(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${e.status.label===void 0?"":`: ${e.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 zd=Object.defineProperty,qd=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?qd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zd(t,i,r),r};let Y=class extends M{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 e=++this.requestId;this.loading=!0;try{const t=await O.projectDirectories(this.path);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return d`
911
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
912
+ <section @click=${e=>{e.stopPropagation()}}>
913
+ <header>
914
+ <strong>Add project</strong>
915
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
916
+ </header>
917
+ <div class="body">
918
+ <label>
919
+ Project folder
920
+ <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
921
+ </label>
922
+ <div class="suggestions">
923
+ ${this.loading?d`<div class="hint">Loading folders…</div>`:null}
924
+ ${this.suggestions.map((e,t)=>d`
925
+ <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
926
+ ${e.path}
927
+ </button>
928
+ `)}
929
+ ${!this.loading&&this.suggestions.length===0?d`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
930
+ </div>
931
+ <label class="check">
932
+ <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
933
+ Create the folder if it does not exist
934
+ </label>
935
+ </div>
936
+ <footer>
937
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
938
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
939
+ </footer>
940
+ </section>
941
+ </div>
942
+ `}};Y.styles=H`
943
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
944
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
945
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
946
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
947
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
948
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
949
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
950
+ input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
951
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
952
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
953
+ .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
954
+ .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
955
+ .hint { padding: 12px; color: var(--pi-muted); }
956
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
957
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
958
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
959
+ button:disabled { opacity: .5; cursor: not-allowed; }
960
+ `;ae([h({attribute:!1})],Y.prototype,"onSubmit",2);ae([h({attribute:!1})],Y.prototype,"onCancel",2);ae([S()],Y.prototype,"path",2);ae([S()],Y.prototype,"createMissing",2);ae([S()],Y.prototype,"suggestions",2);ae([S()],Y.prototype,"selected",2);ae([S()],Y.prototype,"loading",2);ae([oe("input")],Y.prototype,"pathInput",2);Y=ae([F("project-dialog")],Y);var Hd=Object.defineProperty,Bd=Object.getOwnPropertyDescriptor,T=(e,t,i,s)=>{for(var r=s>1?void 0:s?Bd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Hd(t,i,r),r};let P=class extends M{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,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){const e=this.workspace;if(e===void 0)return d`<section class="empty">Select a workspace.</section>`;const t=this.panels,i=t.find(r=>r.id===this.tool)??t[0],s=this.createPanelContext(e);return d`
961
+ <header>
962
+ <div class=${this.workspaceHeaderFrameClass()}>
963
+ <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
964
+ ${this.hideToolTabs?null:d`
965
+ <div class="tabs">
966
+ ${t.map(r=>d`
967
+ <button class=${i?.id===r.id?"selected":""} @click=${()=>{this.onSelectTool(r.id)}}>${this.renderPanelTitle(r,s)}</button>
968
+ `)}
969
+ </div>
970
+ `}
971
+ <small>${Js(e.label,this.workspaceLabelItems,e.path)}</small>
972
+ </div>
973
+ </div>
974
+ </header>
975
+ ${i===void 0?d`<section class="empty">No workspace panels registered.</section>`:d`
976
+ <div class="panel-content">
977
+ ${i.render(s)}
978
+ </div>
979
+ `}
980
+ `}renderPanelTitle(e,t){const i=e.badge?.(t);return i===void 0||i===""?d`${e.title}`:d`${e.title} <span class="tab-badge">${i}</span>`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStrip;this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStrip,t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}createPanelContext(e){return{workspace:e,state:this.appState,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}}};P.styles=Pl;T([h({attribute:!1})],P.prototype,"workspace",2);T([h({attribute:!1})],P.prototype,"appState",2);T([h()],P.prototype,"tool",2);T([h({attribute:!1})],P.prototype,"panels",2);T([h({attribute:!1})],P.prototype,"workspaceLabelItems",2);T([h({type:Boolean})],P.prototype,"hideToolTabs",2);T([h({attribute:!1})],P.prototype,"fileTree",2);T([h({attribute:!1})],P.prototype,"expandedDirs",2);T([h({attribute:!1})],P.prototype,"selectedFilePath",2);T([h({attribute:!1})],P.prototype,"selectedFileContent",2);T([h({type:Boolean})],P.prototype,"fileTreeStale",2);T([h({attribute:!1})],P.prototype,"gitStatus",2);T([h({attribute:!1})],P.prototype,"selectedDiffPath",2);T([h({attribute:!1})],P.prototype,"selectedDiff",2);T([h({attribute:!1})],P.prototype,"selectedStagedDiff",2);T([h({type:Boolean})],P.prototype,"gitStale",2);T([h({attribute:!1})],P.prototype,"onSelectTool",2);T([h({attribute:!1})],P.prototype,"onRefreshFiles",2);T([h({attribute:!1})],P.prototype,"onExpandDir",2);T([h({attribute:!1})],P.prototype,"onSelectFile",2);T([h({attribute:!1})],P.prototype,"onRefreshGit",2);T([h({attribute:!1})],P.prototype,"onSelectDiff",2);T([h({type:Number})],P.prototype,"activeTerminalCount",2);T([h({type:Boolean})],P.prototype,"terminalAutoStart",2);T([oe(".workspace-header-strip")],P.prototype,"workspaceHeaderStrip",2);T([S()],P.prototype,"workspaceHeaderCanScrollLeft",2);T([S()],P.prototype,"workspaceHeaderCanScrollRight",2);P=T([F("workspace-panel")],P);var Ud=Object.defineProperty,Vd=Object.getOwnPropertyDescriptor,se=(e,t,i,s)=>{for(var r=s>1?void 0:s?Vd(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ud(t,i,r),r};const Kd=900*1e3;let K=class extends M{constructor(){super(...arguments),this.state=en(),this.sessions=new Ca(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.auth=new tn(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new _a(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions),this.projects=new dn(()=>this.state,e=>{this.setState(e)},this.workspaces),this.files=new nn(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new cn(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new La,this.realtime=new va,this.activeTerminalIds=new Set,this.mobileNavigationMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(max-width: 760px)"):void 0,this.plugins=Gd(),this.preferredThemeId=qa()??Rt,this.activeThemeId=Rt,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.mobileTabsCanScrollLeft=!1,this.mobileTabsCanScrollRight=!1,this.onPopState=()=>{this.withChatScrollTransition(()=>this.restoreRoute(!1))},this.onFocus=()=>{this.sessions.refreshSelectedSession(),this.refreshPiWebStatus()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.sessions.refreshSelectedSession(),this.refreshPiWebStatus())},this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout=e.matches,this.updateMobileTabsScrollState()},this.onMobileTabsScroll=()=>{this.updateMobileTabsScrollState()},this.onKeyDown=e=>{this.keyboard.handle(e,this.getActions())&&(e.preventDefault(),e.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.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},Kd),this.refreshPiWebStatus(),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(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateMobileTabsScrollState()}updated(){this.observeMobileTabs(),this.updateMobileTabsScrollState()}setState(e){if(!Qd(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state)}async loadProjectsAndRestoreRoute(){await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRoute(!1))}async refreshPiWebStatus(){try{this.setState({piWebStatus:await Rs.piWebStatus()})}catch(e){console.warn("Failed to refresh Pi Web status",e)}}async restoreRoute(e){const t=vl(),i=qi(ct("core:workspace.files"),"file"),s=qi(ct("core:workspace.git"),"diff");if(this.setState({workspaceTool:t.tool??this.state.workspaceTool,mainView:t.view??this.defaultRouteView(),selectedFilePath:i,selectedDiffPath:s}),t.projectId===void 0||t.projectId==="")return;const r=this.state.projects.find(o=>o.id===t.projectId);r&&(await this.workspaces.selectProject(r,{workspaceId:t.workspaceId,sessionId:t.sessionId,updateUrl:e}),this.setState({selectedFilePath:i,selectedDiffPath:s}),t.tool==="core:workspace.files"&&await this.files.refreshFiles(),t.tool==="core:workspace.files"&&i!==void 0&&await this.files.restoreFile(i),t.tool==="core:workspace.git"&&await this.git.refreshGit(),this.git.updatePolling())}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await Jd(),this.chatView?.restoreScrollPosition(),this.promptEditor?.focusInput()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}updateUrl(e){wl({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},e)}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}handleWorkspaceChange(e,t){e.selectedWorkspace?.id!==t.selectedWorkspace?.id&&(this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear(),this.setState({activeTerminalCount:0}),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling()))}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e)})}handleRealtimeEvent(e){Zd(e)?this.applyTerminalEvent(e):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){try{const t=await Es.terminals(e.projectId,e.id);if(this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const i of t)i.exited||this.activeTerminalIds.add(i.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(t){this.setState({error:String(t)})}}handleActivityTransition(e,t){const i=xs(e.status),s=xs(t.status);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(this.state,this.state.selectedWorkspace);return d`<workspace-panel .workspace=${this.state.selectedWorkspace} .appState=${this.state} .tool=${this.state.workspaceTool} .panels=${this.visibleWorkspacePanels()} .workspaceLabelItems=${e} .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=${t=>{this.openWorkspaceTool(t)}} .onRefreshFiles=${()=>this.files.refreshFiles()} .onExpandDir=${t=>this.files.expandDir(t)} .onSelectFile=${t=>this.files.selectFile(t)} .onRefreshGit=${()=>this.git.refreshGit()} .onSelectDiff=${t=>this.git.selectDiff(t)}></workspace-panel>`}renderNavigationPanel(e){const t=i=>this.withChatScrollTransition(async()=>{await i(),e&&this.setState({mainView:"chat"}),e&&this.updateUrl()});return d`
981
+ <header>
982
+ <strong>Pi Web</strong>
983
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.setState({actionPaletteOpen:!0})}}>Actions</button>
984
+ </header>
985
+ <project-list
986
+ .projects=${this.state.projects}
987
+ .selected=${this.state.selectedProject}
988
+ .collapsible=${this.isMobileNavigationLayout}
989
+ .collapsed=${this.isNavigationSectionCollapsed("projects")}
990
+ .onToggleCollapsed=${()=>{this.toggleNavigationSection("projects")}}
991
+ .onSelect=${i=>this.withChatScrollTransition(async()=>{this.expandNavigationSection("workspaces"),await this.workspaces.selectProject(i)})}
992
+ .onClose=${i=>this.projects.closeProject(i.id)}
993
+ ></project-list>
994
+ <workspace-list
995
+ .workspaces=${this.state.workspaces}
996
+ .selected=${this.state.selectedWorkspace}
997
+ .collapsible=${this.isMobileNavigationLayout}
998
+ .collapsed=${this.isNavigationSectionCollapsed("workspaces")}
999
+ .workspaceLabelItems=${i=>this.plugins.getWorkspaceLabelItems(this.state,i)}
1000
+ .onToggleCollapsed=${()=>{this.toggleNavigationSection("workspaces")}}
1001
+ .onSelect=${i=>this.withChatScrollTransition(async()=>{this.expandNavigationSection("sessions"),await this.workspaces.selectWorkspace(i)})}
1002
+ ></workspace-list>
1003
+ <session-list
1004
+ .sessions=${this.state.sessions}
1005
+ .statuses=${this.state.sessionStatuses}
1006
+ .activities=${this.state.sessionActivities}
1007
+ .selected=${this.state.selectedSession}
1008
+ .canStart=${!!this.state.selectedWorkspace}
1009
+ .collapsible=${this.isMobileNavigationLayout}
1010
+ .collapsed=${this.isNavigationSectionCollapsed("sessions")}
1011
+ .onToggleCollapsed=${()=>{this.toggleNavigationSection("sessions")}}
1012
+ .onStart=${()=>t(()=>this.sessions.startSession())}
1013
+ .onSelect=${i=>t(()=>this.sessions.selectSession(i))}
1014
+ .onArchive=${i=>this.sessions.archiveSession(i)}
1015
+ .onRestore=${i=>t(()=>this.sessions.restoreSession(i))}
1016
+ .onDelete=${i=>this.sessions.deleteCachedNewSession(i)}
1017
+ .onDetachParent=${i=>this.sessions.detachParent(i)}
1018
+ ></session-list>
1019
+ `}expandedNavigationSection(){if(this.expandedMobileNavigationSection!=="none")return this.expandedMobileNavigationSection??this.defaultNavigationSection()}defaultNavigationSection(){return this.state.selectedProject===void 0?"projects":this.state.selectedWorkspace===void 0?"workspaces":"sessions"}isNavigationSectionCollapsed(e){return this.isMobileNavigationLayout&&this.expandedNavigationSection()!==e}toggleNavigationSection(e){this.isMobileNavigationLayout&&(this.expandedMobileNavigationSection=this.expandedNavigationSection()===e?"none":e)}expandNavigationSection(e){this.isMobileNavigationLayout&&(this.expandedMobileNavigationSection=e)}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;return e===void 0?[]:this.plugins.getWorkspacePanels().filter(t=>t.visible?.({workspace:e,state:this.state})??!0)}renderMobilePanelTitle(e){const t=this.state.selectedWorkspace;if(t===void 0)return e.title;const i=e.badge?.(this.createWorkspacePanelContext(t));return i===void 0||i===""?e.title:d`${e.title} <span class="tab-badge">${i}</span>`}createWorkspacePanelContext(e){return{workspace:e,state:this.state,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===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:t=>{this.files.expandDir(t)},onSelectFile:t=>{this.files.selectFile(t)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:t=>{this.git.selectDiff(t)}}}getActions(){return this.plugins.getActions(this.createPluginRuntimeContext())}async loadExternalPlugins(){try{for(const e of await dl())this.plugins.register(e);this.applyPreferredTheme(!1),this.requestUpdate()}catch(e){console.warn("Failed to load external Pi Web plugins",e)}}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(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),stopActiveWork:()=>this.sessions.stopActiveWork()}}runAction(e){const t=this.getActions().find(i=>i.id===e&&i.enabled!==!1);t!==void 0&&t.run()}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ current":""}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes();this.setState({themeDialog:{title:"Select Theme",selectedValue:this.activeThemeId,options:e.map(t=>({value:t.id,label:`${t.name}${t.id===this.activeThemeId?" ✓ current":""}`,description:t.description===void 0?t.colorScheme:`${t.colorScheme} · ${t.description}`}))}})}pickTheme(e){const t=this.plugins.getThemes().find(i=>i.id===e);this.setState({themeDialog:void 0}),t!==void 0&&(this.preferredThemeId=t.id,this.activeThemeId=t.id,ts(t))}applyPreferredTheme(e){const t=this.plugins.getThemes(),i=t.find(s=>s.id===this.preferredThemeId)??t.find(s=>s.id===Rt)??t[0];i!==void 0&&(this.activeThemeId=i.id,ts(i,{persist:e}))}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:t,options:e.map(i=>({value:i,label:`${i}${i===t?" ✓ current":""}`,description:Xd(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),Yd(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}mobileTabsFrameClass(){return`mobile-tabs-frame${this.mobileTabsCanScrollLeft?" can-scroll-left":""}${this.mobileTabsCanScrollRight?" can-scroll-right":""}`}observeMobileTabs(){const e=this.mobileTabs;this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateMobileTabsScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateMobileTabsScrollState(){const e=this.mobileTabs,t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.mobileTabsCanScrollLeft!==i&&(this.mobileTabsCanScrollLeft=i),this.mobileTabsCanScrollRight!==s&&(this.mobileTabsCanScrollRight=s)}render(){const e=this.state;return d`
1020
+ <div class=${`shell ${e.mainView==="navigation"?"navigation-view":e.mainView==="chat"?"chat-view":"workspace-view"}`}>
1021
+ <aside>${this.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
1022
+ <main class=${e.mainView==="chat"?"chat-view":e.mainView==="navigation"?"navigation-view":"workspace-view"}>
1023
+ <div class=${this.mobileTabsFrameClass()}>
1024
+ <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1025
+ <button class=${e.mainView==="navigation"?"mobile-navigation-tab selected":"mobile-navigation-tab"} @click=${()=>{this.selectMainView("navigation")}}>Sessions</button>
1026
+ <button class=${e.mainView==="chat"?"selected":""} @click=${()=>{this.selectMainView("chat")}}>Chat</button>
1027
+ ${this.visibleWorkspacePanels().map(t=>d`
1028
+ <button class=${e.mainView===t.id?"selected":""} @click=${()=>{this.openWorkspaceTool(t.id)}}>${this.renderMobilePanelTitle(t)}</button>
1029
+ `)}
1030
+ </div>
1031
+ </div>
1032
+ ${e.error?d`<div class="error">${e.error}</div>`:null}
1033
+ <div class="mobile-navigation-panel">${this.isMobileNavigationLayout?this.renderNavigationPanel(!0):null}</div>
1034
+ ${e.selectedSession?d`
1035
+ <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
1036
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .onSend=${(t,i)=>{this.sendPrompt(t,i)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
1037
+ <status-bar .status=${e.status} .workspace=${e.selectedWorkspace} .workspaceLabelItems=${e.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(e,e.selectedWorkspace)}></status-bar>
1038
+ ${e.commandDialog!==void 0?d`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
1039
+ ${e.modelDialog!==void 0?d`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
1040
+ ${e.thinkingDialog!==void 0?d`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
1041
+ ${e.authDialog!==void 0?d`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
1042
+ `:d`<div class="empty">Select or start a session.</div>`}
1043
+ </main>
1044
+ ${this.renderWorkspacePanel()}
1045
+ ${e.actionPaletteOpen?d`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
1046
+ ${e.projectDialogOpen?d`<project-dialog .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
1047
+ ${e.themeDialog!==void 0?d`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
1048
+ </div>
1049
+ `}};K.styles=$l;se([S()],K.prototype,"state",2);se([oe("chat-view")],K.prototype,"chatView",2);se([oe("prompt-editor")],K.prototype,"promptEditor",2);se([oe(".mobile-tabs")],K.prototype,"mobileTabs",2);se([S()],K.prototype,"activeThemeId",2);se([S()],K.prototype,"isMobileNavigationLayout",2);se([S()],K.prototype,"expandedMobileNavigationSection",2);se([S()],K.prototype,"mobileTabsCanScrollLeft",2);se([S()],K.prototype,"mobileTabsCanScrollRight",2);K=se([F("pi-web-app")],K);function Gd(){const e=new bl;return e.register({id:"core",plugin:ol}),e.register({id:"themes",plugin:cl}),e}function Qd(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function xs(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0}function Zd(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Jd(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Yd(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function Xd(e){switch(e){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{H as a,d as b,Es as c,cp as d,oe as e,M as i,h as n,S as r,F as t};