@jmfederico/pi-web 1.202606.4 → 1.202606.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +27 -8
  2. package/dist/cli.js +6 -4
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/assets/{CodeViewer-CIG4PxA9.js → CodeViewer-Bv8l_MFi.js} +1 -1
  5. package/dist/client/assets/{TerminalPanel-CKtvS-3H.js → TerminalPanel-BZKsaE9s.js} +12 -8
  6. package/dist/client/assets/{index-DDid7ddU.js → index-C9oPLpm7.js} +218 -188
  7. package/dist/client/assets/{vendor-editor-core-B4Sq6exx.js → vendor-editor-core-Bc1A7SO7.js} +4 -4
  8. package/dist/client/assets/{vendor-editor-languages-DznYbTkJ.js → vendor-editor-languages-D0CnB2js.js} +3 -3
  9. package/dist/client/index.html +3 -3
  10. package/dist/config.js +40 -0
  11. package/dist/config.js.map +1 -1
  12. package/dist/server/app.js +14 -10
  13. package/dist/server/app.js.map +1 -1
  14. package/dist/server/configRoutes.js +35 -0
  15. package/dist/server/configRoutes.js.map +1 -1
  16. package/dist/server/sessiond.js +4 -3
  17. package/dist/server/sessiond.js.map +1 -1
  18. package/dist/server/sessions/authProviderOptions.js +1 -5
  19. package/dist/server/sessions/authProviderOptions.js.map +1 -1
  20. package/dist/server/sessions/piSessionManagerGateway.js +2 -2
  21. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
  22. package/dist/server/sessions/piSessionService.js +191 -4
  23. package/dist/server/sessions/piSessionService.js.map +1 -1
  24. package/dist/server/sessions/sessionNameGenerator.js +39 -2
  25. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  26. package/dist/server/sessions/spawnSubsessionTool.js +166 -0
  27. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -0
  28. package/dist/server/sessions/subsessionTranscript.js +235 -0
  29. package/dist/server/sessions/subsessionTranscript.js.map +1 -0
  30. package/dist/server/workspaceExplorerRoutes.js +19 -4
  31. package/dist/server/workspaceExplorerRoutes.js.map +1 -1
  32. package/dist/server/workspaces/effectivePathAccess.js +27 -0
  33. package/dist/server/workspaces/effectivePathAccess.js.map +1 -0
  34. package/dist/server/workspaces/fileContentService.js +6 -6
  35. package/dist/server/workspaces/fileContentService.js.map +1 -1
  36. package/dist/server/workspaces/fileSuggestions.js +311 -23
  37. package/dist/server/workspaces/fileSuggestions.js.map +1 -1
  38. package/dist/server/workspaces/fileTreeService.js +16 -7
  39. package/dist/server/workspaces/fileTreeService.js.map +1 -1
  40. package/dist/server/workspaces/imagePreviewService.js +5 -5
  41. package/dist/server/workspaces/imagePreviewService.js.map +1 -1
  42. package/dist/server/workspaces/pathAccessPolicy.js +90 -0
  43. package/dist/server/workspaces/pathAccessPolicy.js.map +1 -0
  44. package/dist/server/workspaces/pathSafety.js +0 -15
  45. package/dist/server/workspaces/pathSafety.js.map +1 -1
  46. package/dist/server/workspaces/projectPiWebConfig.js +56 -0
  47. package/dist/server/workspaces/projectPiWebConfig.js.map +1 -0
  48. package/dist/shared/apiTypes.d.ts +14 -0
  49. package/dist/shared/apiTypes.js +1 -0
  50. package/dist/shared/apiTypes.js.map +1 -1
  51. package/dist/shared/capabilities.js +2 -1
  52. package/dist/shared/capabilities.js.map +1 -1
  53. package/dist/shared/federatedRoutes.js +2 -0
  54. package/dist/shared/federatedRoutes.js.map +1 -1
  55. package/docs/assets/pi-web-desktop.png +0 -0
  56. package/docs/assets/pi-web-mobile.png +0 -0
  57. package/docs/assets/pi-web-tablet.png +0 -0
  58. package/docs/config.md +166 -0
  59. package/package.json +3 -1
  60. package/docs/assets/pi-web-demo.gif +0 -0
  61. package/docs/assets/pi-web-demo.webm +0 -0
@@ -1,27 +1,27 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CIG4PxA9.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-CKtvS-3H.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as yo,w as rt,J as Hi,R as Da,S as Wa,G as _a,U as Oa,V as La,A as ja,W as Na,X as za,Y as Fa,Z as So,x as xo,_ as Ba}from"./vendor-editor-core-B4Sq6exx.js";import{m as Ua,i as Ha,d as qa}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const ii=globalThis,_s=ii.ShadowRoot&&(ii.ShadyCSS===void 0||ii.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Os=Symbol(),ko=new WeakMap;let en=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Os)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(_s&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=ko.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&ko.set(i,t))}return t}toString(){return this.cssText}};const Ka=e=>new en(typeof e=="string"?e:e+"",void 0,Os),_=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>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.")})(o)+e[r+1],e[0]);return new en(i,e,Os)},Va=(e,t)=>{if(_s)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=ii.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},$o=_s?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Ka(i)})(e):e;const{is:Ga,defineProperty:Qa,getOwnPropertyDescriptor:Za,getOwnPropertyNames:Ja,getOwnPropertySymbols:Xa,getPrototypeOf:Ya}=Object,Ai=globalThis,Po=Ai.trustedTypes,el=Po?Po.emptyScript:"",tl=Ai.reactiveElementPolyfillSupport,Mt=(e,t)=>e,ci={toAttribute(e,t){switch(t){case Boolean:e=e?el: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}},Ls=(e,t)=>!Ga(e,t),Ro={attribute:!0,type:String,converter:ci,reflect:!1,useDefault:!1,hasChanged:Ls};Symbol.metadata??=Symbol("metadata"),Ai.litPropertyMetadata??=new WeakMap;let lt=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=Ro){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(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Qa(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=Za(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ro}static _$Ei(){if(this.hasOwnProperty(Mt("elementProperties")))return;const t=Ya(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Mt("properties"))){const i=this.properties,s=[...Ja(i),...Xa(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,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 o of s)i.unshift($o(o))}else t!==void 0&&i.push($o(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 Va(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),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:ci).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:ci;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ls)(r,i)||s.useDefault&&s.reflect&&r===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:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!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[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,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){}};lt.elementStyles=[],lt.shadowRootOptions={mode:"open"},lt[Mt("elementProperties")]=new Map,lt[Mt("finalized")]=new Map,tl?.({ReactiveElement:lt}),(Ai.reactiveElementVersions??=[]).push("2.1.2");const js=globalThis,Co=e=>e,di=js.trustedTypes,Io=di?di.createPolicy("lit-html",{createHTML:e=>e}):void 0,tn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,sn="?"+Be,il=`<${sn}>`,Je=document,Et=()=>Je.createComment(""),Dt=e=>e===null||typeof e!="object"&&typeof e!="function",Ns=Array.isArray,sl=e=>Ns(e)||typeof e?.[Symbol.iterator]=="function",qi=`[
3
- \f\r]`,bt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Mo=/-->/g,To=/>/g,qe=RegExp(`>|${qi}(?:([^\\s"'>=/]+)(${qi}*=${qi}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Ao=/'/g,Eo=/"/g,on=/^(?:script|style|textarea|title)$/i,rn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=rn(1),he=rn(2),Ue=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),Do=new WeakMap,Qe=Je.createTreeWalker(Je,129);function nn(e,t){if(!Ns(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Io!==void 0?Io.createHTML(t):t}const ol=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=bt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===bt?u[1]==="!--"?n=Mo:u[1]!==void 0?n=To:u[2]!==void 0?(on.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??bt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?Eo:Ao):n===Eo||n===Ao?n=qe:n===Mo||n===To?n=bt:(n=qe,o=void 0);const v=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===bt?c+il:h>=0?(s.push(p),c.slice(0,h)+tn+c.slice(h)+Be+v):c+Be+(h===-2?a:v)}return[nn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Wt{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=ol(t,i);if(this.el=Wt.createElement(p,s),Qe.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Qe.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(tn)){const f=u[n++],v=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?nl:P[1]==="?"?al:P[1]==="@"?ll:Ei}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(on.test(o.tagName)){const h=o.textContent.split(Be),f=h.length-1;if(f>0){o.textContent=di?di.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],Et()),Qe.nextNode(),c.push({type:2,index:++r});o.append(h[f],Et())}}}else if(o.nodeType===8)if(o.data===sn)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Je.createElement("template");return s.innerHTML=t,s}}function dt(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Dt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=dt(e,o._$AS(e,t.values),o,s)),t}class rl{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,o=(t?.creationScope??Je).importNode(i,!0);Qe.currentNode=o;let r=Qe.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ut(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new cl(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Qe.nextNode(),n++)}return Qe.currentNode=Je,o}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 ut{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.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=dt(this,t,i),Dt(t)?t===z||t==null||t===""?(this._$AH!==z&&this._$AR(),this._$AH=z):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):sl(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!==z&&Dt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Je.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Wt.createElement(nn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new rl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Do.get(t.strings);return i===void 0&&Do.set(t.strings,i=new Wt(t)),i}k(t){Ns(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new ut(this.O(Et()),this.O(Et()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Co(t).nextSibling;Co(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Ei=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=z,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=z}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=dt(this,t,i,0),n=!Dt(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=dt(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!Dt(p)||p!==this._$AH[c],p===z?t=z:t!==z&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},nl=class extends Ei{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===z?void 0:t}},al=class extends Ei{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==z)}},ll=class extends Ei{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=dt(this,t,i,0)??z)===Ue)return;const s=this._$AH,o=t===z&&s!==z||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==z&&(s===z||o);o&&this.element.removeEventListener(this.name,this,s),r&&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 cl{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){dt(this,t)}}const dl={I:ut},pl=js.litHtmlPolyfillSupport;pl?.(Wt,ut),(js.litHtmlVersions??=[]).push("3.3.2");const hl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new ut(t.insertBefore(Et(),r),r,void 0,i??{})}return o._$AI(e),o};const zs=globalThis;let I=class extends lt{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=hl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};I._$litElement$=!0,I.finalized=!0,zs.litElementHydrateSupport?.({LitElement:I});const ul=zs.litElementPolyfillSupport;ul?.({LitElement:I});(zs.litElementVersions??=[]).push("4.2.2");const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const fl={attribute:!0,type:String,converter:ci,reflect:!1,hasChanged:Ls},gl=(e=fl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,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 c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?gl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function b(e){return d({...e,state:!0,attribute:!1})}const ml=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return ml(i,s,{get(){return r(this)}})}}async function y(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(vl(n)??o.statusText)}const r=await o.json();return t(r)}function vl(e){if(bl(e))return typeof e.error=="string"?e.error:void 0}function bl(e){return typeof e=="object"&&e!==null}const pt={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},wl=Object.values(pt),yl=new Set(wl);function Sl(e){return typeof e=="string"&&yl.has(e)}function _t(e,t){return e?.capabilities?.includes(t)===!0}function Tt(e){return typeof e=="object"&&e!==null}function w(e){if(!Tt(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(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 le(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function W(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function F(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function xl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function kl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function $l(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=w(e);return{messages:xl(t.messages),start:le(t,"start"),total:le(t,"total")}}function Pl(e){const t=w(e);return F(an)(t.machines)}function an(e){const t=w(e),i=Il(t,"kind"),s=$(t,"baseUrl"),o=ln(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Rl(e){const t=w(e),i=ln(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:pi(t.web)},...t.sessiond===void 0?{}:{sessiond:pi(t.sessiond)},...s===void 0?{}:{error:s}}}function Cl(e){const t=w(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...S("packageName",$(t,"packageName")),...S("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:pn(t.components)},...t.capabilities===void 0?{}:{capabilities:Fs(t.capabilities)},...i===void 0?{}:{error:i}}}function Il(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function ln(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Wo(e){const t=w(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Ml(e){const t=w(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:W(t,"isMain"),isGitRepo:W(t,"isGitRepo"),isGitWorktree:W(t,"isGitWorktree")}}function gs(e){const t=w(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:le(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function wt(e){const t=w(e);return{sessionId:m(t,"sessionId"),isStreaming:W(t,"isStreaming"),isCompacting:W(t,"isCompacting"),isBashRunning:W(t,"isBashRunning"),pendingMessageCount:le(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:F(Tl)(t.queuedMessages),...S("messageCount",Ae(t,"messageCount")),tokens:Al(t.tokens),cost:le(t,"cost"),...El(t.model),...ql(t.contextUsage),...S("thinkingLevel",$(t,"thinkingLevel"))}}function Tl(e){const t=w(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function Al(e){const t=w(e);return{input:le(t,"input"),output:le(t,"output"),cacheRead:le(t,"cacheRead"),cacheWrite:le(t,"cacheWrite"),total:le(t,"total")}}function cn(e){const t=w(e);return{...S("provider",$(t,"provider")),...S("id",$(t,"id")),...S("name",$(t,"name")),...S("contextWindow",Ae(t,"contextWindow")),...S("reasoning",t.reasoning)}}function El(e){return e===void 0?{}:{model:cn(e)}}function Dl(e){const t=w(e);return{models:F(cn)(t.models)}}function Wl(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function _l(e){const t=w(e);return{levels:F(Wl)(t.levels)}}function Ol(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Ll(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 jl(e){const t=w(e),i=t.source===void 0?void 0:Ll(t.source);return{configured:W(t,"configured"),...S("source",i),...S("label",$(t,"label"))}}function Nl(e){const t=w(e);return{id:m(t,"id"),name:m(t,"name"),authType:Ol(t.authType),status:jl(t.status)}}function zl(e){const t=w(e);return{providers:F(Nl)(t.providers)}}function Kt(e){const t=w(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Fl(t.status),progress:F(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...S("error",$(t,"error")),...S("auth",Bl(t.auth)),...S("prompt",Ul(t.prompt)),...S("select",Hl(t.select))}}function Fl(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Bl(e){if(e===void 0)return;const t=w(e);return{url:m(t,"url"),...S("instructions",$(t,"instructions"))}}function Ul(e){if(e===void 0)return;const t=w(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...S("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Hl(e){if(e===void 0)return;const t=w(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:F(un)(t.options)}}function ql(e){if(e===void 0)return{};const t=w(e);return{contextUsage:{tokens:Fo(t,"tokens"),contextWindow:le(t,"contextWindow"),percent:Fo(t,"percent")}}}function Kl(e){const t=w(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...S("description",$(t,"description"))}}function dn(e){const t=w(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Vl(e){const t=w(e);return{path:m(t,"path"),entries:F(Gl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:W(t,"truncated")}}function Gl(e){const t=w(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...S("size",Ae(t,"size")),...S("modifiedAt",$(t,"modifiedAt"))}}function Ql(e){const t=w(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...S("language",$(t,"language")),...S("mediaType",Zl(t.mediaType)),...S("mimeType",$(t,"mimeType")),encoding:i,size:le(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:W(t,"truncated"),binary:W(t,"binary")}}function Zl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Jl(e){const t=w(e);return{isGitRepo:W(t,"isGitRepo"),hash:m(t,"hash"),...S("branch",$(t,"branch")),...S("upstream",$(t,"upstream")),...S("ahead",Ae(t,"ahead")),...S("behind",Ae(t,"behind")),files:F(Xl)(t.files)}}function Xl(e){const t=w(e);return{path:m(t,"path"),...S("oldPath",$(t,"oldPath")),index:_o(t.index),workingTree:_o(t.workingTree)}}function _o(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 Yl(e){const t=w(e);return{...S("path",$(t,"path")),staged:W(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:W(t,"truncated")}}function Ki(e){const t=w(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:W(t,"exited"),...S("exitCode",Ae(t,"exitCode")),...S("commandRunId",$(t,"commandRunId"))}}function At(e){const t=w(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:ec(t.status),...S("exitCode",Ae(t,"exitCode")),createdAt:m(t,"createdAt"),...S("startedAt",$(t,"startedAt")),...S("completedAt",$(t,"completedAt")),metadata:tc(t.metadata,"metadata")}}function ec(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function tc(e,t){const i=w(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function ic(e){const t=w(e);return{cwd:m(t,"cwd"),hasSessionActivity:W(t,"hasSessionActivity"),hasTerminalActivity:W(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function sc(e){const t=w(e);return{workspaces:F(ic)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Oo(e){const t=w(e);return{path:m(t,"path"),exists:W(t,"exists"),config:Lo(t.config),effectiveConfig:Lo(t.effectiveConfig),envOverrides:ac(t.envOverrides)}}function Lo(e){const t=w(e);return{...S("host",$(t,"host")),...S("port",Ae(t,"port")),...S("allowedHosts",oc(t.allowedHosts)),...S("shortcuts",rc(t.shortcuts)),...S("plugins",nc(t.plugins)),...S("spawnSessions",Mc(t,"spawnSessions"))}}function oc(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function rc(e){if(e!==void 0){if(!Tt(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function nc(e){if(e!==void 0){if(!Tt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Tt(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!Tt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function ac(e){const t=w(e);return{host:W(t,"host"),port:W(t,"port"),allowedHosts:W(t,"allowedHosts"),spawnSessions:W(t,"spawnSessions")}}function lc(e){const t=w(e);return{plugins:F(cc)(t.plugins)}}function cc(e){const t=w(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:dc(t.scope),machineSpecific:pc(t.machineSpecific,"machineSpecific")??!1,enabled:W(t,"enabled")}}function dc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function pc(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function hc(e){const t=w(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fc(t.components),release:mc(t.release),commands:vc(t.commands),messages:F(bc)(t.messages)}}function uc(e){const t=w(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:pn(t.components),capabilities:Fs(t.capabilities)}}function fc(e){const t=w(e);return{web:pi(t.web),sessiond:pi(t.sessiond)}}function pn(e){const t=w(e);return{web:jo(t.web),sessiond:jo(t.sessiond)}}function jo(e){const t=w(e);return{component:hn(t.component),label:m(t,"label"),...S("runtimeVersion",$(t,"runtimeVersion")),available:W(t,"available"),capabilities:Fs(t.capabilities),...S("error",$(t,"error"))}}function pi(e){const t=w(e);return{component:hn(t.component),label:m(t,"label"),...S("runtimeVersion",$(t,"runtimeVersion")),...S("installedVersion",$(t,"installedVersion")),stale:W(t,"stale"),available:W(t,"available"),...S("installation",gc(t.installation)),...S("error",$(t,"error"))}}function gc(e){if(e===void 0)return;const t=w(e),i=m(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,...S("path",$(t,"path")),...S("source",$(t,"source")),...s===void 0?{}:{scope:s},...S("npmRoot",$(t,"npmRoot"))}}function mc(e){const t=w(e);return{packageName:m(t,"packageName"),...S("latestVersion",$(t,"latestVersion")),updateAvailable:W(t,"updateAvailable"),...S("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...S("error",$(t,"error"))}}function vc(e){const t=w(e);return{...S("update",$(t,"update")),...S("restart",$(t,"restart")),...S("restartWeb",$(t,"restartWeb")),...S("restartSessiond",$(t,"restartSessiond")),...S("status",$(t,"status"))}}function bc(e){const t=w(e);return{id:m(t,"id"),severity:wc(t.severity),title:m(t,"title"),body:m(t,"body"),...S("command",$(t,"command"))}}function hn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Fs(e){if(!Array.isArray(e)||!e.every(Sl))throw new Error("Invalid PI WEB capabilities");return e}function wc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function No(e){const t=w(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:F(un)(t.options)};if(i==="done")return{type:i,...S("message",$(t,"message")),...yc(t.session),...S("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function un(e){const t=w(e);return{value:m(t,"value"),label:m(t,"label"),...S("description",$(t,"description"))}}function yc(e){return e===void 0?{}:{session:gs(e)}}function Vt(e){if(w(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Sc(e){const t=w(e);return F(xc)(t.attachments)}function xc(e){const t=w(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:le(t,"size")}}function ms(e){if(w(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function kc(e){if(w(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function $c(e){if(w(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function zo(e){const t=w(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:kl(t.sessionIds,"sessionIds"),s=Ae(t,"archivedCount"),o=Ae(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Pc(e){if(w(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Rc(e){if(w(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Cc(e){if(w(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Ic(e){if(w(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Mc(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Ae(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 Fo(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 S(e,t){return t===void 0?{}:{[e]:t}}function Tc(e){return typeof e=="string"?e:e.id}function Ac(e){return typeof e=="string"?void 0:e.cwd}function Ec(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function Dc(e,t,i="local"){const s=new URLSearchParams,o=Ac(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Tc(e))}/messages${r===""?"":`?${r}`}`}function Wc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const T=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function _c(e){return typeof e=="string"?e:e.id}function fn(e){return typeof e=="string"?void 0:e.cwd}function gn(e,t="local"){return`${T(t)}/sessions/${encodeURIComponent(_c(e))}`}function V(e,t,i="local"){return`${gn(e,i)}/${t}`}function Gt(e,t,i="local"){return`${V(e,t,i)}${mn(e)}`}function Oc(e,t="local"){return`${gn(e,t)}${mn(e)}`}function mn(e){const t=fn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=fn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const vn={piWebStatus:(e="local")=>y(e==="local"?"/api/pi-web/status":`${T(e)}/pi-web/status`,hc),piWebRuntime:()=>y("/api/pi-web/runtime",uc)},Lc={machines:()=>y("/api/machines",Pl),addMachine:e=>y("/api/machines",an,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>y(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>y(`/api/machines/${encodeURIComponent(e)}/health`,Rl),runtime:e=>y(`/api/machines/${encodeURIComponent(e)}/runtime`,Cl)},hi={config:()=>y("/api/config",Oo),saveConfig:e=>y("/api/config",Oo,{method:"PUT",body:JSON.stringify({config:e})})},vs={plugins:()=>y("/api/plugins",lc)},bn={workspaceActivity:(e="local")=>y(`${T(e)}/activity`,sc)},jc={projects:(e="local")=>y(`${T(e)}/projects`,F(Wo)),addProject:(e,t,i,s="local")=>y(`${T(s)}/projects`,Wo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>y(`${T(t)}/projects/${encodeURIComponent(e)}`,ms,{method:"DELETE"}),projectDirectories:(e,t="local")=>y(`${T(t)}/project-directories?q=${encodeURIComponent(e)}`,F(dn))},bs={workspaces:(e,t="local")=>y(`${T(t)}/projects/${e}/workspaces`,F(Ml)),deleteWorkspace:(e,t,i="local")=>y(`${T(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,At,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>y(`${T(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Vl),workspaceFile:(e,t,i,s="local")=>y(`${T(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Ql)},Nc={sessions:(e,t="local")=>y(`${T(t)}/sessions?cwd=${encodeURIComponent(e)}`,F(gs)),startSession:(e,t="local")=>y(`${T(t)}/sessions`,gs,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>y(Dc(e,t,i),$l),status:(e,t="local")=>y(Gt(e,"status",t),wt),models:(e,t="local")=>y(Gt(e,"models",t),Dl),setModel:(e,t,i,s="local")=>y(V(e,"model",s),wt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>y(V(e,"model/cycle",i),wt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>y(Gt(e,"thinking-levels",t),_l),setThinkingLevel:(e,t,i="local")=>y(V(e,"thinking-level",i),wt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>y(V(e,"thinking-level/cycle",t),wt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>y(Gt(e,"commands",t),F(Kl)),prompt:(e,t,i,s="local",o)=>y(V(e,"prompt",s),Vt,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>y(V(e,"attachments",i),Sc,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>y(V(e,"shell",i),Vt,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>y(V(e,"commands/run",i),No,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>y(V(e,"commands/respond",s),No,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>y(V(e,"abort",t),kc,{method:"POST",body:Q(e)}),stop:(e,t="local")=>y(V(e,"stop",t),$c,{method:"POST",body:Q(e)}),archive:(e,t="local")=>y(V(e,"archive",t),zo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>y(V(e,"archive-tree",t),zo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>y(V(e,"restore",t),Pc,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>y(Oc(e,t),Rc,{method:"DELETE"}),detachParent:(e,t="local")=>y(V(e,"detach-parent",t),Cc,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>y(V(e,"reload",t),Ic,{method:"POST",body:Q(e)}),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 y(`${T(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,zl)},saveApiKey:(e,t,i="local")=>y(`${T(i)}/auth/api-key`,Vt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>y(`${T(t)}/auth/logout`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>y(`${T(t)}/auth/oauth`,Kt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>y(`${T(t)}/auth/oauth/${encodeURIComponent(e)}`,Kt),respondOAuthFlow:(e,t,i,s="local")=>y(`${T(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Kt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>y(`${T(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Kt,{method:"POST"})},ct={terminals:(e,t,i="local")=>y(`${T(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,F(Ki)),startTerminal:(e,t,i,s="local")=>y(`${T(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ki,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>y(`${T(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ms,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>y(`${T(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ms,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>y(`${T(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Ki,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>y(`${T(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,At,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>y(`${T(t)}/terminal-command-runs${Fc(e)}`,F(At)),getCommandRun:(e,t="local")=>zc(e,t),cancelCommandRun:(e,t="local")=>y(`${T(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,At,{method:"POST"})};async function zc(e,t){const i=await fetch(`${T(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Bc(s)??i.statusText)}return At(await i.json())}}function Fc(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Bc(e){if(!Uc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Uc(e){return typeof e=="object"&&e!==null}const Hc={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),y(`${T(i.machineId)}/files?${s.toString()}`,F(dn))}},qc={gitStatus:(e,t,i="local")=>y(`${T(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Jl),gitDiff:(e,t,i,s="local")=>y(Ec(s,e,t,i),Yl)},L={...vn,...Lc,...hi,...vs,...bn,...jc,...bs,...Nc,...ct,...Hc,...qc};function Kc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Us()}${Bs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function cw(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Us()}${Bs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Vc(e="local"){return new WebSocket(`${Us()}${Bs(e)}/events`)}function Bs(e){return`/api/machines/${encodeURIComponent(e)}`}function Us(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function si(){return{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,selectedTerminalId:void 0,error:""}}function Gc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!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,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function wn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const yn="local";function Vi(e,t){return`${e}:${t}`}function Sn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??yn}class Qc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??bn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Zc(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=Jc(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Zc(e){const t={};for(const i of e.workspaces)wn(i)&&(t[i.cwd]=i);return t}function Jc(e,t){const i={...e};return wn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Xc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??L,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Yc(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,machineId:g(this.getState())});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 o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,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,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&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){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}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 o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));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,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.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 o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}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??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}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,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Yc(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 o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function jt(e){return e.replaceAll(":",".")}function ed(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Gi(e,t){const i=ed(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function xe(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));td(o,s)}function td(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 Bo=jt("core:workspace.files");class id{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=g(this.getState()),o=await L.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await L.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.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:od(this.getState().expandedDirs,t)});return}try{const o=await L.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),xe(Bo,"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 o=await L.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(sd(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),xe(Bo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function sd(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function od(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Uo=jt("core:workspace.git");class rd{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 L.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),xe(Uo,"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"}),xe(Uo,"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[o,r]=await Promise.all([L.gitDiff(i.id,s.id,{path:t},g(this.getState())),L.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}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 nd{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await L.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Ho(this.getState().machineActivities,o),machineRuntimes:Ho(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...si()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await L.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await L.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Qi(this.getState().machineStatuses,t.id),machineRuntimes:Qi(this.getState().machineRuntimes,t.id),machineActivities:Qi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await L.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await L.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await L.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>L.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>L.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Qi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ho(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class ad{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await L.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await L.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await L.closeProject(t,g(this.getState())),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 ws="pi-web:cached-new-sessions:v1",ld="browserCachedNew",ft="local";function Nt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function qo(e,t=ft,i=Nt()){if(e.messageCount!==0||e.archived===!0)return;const s=Hs(i).filter(o=>o.id!==e.id||o.machineId!==t);qs([ys(e,t),...s],i)}function ys(e,t=ft){return{...e,browserCachedNew:!0,machineId:t}}function Ko(e,t=ft,i=Nt()){const s=Hs(i).filter(o=>o.id!==e||o.machineId!==t);qs(s,i)}function cd(e,t,i=ft,s=Nt()){const o=new Set(t.map(c=>c.id)),r=Hs(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&qs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ee(e){return e===void 0?!1:hd(e)&&e.browserCachedNew===!0}function dd(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},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:ft},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Hs(e=Nt()){try{const t=e?.getItem(ws);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>pd(s)):[]}catch{return[]}}function qs(e,t=Nt()){try{e.length===0?t?.removeItem(ws):t?.setItem(ws,JSON.stringify(e))}catch{}}function pd(e){if(!ud(e))return[];const t=nt(e,"id"),i=nt(e,"path"),s=nt(e,"cwd"),o=nt(e,"created"),r=nt(e,"modified"),n=nt(e,"firstMessage"),a=fd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Zi(e,"name"),p=Zi(e,"parentSessionPath"),u=Zi(e,"machineId")??ft;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function hd(e){return ld in e}function ud(e){return typeof e=="object"&&e!==null}function nt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Zi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function fd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function gd(e){return Ad(e.flatMap(Ks)).filter(t=>t.parts.length>0)}function Te(e,t){return{role:e,parts:[{type:"text",text:t}]}}function yt(e,t){const i=kd(t);return i===void 0?e:{...e,meta:i}}function md(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Te(t,i)]}function vd(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 Ks(e){if(wd(e))return[e];if(D(e,"role")==="bashExecution")return[yt(Rd(e),e)];const t=Cd(D(e,"role")),i=Id(fe(e,"content"),e),s=t==="user"?yd(i):void 0;if(s!==void 0)return s.map(p=>yt(p,e));const o=xd(e);if(t==="tool")return[yt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[yt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=bd(e);return c===void 0?a:[...a,yt(c,e)]}function bd(e){if(D(e,"role")!=="assistant"||D(e,"stopReason")!=="error")return;const t=D(e,"errorMessage")?.trim();return Te("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function wd(e){const t=D(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function yd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Sd(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 Sd(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 xd(e){const t=D(e,"source");if(t==="compaction"||t==="branch_summary")return t}function kd(e){const t=$d(fe(e,"timestamp")),i=Pd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function $d(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 Pd(e){if(D(e,"role")!=="assistant")return;const t=D(e,"provider"),i=D(e,"model"),s=D(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 Rd(e){const t=D(e,"command")??"",i=oi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",fi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${fi(o)}`),oi(e,"cancelled")===!0&&i.push("","cancelled"),oi(e,"truncated")===!0&&i.push("","output truncated");const r=D(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function Cd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Id(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=D(i,"type"),o=D(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=D(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=D(i,"name")??"tool",n=fe(i,"arguments"),a=r==="read"?Td(D(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=D(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:r,summary:zt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=D(i,"data"),n=D(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return Vo(i)}).map(i=>i.type==="text"&&D(t,"role")==="toolResult"?Md(i.text,t):i):Vo(e)}function Md(e,t){const i=D(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:D(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:oi(t,"isError")===!0}}function Td(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 Ad(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Ed(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&Dd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function Ed(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 Dd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=ui(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function ui(e){const t=fe(e,"preview");if(!Vs(t))return;const i=D(t,"diff"),s=D(t,"error"),o=_d(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Vo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:zt(e)}]:[{type:"text",text:fi(e)}]}function zt(e){if(!Vs(e))return fi(e);const t=D(e,"command");if(t!==void 0)return t;const i=D(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(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${Wd(n)}`).join(" · ")}function Wd(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 Vs(e){return typeof e=="object"&&e!==null}function fe(e,t){return Vs(e)?e[t]:void 0}function D(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function oi(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function _d(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function fi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Od="pi-web:prompt-draft:";function gi(e){return`${Od}${e}`}function Di(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function xn(e,t=Di()){try{return t?.getItem(gi(e))??""}catch{return""}}function mi(e,t,i=Di()){try{t?i?.setItem(gi(e),t):i?.removeItem(gi(e))}catch{}}function Gs(e,t=Di()){try{t?.removeItem(gi(e))}catch{}}function Ld(e,t,i=Di()){const s=xn(e,i);s!==""&&(mi(t,s,i),Gs(e,i))}function jd(e,t){return Te("bash",`${t===!0?`excluded from context
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Bv8l_MFi.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BZKsaE9s.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as xo,w as nt,J as qi,R as La,S as ja,G as Na,U as za,V as Fa,A as Ba,W as Ua,X as Ha,Y as qa,Z as ko,x as $o,_ as Ka}from"./vendor-editor-core-Bc1A7SO7.js";import{m as Va,i as Ga,d as Qa}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const si=globalThis,Ls=si.ShadowRoot&&(si.ShadyCSS===void 0||si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,js=Symbol(),Po=new WeakMap;let rn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==js)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(Ls&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Po.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Po.set(i,t))}return t}toString(){return this.cssText}};const Za=e=>new rn(typeof e=="string"?e:e+"",void 0,js),O=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>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.")})(o)+e[r+1],e[0]);return new rn(i,e,js)},Ja=(e,t)=>{if(Ls)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=si.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Ro=Ls?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Za(i)})(e):e;const{is:Xa,defineProperty:Ya,getOwnPropertyDescriptor:el,getOwnPropertyNames:tl,getOwnPropertySymbols:il,getPrototypeOf:sl}=Object,Ei=globalThis,Io=Ei.trustedTypes,ol=Io?Io.emptyScript:"",rl=Ei.reactiveElementPolyfillSupport,Et=(e,t)=>e,di={toAttribute(e,t){switch(t){case Boolean:e=e?ol: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}},Ns=(e,t)=>!Xa(e,t),Co={attribute:!0,type:String,converter:di,reflect:!1,useDefault:!1,hasChanged:Ns};Symbol.metadata??=Symbol("metadata"),Ei.litPropertyMetadata??=new WeakMap;let dt=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=Co){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(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Ya(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=el(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Co}static _$Ei(){if(this.hasOwnProperty(Et("elementProperties")))return;const t=sl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Et("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Et("properties"))){const i=this.properties,s=[...tl(i),...il(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,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 o of s)i.unshift(Ro(o))}else t!==void 0&&i.push(Ro(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 Ja(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),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:di).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:di;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ns)(r,i)||s.useDefault&&s.reflect&&r===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:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!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[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,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){}};dt.elementStyles=[],dt.shadowRootOptions={mode:"open"},dt[Et("elementProperties")]=new Map,dt[Et("finalized")]=new Map,rl?.({ReactiveElement:dt}),(Ei.reactiveElementVersions??=[]).push("2.1.2");const zs=globalThis,Mo=e=>e,pi=zs.trustedTypes,Ao=pi?pi.createPolicy("lit-html",{createHTML:e=>e}):void 0,nn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,an="?"+Be,nl=`<${an}>`,Xe=document,Wt=()=>Xe.createComment(""),_t=e=>e===null||typeof e!="object"&&typeof e!="function",Fs=Array.isArray,al=e=>Fs(e)||typeof e?.[Symbol.iterator]=="function",Ki=`[
3
+ \f\r]`,St=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,To=/-->/g,Eo=/>/g,qe=RegExp(`>|${Ki}(?:([^\\s"'>=/]+)(${Ki}*=${Ki}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Do=/'/g,Wo=/"/g,ln=/^(?:script|style|textarea|title)$/i,cn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=cn(1),he=cn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),_o=new WeakMap,Qe=Xe.createTreeWalker(Xe,129);function dn(e,t){if(!Fs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ao!==void 0?Ao.createHTML(t):t}const ll=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=St;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===St?u[1]==="!--"?n=To:u[1]!==void 0?n=Eo:u[2]!==void 0?(ln.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??St,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?Wo:Do):n===Wo||n===Do?n=qe:n===To||n===Eo?n=St:(n=qe,o=void 0);const v=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===St?c+nl:h>=0?(s.push(p),c.slice(0,h)+nn+c.slice(h)+Be+v):c+Be+(h===-2?a:v)}return[dn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ot{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=ll(t,i);if(this.el=Ot.createElement(p,s),Qe.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Qe.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(nn)){const f=u[n++],v=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?dl:P[1]==="?"?pl:P[1]==="@"?hl:Di}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(ln.test(o.tagName)){const h=o.textContent.split(Be),f=h.length-1;if(f>0){o.textContent=pi?pi.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],Wt()),Qe.nextNode(),c.push({type:2,index:++r});o.append(h[f],Wt())}}}else if(o.nodeType===8)if(o.data===an)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Xe.createElement("template");return s.innerHTML=t,s}}function ft(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=_t(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ft(e,o._$AS(e,t.values),o,s)),t}class cl{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,o=(t?.creationScope??Xe).importNode(i,!0);Qe.currentNode=o;let r=Qe.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new mt(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new ul(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Qe.nextNode(),n++)}return Qe.currentNode=Xe,o}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 mt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.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=ft(this,t,i),_t(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):al(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!==F&&_t(this._$AH)?this._$AA.nextSibling.data=t:this.T(Xe.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ot.createElement(dn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new cl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=_o.get(t.strings);return i===void 0&&_o.set(t.strings,i=new Ot(t)),i}k(t){Fs(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new mt(this.O(Wt()),this.O(Wt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Mo(t).nextSibling;Mo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Di=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=ft(this,t,i,0),n=!_t(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=ft(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!_t(p)||p!==this._$AH[c],p===F?t=F:t!==F&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},dl=class extends Di{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},pl=class extends Di{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},hl=class extends Di{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=ft(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&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)}},ul=class{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){ft(this,t)}};const fl={I:mt},gl=zs.litHtmlPolyfillSupport;gl?.(Ot,mt),(zs.litHtmlVersions??=[]).push("3.3.3");const ml=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new mt(t.insertBefore(Wt(),r),r,void 0,i??{})}return o._$AI(e),o};const Bs=globalThis;let C=class extends dt{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=ml(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};C._$litElement$=!0,C.finalized=!0,Bs.litElementHydrateSupport?.({LitElement:C});const vl=Bs.litElementPolyfillSupport;vl?.({LitElement:C});(Bs.litElementVersions??=[]).push("4.2.2");const D=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const bl={attribute:!0,type:String,converter:di,reflect:!1,hasChanged:Ns},wl=(e=bl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,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 c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?wl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const yl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return yl(i,s,{get(){return r(this)}})}}async function S(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Sl(n)??o.statusText)}const r=await o.json();return t(r)}function Sl(e){if(xl(e))return typeof e.error=="string"?e.error:void 0}function xl(e){return typeof e=="object"&&e!==null}const Ze={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},kl=Object.values(Ze),$l=new Set(kl);function Pl(e){return typeof e=="string"&&$l.has(e)}function ht(e,t){return e?.capabilities?.includes(t)===!0}function ut(e){return typeof e=="object"&&e!==null}function y(e){if(!ut(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(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 le(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Rl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Il(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Cl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:Rl(t.messages),start:le(t,"start"),total:le(t,"total")}}function Ml(e){const t=y(e);return N(pn)(t.machines)}function pn(e){const t=y(e),i=El(t,"kind"),s=$(t,"baseUrl"),o=hn(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Al(e){const t=y(e),i=hn(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:hi(t.web)},...t.sessiond===void 0?{}:{sessiond:hi(t.sessiond)},...s===void 0?{}:{error:s}}}function Tl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:fn(t.components)},...t.capabilities===void 0?{}:{capabilities:Us(t.capabilities)},...i===void 0?{}:{error:i}}}function El(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function hn(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Oo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Dl(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function ms(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:le(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function xt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:le(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Wl)(t.queuedMessages),...b("messageCount",Pe(t,"messageCount")),tokens:_l(t.tokens),cost:le(t,"cost"),...Ol(t.model),...Ql(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Wl(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function _l(e){const t=y(e);return{input:le(t,"input"),output:le(t,"output"),cacheRead:le(t,"cacheRead"),cacheWrite:le(t,"cacheWrite"),total:le(t,"total")}}function un(e){const t=y(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",Pe(t,"contextWindow")),...b("reasoning",t.reasoning)}}function Ol(e){return e===void 0?{}:{model:un(e)}}function Ll(e){const t=y(e);return{models:N(un)(t.models)}}function jl(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Nl(e){const t=y(e);return{levels:N(jl)(t.levels)}}function zl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Fl(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 Bl(e){const t=y(e),i=t.source===void 0?void 0:Fl(t.source);return{configured:E(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function Ul(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:zl(t.authType),status:Bl(t.status)}}function Hl(e){const t=y(e);return{providers:N(Ul)(t.providers)}}function Vt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:ql(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Kl(t.auth)),...b("prompt",Vl(t.prompt)),...b("select",Gl(t.select))}}function ql(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Kl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function Vl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Gl(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(mn)(t.options)}}function Ql(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Ho(t,"tokens"),contextWindow:le(t,"contextWindow"),percent:Ho(t,"percent")}}}function Zl(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...b("description",$(t,"description"))}}function vs(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Jl(e){const t=y(e);return{path:m(t,"path"),entries:N(Xl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function Xl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...b("size",Pe(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function Yl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",ec(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:le(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function ec(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function tc(e){const t=y(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",Pe(t,"ahead")),...b("behind",Pe(t,"behind")),files:N(ic)(t.files)}}function ic(e){const t=y(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Lo(t.index),workingTree:Lo(t.workingTree)}}function Lo(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 sc(e){const t=y(e);return{...b("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Vi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...b("exitCode",Pe(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Dt(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:oc(t.status),...b("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:rc(t.metadata,"metadata")}}function oc(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function rc(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function nc(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ac(e){const t=y(e);return{workspaces:N(nc)(t.workspaces),generatedAt:m(t,"generatedAt")}}function jo(e){const t=y(e);return{path:m(t,"path"),exists:E(t,"exists"),config:No(t.config),effectiveConfig:No(t.effectiveConfig),envOverrides:gc(t.envOverrides)}}function No(e){const t=y(e);return{...b("host",$(t,"host")),...b("port",Pe(t,"port")),...b("allowedHosts",lc(t.allowedHosts)),...b("shortcuts",uc(t.shortcuts)),...b("plugins",fc(t.plugins)),...b("pathAccess",cc(t.pathAccess)),...b("maxUploadBytes",Pe(t,"maxUploadBytes")),...b("spawnSessions",Uo(t,"spawnSessions")),...b("subsessions",Uo(t,"subsessions"))}}function lc(e){if(e!==void 0){if(e===!0)return!0;if(pc(e))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function cc(e){if(e===void 0)return;if(!ut(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",dc(t,"pathAccess.allowedPaths"))}}function dc(e,t){if(e!==void 0){if(hc(e))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function pc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function hc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}function uc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function fc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!ut(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!ut(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function gc(e){const t=y(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function mc(e){const t=y(e);return{plugins:N(vc)(t.plugins)}}function vc(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:bc(t.scope),machineSpecific:wc(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function bc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function wc(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function yc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:xc(t.components),release:$c(t.release),commands:Pc(t.commands),messages:N(Rc)(t.messages)}}function Sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fn(t.components),capabilities:Us(t.capabilities)}}function xc(e){const t=y(e);return{web:hi(t.web),sessiond:hi(t.sessiond)}}function fn(e){const t=y(e);return{web:zo(t.web),sessiond:zo(t.sessiond)}}function zo(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Us(t.capabilities),...b("error",$(t,"error"))}}function hi(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...b("installation",kc(t.installation)),...b("error",$(t,"error"))}}function kc(e){if(e===void 0)return;const t=y(e),i=m(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,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function $c(e){const t=y(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function Pc(e){const t=y(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function Rc(e){const t=y(e);return{id:m(t,"id"),severity:Ic(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function gn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Us(e){if(!Array.isArray(e)||!e.every(Pl))throw new Error("Invalid PI WEB capabilities");return e}function Ic(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Fo(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(mn)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...Cc(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function mn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function Cc(e){return e===void 0?{}:{session:ms(e)}}function Gt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Mc(e){const t=y(e);return N(Ac)(t.attachments)}function Ac(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:le(t,"size")}}function bs(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Tc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Ec(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Bo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Il(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Dc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Wc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function _c(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Oc(e){if(y(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Uo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(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 Ho(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 b(e,t){return t===void 0?{}:{[e]:t}}function Lc(e){return typeof e=="string"?e:e.id}function jc(e){return typeof e=="string"?void 0:e.cwd}function Nc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function zc(e,t,i="local"){const s=new URLSearchParams,o=jc(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Lc(e))}/messages${r===""?"":`?${r}`}`}function Fc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const A=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Bc(e){return typeof e=="string"?e:e.id}function vn(e){return typeof e=="string"?void 0:e.cwd}function bn(e,t="local"){return`${A(t)}/sessions/${encodeURIComponent(Bc(e))}`}function V(e,t,i="local"){return`${bn(e,i)}/${t}`}function Qt(e,t,i="local"){return`${V(e,t,i)}${wn(e)}`}function Uc(e,t="local"){return`${bn(e,t)}${wn(e)}`}function wn(e){const t=vn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=vn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const yn={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${A(e)}/pi-web/status`,yc),piWebRuntime:()=>S("/api/pi-web/runtime",Sc)},Hc={machines:()=>S("/api/machines",Ml),addMachine:e=>S("/api/machines",pn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>S(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>S(`/api/machines/${encodeURIComponent(e)}/health`,Al),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,Tl)},ui={config:()=>S("/api/config",jo),saveConfig:e=>S("/api/config",jo,{method:"PUT",body:JSON.stringify({config:e})})},ws={plugins:()=>S("/api/plugins",mc)},Sn={workspaceActivity:(e="local")=>S(`${A(e)}/activity`,ac)},qc={projects:(e="local")=>S(`${A(e)}/projects`,N(Oo)),addProject:(e,t,i,s="local")=>S(`${A(s)}/projects`,Oo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${A(t)}/projects/${encodeURIComponent(e)}`,bs,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${A(t)}/project-directories?q=${encodeURIComponent(e)}`,N(vs))},ys={workspaces:(e,t="local")=>S(`${A(t)}/projects/${e}/workspaces`,N(Dl)),deleteWorkspace:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Dt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Jl),workspaceFile:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Yl)},Kc={sessions:(e,t="local")=>S(`${A(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ms)),startSession:(e,t="local")=>S(`${A(t)}/sessions`,ms,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(zc(e,t,i),Cl),status:(e,t="local")=>S(Qt(e,"status",t),xt),models:(e,t="local")=>S(Qt(e,"models",t),Ll),setModel:(e,t,i,s="local")=>S(V(e,"model",s),xt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(V(e,"model/cycle",i),xt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Qt(e,"thinking-levels",t),Nl),setThinkingLevel:(e,t,i="local")=>S(V(e,"thinking-level",i),xt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(V(e,"thinking-level/cycle",t),xt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>S(Qt(e,"commands",t),N(Zl)),prompt:(e,t,i,s="local",o)=>S(V(e,"prompt",s),Gt,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>S(V(e,"attachments",i),Mc,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>S(V(e,"shell",i),Gt,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>S(V(e,"commands/run",i),Fo,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(V(e,"commands/respond",s),Fo,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(V(e,"abort",t),Tc,{method:"POST",body:Q(e)}),stop:(e,t="local")=>S(V(e,"stop",t),Ec,{method:"POST",body:Q(e)}),archive:(e,t="local")=>S(V(e,"archive",t),Bo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>S(V(e,"archive-tree",t),Bo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>S(V(e,"restore",t),Dc,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>S(Uc(e,t),Wc,{method:"DELETE"}),detachParent:(e,t="local")=>S(V(e,"detach-parent",t),_c,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>S(V(e,"reload",t),Oc,{method:"POST",body:Q(e)}),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 S(`${A(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Hl)},saveApiKey:(e,t,i="local")=>S(`${A(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${A(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${A(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>S(`${A(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},pt={terminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Vi)),startTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Vi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,bs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,bs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Vi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Dt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${A(t)}/terminal-command-runs${Gc(e)}`,N(Dt)),getCommandRun:(e,t="local")=>Vc(e,t),cancelCommandRun:(e,t="local")=>S(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Dt,{method:"POST"})};async function Vc(e,t){const i=await fetch(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Qc(s)??i.statusText)}return Dt(await i.json())}}function Gc(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Qc(e){if(!Zc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Zc(e){return typeof e=="object"&&e!==null}const Jc={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?S(`${A(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,N(vs)):(s.set("cwd",e),S(`${A(i.machineId)}/files?${s.toString()}`,N(vs)))}},Xc={gitStatus:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,tc),gitDiff:(e,t,i,s="local")=>S(Nc(s,e,t,i),sc)},j={...yn,...Hc,...ui,...ws,...Sn,...qc,...ys,...Kc,...pt,...Jc,...Xc};function Yc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${qs()}${Hs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function $w(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${qs()}${Hs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function ed(e="local"){return new WebSocket(`${qs()}${Hs(e)}/events`)}function Hs(e){return`/api/machines/${encodeURIComponent(e)}`}function qs(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function oi(){return{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,selectedTerminalId:void 0,error:""}}function td(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!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,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ye(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function xn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const kn="local";function Gi(e,t){return`${e}:${t}`}function $n(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??kn}class id{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Sn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,sd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=od(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function sd(e){const t={};for(const i of e.workspaces)xn(i)&&(t[i.cwd]=i);return t}function od(e,t){const i={...e};return xn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class rd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??j,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=nd(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,machineId:g(this.getState())});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 o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,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,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&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){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}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 o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));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,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.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 o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}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??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}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,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function nd(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 o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Nt(e){return e.replaceAll(":",".")}function ad(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Qi(e,t){const i=ad(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function xe(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));ld(o,s)}function ld(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 qo=Nt("core:workspace.files");class cd{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=g(this.getState()),o=await j.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await j.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.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:pd(this.getState().expandedDirs,t)});return}try{const o=await j.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),xe(qo,"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 o=await j.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(dd(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),xe(qo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function dd(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function pd(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Ko=Nt("core:workspace.git");class hd{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 j.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),xe(Ko,"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"}),xe(Ko,"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[o,r]=await Promise.all([j.gitDiff(i.id,s.id,{path:t},g(this.getState())),j.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}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 ud{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await j.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Vo(this.getState().machineActivities,o),machineRuntimes:Vo(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...oi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await j.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await j.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Zi(this.getState().machineStatuses,t.id),machineRuntimes:Zi(this.getState().machineRuntimes,t.id),machineActivities:Zi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await j.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>j.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>j.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Zi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Vo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class fd{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await j.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await j.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await j.closeProject(t,g(this.getState())),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 Ss="pi-web:cached-new-sessions:v1",gd="browserCachedNew",vt="local";function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Go(e,t=vt,i=zt()){if(e.messageCount!==0||e.archived===!0)return;const s=Ks(i).filter(o=>o.id!==e.id||o.machineId!==t);Vs([xs(e,t),...s],i)}function xs(e,t=vt){return{...e,browserCachedNew:!0,machineId:t}}function Qo(e,t=vt,i=zt()){const s=Ks(i).filter(o=>o.id!==e||o.machineId!==t);Vs(s,i)}function md(e,t,i=vt,s=zt()){const o=new Set(t.map(c=>c.id)),r=Ks(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Vs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ee(e){return e===void 0?!1:wd(e)&&e.browserCachedNew===!0}function vd(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},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:vt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ks(e=zt()){try{const t=e?.getItem(Ss);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>bd(s)):[]}catch{return[]}}function Vs(e,t=zt()){try{e.length===0?t?.removeItem(Ss):t?.setItem(Ss,JSON.stringify(e))}catch{}}function bd(e){if(!yd(e))return[];const t=at(e,"id"),i=at(e,"path"),s=at(e,"cwd"),o=at(e,"created"),r=at(e,"modified"),n=at(e,"firstMessage"),a=Sd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Ji(e,"name"),p=Ji(e,"parentSessionPath"),u=Ji(e,"machineId")??vt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function wd(e){return gd in e}function yd(e){return typeof e=="object"&&e!==null}function at(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ji(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Sd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function xd(e){return jd(e.flatMap(Gs)).filter(t=>t.parts.length>0)}function Te(e,t){return{role:e,parts:[{type:"text",text:t}]}}function kt(e,t){const i=Ad(t);return i===void 0?e:{...e,meta:i}}function kd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Te(t,i)]}function $d(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 Gs(e){if(Rd(e))return[e];if(W(e,"role")==="bashExecution")return[kt(Dd(e),e)];const t=Wd(W(e,"role")),i=_d(fe(e,"content"),e),s=t==="user"?Id(i):void 0;if(s!==void 0)return s.map(p=>kt(p,e));const o=Md(e);if(t==="tool")return[kt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[kt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Pd(e);return c===void 0?a:[...a,kt(c,e)]}function Pd(e){if(W(e,"role")!=="assistant"||W(e,"stopReason")!=="error")return;const t=W(e,"errorMessage")?.trim();return Te("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Rd(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Id(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Cd(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 Cd(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 Md(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ad(e){const t=Td(fe(e,"timestamp")),i=Ed(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Td(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 Ed(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(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 Dd(e){const t=W(e,"command")??"",i=ri(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",gi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${gi(o)}`),ri(e,"cancelled")===!0&&i.push("","cancelled"),ri(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function Wd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function _d(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=W(i,"type"),o=W(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=W(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=W(i,"name")??"tool",n=fe(i,"arguments"),a=W(i,"id"),c=r==="read"?Ld(W(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:Ft(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=W(i,"data"),n=W(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return Zo(i)}).map(i=>i.type==="text"&&W(t,"role")==="toolResult"?Od(i.text,t):i):Zo(e)}function Od(e,t){const i=W(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:W(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ri(t,"isError")===!0}}function Ld(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 jd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Nd(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&zd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function Nd(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 zd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=fi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function fi(e){const t=fe(e,"preview");if(!Qs(t))return;const i=W(t,"diff"),s=W(t,"error"),o=Bd(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Zo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Ft(e)}]:[{type:"text",text:gi(e)}]}function Ft(e){if(!Qs(e))return gi(e);const t=W(e,"command");if(t!==void 0)return t;const i=W(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(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${Fd(n)}`).join(" · ")}function Fd(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 Qs(e){return typeof e=="object"&&e!==null}function fe(e,t){return Qs(e)?e[t]:void 0}function W(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function ri(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function Bd(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function gi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Ud="pi-web:prompt-draft:";function mi(e){return`${Ud}${e}`}function Wi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Pn(e,t=Wi()){try{return t?.getItem(mi(e))??""}catch{return""}}function vi(e,t,i=Wi()){try{t?i?.setItem(mi(e),t):i?.removeItem(mi(e))}catch{}}function Zs(e,t=Wi()){try{t?.removeItem(mi(e))}catch{}}function Hd(e,t,i=Wi()){const s=Pn(e,i);s!==""&&(vi(t,s,i),Zs(e,i))}function qd(e,t){return Te("bash",`${t===!0?`excluded from context
6
6
 
7
- `:""}$ ${e}`)}function Nd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Te("bash",t)];const o=Fd(s.text)?"":`
7
+ `:""}$ ${e}`)}function Kd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Te("bash",t)];const o=Gd(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function zd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Vd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
10
10
 
11
11
  `)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash command failed"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`full output: ${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
12
 
13
13
  ${o.join(`
14
- `)}`}]}]}function Fd(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function Gd(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function Bd(e,t){if(t.type==="message.append")return Yd(e,t.message);if(t.type==="assistant.delta")return md(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return vd(e,t.text);if(t.type==="tool.start")return Vd(e,t);if(t.type==="tool.update")return $n(e,t.toolCallId,i=>Gd(i,t));if(t.type==="tool.end")return kn(e,t.toolCallId,t.toolName,zt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,jd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Nd(e,t.chunk);if(t.type==="shell.end")return zd(e,t);if(t.type==="command.output")return[...e,Te(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Te("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Ud(e,t.message)}function Ud(e,t){const i=Qd(t);if(i!==void 0)return kn(e,i.toolCallId,i.toolName,zt(i.content),i.text,i.isError,i.content,i.details);const s=Ks(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?qd(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Hd(r,n),e)}function Hd(e,t){const i=Zd(e,t);if(i>=0)return[...e.slice(0,i),t,...e.slice(i+1)];const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Xd(s,t)?[...e.slice(0,-1),t]:[...e,t]}function qd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Kd(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 Vd(e,t){const i=t.toolName==="read"?Kd(Ze(t.args,"path")):void 0;if(i!==void 0)return ep(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||zt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function Gd(e,t){const i=ui(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 kn(e,t,i,s,o,r,n,a){const c=$n(e,t,h=>{const f=ui(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=ui(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function $n(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Qd(e){if(Ze(e,"role")!=="toolResult")return;const t=Ze(e,"toolCallId"),i=bi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Ze(e,"toolName")??"tool",text:Pn(i),isError:ip(e,"isError")===!0,content:i,details:bi(e,"details")}}function Pn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Pn).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=Ze(e,"text")??Ze(e,"content")??Ze(e,"output");if(t!==void 0)return t}return""}function Zd(e,t){const i=vi(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o?.role!=="skill")continue;const r=vi(o);if(Rn(r,i))return s}return-1}function vi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Rn(e,t){return e.length===t.length&&e.every((i,s)=>Jd(i,t[s]))}function Jd(e,t){return t===void 0?!1:Go(e.path)===Go(t.path)||e.name===t.name}function Go(e){return e.replace(/\\/g,"/")}function Xd(e,t){return Qo(e)===Qo(t)}function Qo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function Qd(e,t){if(t.type==="message.append")return cp(e,t.message);if(t.type==="assistant.delta")return kd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return $d(e,t.text);if(t.type==="tool.start")return ep(e,t);if(t.type==="tool.update")return In(e,t.toolCallId,i=>tp(i,t));if(t.type==="tool.end")return Rn(e,t.toolCallId,t.toolName,Ft(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,qd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Kd(e,t.chunk);if(t.type==="shell.end")return Vd(e,t);if(t.type==="command.output")return[...e,Te(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Te("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Zd(e,t.message)}function Zd(e,t){const i=ip(t);if(i!==void 0)return Rn(e,i.toolCallId,i.toolName,Ft(i.content),i.text,i.isError,i.content,i.details);const s=Gs(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Xd(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Jd(r,n),e)}function Jd(e,t){const i=sp(e,t);if(i.length>0)return op(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||lp(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Xd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Yd(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 ep(e,t){const i=t.toolName==="read"?Yd(Je(t.args,"path")):void 0;if(i!==void 0)return dp(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Ft(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function tp(e,t){const i=fi(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 Rn(e,t,i,s,o,r,n,a){const c=In(e,t,h=>{const f=fi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=fi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function In(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function ip(e){if(Je(e,"role")!=="toolResult")return;const t=Je(e,"toolCallId"),i=wi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Je(e,"toolName")??"tool",text:Cn(i),isError:fp(e,"isError")===!0,content:i,details:wi(e,"details")}}function Cn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Cn).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=Je(e,"text")??Je(e,"content")??Je(e,"output");if(t!==void 0)return t}return""}function sp(e,t){const i=bi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=An(e)+1;for(let n=e.length-1;n>=r;n--){const a=bi(e[n]);if(a.length===0)continue;const c=o-a.length;if(!(c<0)&&ap(a,i.slice(c,o))&&(s.unshift(n),o=c,o===0))return s}return[]}function op(e,t,i){const s=rp(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const c=e[a];c!==void 0&&!r.has(a)&&n.push(c)}return n}function rp(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return np(e[o])?[o,...t]:t}function np(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function bi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function ap(e,t){return e.length===t.length&&e.every((i,s)=>Mn(i,t[s]))}function Mn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Jo(e.path)===Jo(t.path)||e.name===t.name}function Jo(e){return e.replace(/\\/g,"/")}function lp(e,t){return Xo(e)===Xo(t)}function Xo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function Yd(e,t){const i=Ks(t);return i.length===0?e:[...e,...i]}function ep(e,t){const i=e.at(-1);return t.role==="skill"&&Rn(vi(i),vi(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function tp(e){return typeof e=="object"&&e!==null}function bi(e,t){return tp(e)?e[t]:void 0}function Ze(e,t){const i=bi(e,t);return typeof i=="string"?i:void 0}function ip(e,t){const i=bi(e,t);return typeof i=="boolean"?i:void 0}const sp="pi-web:chat-history:v2:",op=1800*1e3;function rp(e){try{const t=sessionStorage.getItem(wi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!pp(i))return;if(Date.now()-i.savedAt>op){sessionStorage.removeItem(wi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function np(e,t){try{sessionStorage.setItem(wi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function ap(e){try{sessionStorage.removeItem(wi(e))}catch{}}function lp(e,t){if(e===void 0||!Ss(e))return t;if(!Ss(t))return e;if(cp(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),o=new Array(s-i);return Zo(o,i,e),Zo(o,i,t),dp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function cp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function dp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Zo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function wi(e){return`${sp}${e}`}function pp(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:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&Ss({messages:t,start:i,total:s})}function Ss(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(hp)}function hp(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 up={read:rp,write:np,remove:ap};class fp{constructor(t=up){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Jo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=lp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Jo(s)}applyLiveEvent(t,i){return Bd(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Jo(e){const t=e?.start??0;return{messages:gd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Cn(e,t=e.length){const i=e.slice(0,t),s=gp(i,t);if(s!==void 0)return s;const o=mp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
- `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function In(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function gp(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-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function mp(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),o=Xo(s,"@ "),r=Xo(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function Xo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||vp(e[i-1]))return i;return-1}function vp(e){return e===" "||e===" "}function Qs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:wp(e).startsWith("/")?{kind:"command"}:Cn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function bp(e){return Qs(e).kind==="shell"}function wp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class yp{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=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),Tn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Kc(this.session,this.machineId);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 Mn(t);Sp(i)&&this.onEvent?.(i)}}class Yo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Tn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Vc(this.machineId);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 Mn(t);kp(i)&&this.onEvent?.(i)}}function Sp(e){const t=Zs(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","session.created","pi.event"].includes(t)}function xp(e){const t=Zs(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function kp(e){const t=Zs(e);return xp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Zs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Mn(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 Tn(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()}}function Ft(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Wi{constructor(t,i,s=Ft()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of $p(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Js(e){return typeof e=="string"&&e!==""?e:void 0}function $p(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!Pp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function Pp(e){return!Rp(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function Rp(e){return typeof e=="object"&&e!==null}class Cp{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)}}const Ip="pi-web:session-selection:v1";class Mp{constructor(t=Ft()){this.sessionIdsByCwd=new Wi(Ip,Js,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Tp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Ep(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function Ap(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Ep(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Dp(e,t,i){return xs(e,[t],i)}function xs(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Wp(e,t,i){return ks(e,t,[i])}function ks(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const St=100;class _p{constructor(t,i,s,o=new Cp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new yp,this.api=r.api??L,this.transcripts=r.transcripts??new fp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Ap(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);qo(s,i);const o=ys(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Tp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);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,{limit:St},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:St},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ee(t)&&Hp(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}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,{before:t.messagePageStart,limit:St},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&bp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=g(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(v=>In(v.path,!1)).join(" "),f=t===""?h:`${t}
19
+ `)}function cp(e,t){const i=Gs(t);return i.length===0?e:[...e,...i]}function dp(e,t){const i=e.at(-1);return pp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function pp(e,t){const i=bi(t);if(t.role!=="skill"||i.length===0)return!1;const s=An(e)+1;return i.every(o=>hp(e,o,s))}function hp(e,t,i){for(let s=e.length-1;s>=i;s--)if(bi(e[s]).some(o=>Mn(o,t)))return!0;return!1}function An(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function up(e){return typeof e=="object"&&e!==null}function wi(e,t){return up(e)?e[t]:void 0}function Je(e,t){const i=wi(e,t);return typeof i=="string"?i:void 0}function fp(e,t){const i=wi(e,t);return typeof i=="boolean"?i:void 0}const gp="pi-web:chat-history:v2:",mp=1800*1e3;function vp(e){try{const t=sessionStorage.getItem(yi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!kp(i))return;if(Date.now()-i.savedAt>mp){sessionStorage.removeItem(yi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function bp(e,t){try{sessionStorage.setItem(yi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function wp(e){try{sessionStorage.removeItem(yi(e))}catch{}}function yp(e,t){if(e===void 0||!ks(e))return t;if(!ks(t))return e;if(Sp(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),o=new Array(s-i);return Yo(o,i,e),Yo(o,i,t),xp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Sp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function xp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Yo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function yi(e){return`${gp}${e}`}function kp(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:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&ks({messages:t,start:i,total:s})}function ks(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($p)}function $p(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 Pp={read:vp,write:bp,remove:wp};class Rp{constructor(t=Pp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return er(this.rawHistoryPage(t))}mergeHistory(t,i){const s=yp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),er(s)}applyLiveEvent(t,i){return Qd(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function er(e){const t=e?.start??0;return{messages:xd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Tn(e,t=e.length){const i=e.slice(0,t),s=Ip(i,t);if(s!==void 0)return s;const o=Cp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function En(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Ip(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-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Cp(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),o=tr(s,"@ "),r=tr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function tr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Mp(e[i-1]))return i;return-1}function Mp(e){return e===" "||e===" "}function Js(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Tp(e).startsWith("/")?{kind:"command"}:Tn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Ap(e){return Js(e).kind==="shell"}function Tp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class Ep{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=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),Wn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Yc(this.session,this.machineId);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 Dn(t);Dp(i)&&this.onEvent?.(i)}}class ir{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Wn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=ed(this.machineId);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 Dn(t);_p(i)&&this.onEvent?.(i)}}function Dp(e){const t=Xs(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","session.created","pi.event"].includes(t)}function Wp(e){const t=Xs(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function _p(e){const t=Xs(e);return Wp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Xs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Dn(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 Wn(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()}}function Bt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class _i{constructor(t,i,s=Bt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of Op(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Ys(e){return typeof e=="string"&&e!==""?e:void 0}function Op(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!Lp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function Lp(e){return!jp(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function jp(e){return typeof e=="object"&&e!==null}class Np{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)}}const zp="pi-web:session-selection:v1";class Fp{constructor(t=Bt()){this.sessionIdsByCwd=new _i(zp,Ys,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Bp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Hp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function Up(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Hp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function qp(e,t,i){return $s(e,[t],i)}function $s(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Kp(e,t,i){return Ps(e,t,[i])}function Ps(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const $t=100;class Vp{constructor(t,i,s,o=new Np,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Ep,this.api=r.api??j,this.transcripts=r.transcripts??new Rp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Up(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Go(s,i);const o=xs(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Bp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);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,{limit:$t},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:$t},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ee(t)&&ih(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}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,{before:t.messagePageStart,limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Ap(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=g(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(v=>En(v.path,!1)).join(" "),f=t===""?h:`${t}
23
23
 
24
- ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:An(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Te("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=Dp(i.sessions,t.id,new Date().toISOString()),o=Wp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ee(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=xs(o.sessions,s,new Date().toISOString()),n=ks(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=er(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=tr(o);if(r.length>0){const n=this.getState(),a=xs(n.sessions,r,new Date().toISOString()),c=ks(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=er(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!_t(o,pt.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=tr(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Ko(t.id,g(this.getState())),Gs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.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,g(this.getState()));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 reloadSession(t=this.getState().selectedSession){if(t===void 0||ee(t)||t.archived===!0)return;const i=g(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!_t(s,pt.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));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,g(this.getState()))).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,t,i,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState()))),await this.refreshAvailableThinkingLevels()}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,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}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,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}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,o]=await Promise.all([this.api.messages(i,{limit:St},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=Lp(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Sn(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}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=g(this.getState()),o=await this.api.startSession(t.cwd,s);qo(o,s),Ld(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Ko(t.id,s);const r=ys(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.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){if(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(dd(i))}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,Te(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&mi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Fp(i,t.sessionId,t.messageCount),...s?{sessionActivities:Op(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}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(Bp(t))return}if(Up(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)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:St},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Op(e,t){return An(e,t)}function An(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function er(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function tr(e){return e.filter(jp).map(t=>t.value)}function Lp(e){return e.filter(Np).map(t=>zp(t.reason))}function jp(e){return e.status==="fulfilled"}function Np(e){return e.status==="rejected"}function zp(e){return e instanceof Error?e.message:String(e)}function Fp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function Bp(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 Up(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Hp(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class qp{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)}}const Kp="pi-web:workspace-selection:v1";class Vp{constructor(t=Ft()){this.workspaceIdsByProject=new Wi(Kp,Js,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Gp(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Qp{constructor(t,i,s,o,r=new qp,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??L}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...si()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Vi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...si()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Gp(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Vi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Vi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...si()});try{const o=cd(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Jp(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Zp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Jp(e){return e.find(t=>t.isMain)??e[0]}const Xp="pi-web:machine-navigation:v1";class Yp{constructor(t=Ft()){this.snapshotsByMachine=new Wi(Xp,th,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?or(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,or(t))}forget(t){this.snapshotsByMachine.delete(t)}}function eh(e){return{machineId:e,surface:{}}}function ir(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??yn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function sr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function or(e){return{...e,surface:{...e.surface}}}function th(e){if(!Dn(e))return;const t=Oe(e,"machineId");if(t===void 0)return;const i=En(Oe(e,"tool")),s=sh(Oe(e,"view"));return{machineId:t,projectId:Oe(e,"projectId"),workspaceId:Oe(e,"workspaceId"),sessionId:Oe(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:ih(e.surface)}}function ih(e){return Dn(e)?{selectedFilePath:Oe(e,"selectedFilePath"),selectedDiffPath:Oe(e,"selectedDiffPath"),selectedTerminalId:Oe(e,"selectedTerminalId")}:{}}function sh(e){return e==="navigation"||e==="chat"?e:En(e)}function En(e){return oh(e)?e:void 0}function oh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Oe(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Dn(e){return typeof e=="object"&&e!==null}const rh="pi-web:terminal-selection:v1";class nh{constructor(t=Ft()){this.terminalIdsByCwd=new Wi(rh,Js,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function dw(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function pw(e){return e.find(t=>!t.exited)??e[0]}const Wn=1200,ah=["mod","alt","shift"];class lh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=On(t);if(o===void 0)return!1;const r=Xs(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Ot(o))return!1}else if(!Ot(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>bh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Ys(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Wn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Xs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=ch(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort($s)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(hh),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=uh(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:rr(u),v=h?[...a.get(p)??[]].sort($s).map(rr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Ji(e){return Ln(e,{requireFirstChordActivator:!0})}function _n(e){const t=Ln(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ri(e){return _n(e).map(t=>t.split("+").map(Nn).join("+")).join(" ")}function On(e){if(e.isComposing)return;const t=mh(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 Ot(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function ch(e,t,i){const s=dh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=_n(o),n=r[0];if(!(n===void 0||!Ot(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:ph(r),order:i}}function dh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function ph(e){return e.join("\0")}function rr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function $s(e,t){return nr(e.source)-nr(t.source)||ar(e.action.id,t.action.id)||ar(e.action.title,t.action.title)||e.order-t.order}function hh(e,t){return e.tokens.length-t.tokens.length||$s(e,t)}function uh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Ys(e.tokens,i.tokens))}function nr(e){switch(e){case"custom":return 0;case"default":return 1}}function ar(e,t){return e<t?-1:e>t?1:0}function Ln(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=fh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Ot(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function fh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=gh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Nn(n)} modifiers.`};i.add(n);continue}const a=jn(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...ah.filter(r=>i.has(r)),s].join("+")}}function gh(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function jn(e){const t=vh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function mh(e){if(e===" ")return"space";const t=e.toLowerCase();return jn(t)}function vh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Nn(e){return e==="mod"?lr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?lr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function bh(e,t){return e.length===t.length&&Ys(e,t)}function Ys(e,t){return t.every((i,s)=>e[s]===i)}function lr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const eo="themes:classic",wh="themes:pi-web-dark",yh={themeId:wh,auto:!0},zn="pi-web-app-theme",Sh=["--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"],xh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function kh(){try{const e=window.localStorage.getItem(zn);return e===null?void 0:Ih(e)}catch{return}}function $h(e){try{window.localStorage.setItem(zn,JSON.stringify(e))}catch{}}function Ph(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Sh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Rh(e){const t=Ch(e.themes,e.fallbackThemeId??eo),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=Fn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function Ch(e,t=eo){return e.find(i=>i.id===t)??e[0]}function Fn(e,t){return e.find(i=>i.light===t||i.dark===t)}function Ih(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Mh(i)?i:void 0}catch{return}}function Mh(e){if(!Th(e))return!1;const t=e.themeId,i=e.auto;return Ah(t)&&typeof i=="boolean"}function Th(e){return typeof e=="object"&&e!==null}function Ah(e){return typeof e=="string"&&xh.test(e)}const Eh="workspace.delete",Dh="pi.operation",Wh="target.workspaceId";function _h(e){return{...e===void 0?{}:{projectId:e},metadata:{[Dh]:Eh}}}function Oh(e){const t={};for(const i of e){const s=Ps(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function Lh(e){return Object.entries(e).filter(([,t])=>yi(t)).map(([t])=>t)}function Bn(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&yi(i)}function Ps(e){return e.metadata[Wh]}function yi(e){return e.status==="queued"||e.status==="running"}function jh(){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",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{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:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:xt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:cr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:xt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:xt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:cr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:xt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Nh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:xt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:zh,run:e=>e.archiveSession()},{id:"session.reload",title:"Reload Session",description:"Re-read the selected session from disk to pick up entries written by another process",group:"Session",enabled:Bh,run:e=>e.reloadSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Fh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function xt(e){return e.state.selectedWorkspace!==void 0}function cr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Nh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Bn(e.state,t)}function zh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function Fh(e){return ee(e.state.selectedSession)}function Bh(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[g(e.state)];return i?.ok!==!0||!_t(i,pt.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const Uh="modulepreload",Hh=function(e){return"/"+e},dr={},Un=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Hh(p),p in dr)return;dr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Uh,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},qh=10*1024*1024,Kh="10 MB";function Vh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ni(e)}function ni(e){switch(e){case"navigation":return he`
24
+ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:_n(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Te("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=qp(i.sessions,t.id,new Date().toISOString()),o=Kp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ee(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=$s(o.sessions,s,new Date().toISOString()),n=Ps(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=sr(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=or(o);if(r.length>0){const n=this.getState(),a=$s(n.sessions,r,new Date().toISOString()),c=Ps(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=sr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!ht(o,Ze.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=or(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Qo(t.id,g(this.getState())),Zs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.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,g(this.getState()));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 reloadSession(t=this.getState().selectedSession){if(t===void 0||ee(t)||t.archived===!0)return;const i=g(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!ht(s,Ze.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));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,g(this.getState()))).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,t,i,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState()))),await this.refreshAvailableThinkingLevels()}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,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}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,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}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,o]=await Promise.all([this.api.messages(i,{limit:$t},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=Qp(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return $n(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}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=g(this.getState()),o=await this.api.startSession(t.cwd,s);Go(o,s),Hd(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Qo(t.id,s);const r=xs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.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){if(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(vd(i))}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,Te(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&vi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ye(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Yp(i,t.sessionId,t.messageCount),...s?{sessionActivities:Gp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}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(eh(t))return}if(th(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)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Gp(e,t){return _n(e,t)}function _n(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function sr(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function or(e){return e.filter(Zp).map(t=>t.value)}function Qp(e){return e.filter(Jp).map(t=>Xp(t.reason))}function Zp(e){return e.status==="fulfilled"}function Jp(e){return e.status==="rejected"}function Xp(e){return e instanceof Error?e.message:String(e)}function Yp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function eh(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 th(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function ih(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class sh{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)}}const oh="pi-web:workspace-selection:v1";class rh{constructor(t=Bt()){this.workspaceIdsByProject=new _i(oh,Ys,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function nh(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class ah{constructor(t,i,s,o,r=new sh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??j}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...oi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Gi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...oi()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=nh(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Gi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Gi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...oi()});try{const o=md(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=ch(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function lh(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function ch(e){return e.find(t=>t.isMain)??e[0]}const dh="pi-web:machine-navigation:v1";class ph{constructor(t=Bt()){this.snapshotsByMachine=new _i(dh,uh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?ar(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,ar(t))}forget(t){this.snapshotsByMachine.delete(t)}}function hh(e){return{machineId:e,surface:{}}}function rr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??kn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function nr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function ar(e){return{...e,surface:{...e.surface}}}function uh(e){if(!Ln(e))return;const t=Oe(e,"machineId");if(t===void 0)return;const i=On(Oe(e,"tool")),s=gh(Oe(e,"view"));return{machineId:t,projectId:Oe(e,"projectId"),workspaceId:Oe(e,"workspaceId"),sessionId:Oe(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:fh(e.surface)}}function fh(e){return Ln(e)?{selectedFilePath:Oe(e,"selectedFilePath"),selectedDiffPath:Oe(e,"selectedDiffPath"),selectedTerminalId:Oe(e,"selectedTerminalId")}:{}}function gh(e){return e==="navigation"||e==="chat"?e:On(e)}function On(e){return mh(e)?e:void 0}function mh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Oe(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Ln(e){return typeof e=="object"&&e!==null}const vh="pi-web:terminal-selection:v1";class bh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(vh,Ys,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Pw(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Rw(e){return e.find(t=>!t.exited)??e[0]}const jn=1200,wh=["mod","alt","shift"];class yh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=zn(t);if(o===void 0)return!1;const r=eo(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Lt(o))return!1}else if(!Lt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Ah(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>to(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},jn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function eo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Sh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(Rs)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort($h),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Ph(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:lr(u),v=h?[...a.get(p)??[]].sort(Rs).map(lr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Xi(e){return Fn(e,{requireFirstChordActivator:!0})}function Nn(e){const t=Fn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ni(e){return Nn(e).map(t=>t.split("+").map(Un).join("+")).join(" ")}function zn(e){if(e.isComposing)return;const t=Ch(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 Lt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Sh(e,t,i){const s=xh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Nn(o),n=r[0];if(!(n===void 0||!Lt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:kh(r),order:i}}function xh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function kh(e){return e.join("\0")}function lr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Rs(e,t){return cr(e.source)-cr(t.source)||dr(e.action.id,t.action.id)||dr(e.action.title,t.action.title)||e.order-t.order}function $h(e,t){return e.tokens.length-t.tokens.length||Rs(e,t)}function Ph(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&to(e.tokens,i.tokens))}function cr(e){switch(e){case"custom":return 0;case"default":return 1}}function dr(e,t){return e<t?-1:e>t?1:0}function Fn(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Rh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Rh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=Ih(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Un(n)} modifiers.`};i.add(n);continue}const a=Bn(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...wh.filter(r=>i.has(r)),s].join("+")}}function Ih(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function Bn(e){const t=Mh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Ch(e){if(e===" ")return"space";const t=e.toLowerCase();return Bn(t)}function Mh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Un(e){return e==="mod"?pr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?pr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Ah(e,t){return e.length===t.length&&to(e,t)}function to(e,t){return t.every((i,s)=>e[s]===i)}function pr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const io="themes:classic",Th="themes:pi-web-dark",Eh={themeId:Th,auto:!0},Hn="pi-web-app-theme",Dh=["--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"],Wh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function _h(){try{const e=window.localStorage.getItem(Hn);return e===null?void 0:zh(e)}catch{return}}function Oh(e){try{window.localStorage.setItem(Hn,JSON.stringify(e))}catch{}}function Lh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Dh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function jh(e){const t=Nh(e.themes,e.fallbackThemeId??io),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=qn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function Nh(e,t=io){return e.find(i=>i.id===t)??e[0]}function qn(e,t){return e.find(i=>i.light===t||i.dark===t)}function zh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Fh(i)?i:void 0}catch{return}}function Fh(e){if(!Bh(e))return!1;const t=e.themeId,i=e.auto;return Uh(t)&&typeof i=="boolean"}function Bh(e){return typeof e=="object"&&e!==null}function Uh(e){return typeof e=="string"&&Wh.test(e)}const Hh="workspace.delete",qh="pi.operation",Kh="target.workspaceId";function Vh(e){return{...e===void 0?{}:{projectId:e},metadata:{[qh]:Hh}}}function Gh(e){const t={};for(const i of e){const s=Is(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function Qh(e){return Object.entries(e).filter(([,t])=>Si(t)).map(([t])=>t)}function Kn(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&Si(i)}function Is(e){return e.metadata[Kh]}function Si(e){return e.status==="queued"||e.status==="running"}function Zh(){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",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{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:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:hr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Pt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:hr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Pt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Jh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Pt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Xh,run:e=>e.archiveSession()},{id:"session.reload",title:"Reload Session",description:"Re-read the selected session from disk to pick up entries written by another process",group:"Session",enabled:eu,run:e=>e.reloadSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Yh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ye(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Pt(e){return e.state.selectedWorkspace!==void 0}function hr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Jh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Kn(e.state,t)}function Xh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function Yh(e){return ee(e.state.selectedSession)}function eu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[g(e.state)];return i?.ok!==!0||!ht(i,Ze.sessionsReload)?!1:!Ye(e.state.status,e.state.activity)}const tu="modulepreload",iu=function(e){return"/"+e},ur={},Vn=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=iu(p),p in ur)return;ur[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":tu,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},su=10*1024*1024,ou="10 MB";function ru(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ai(e)}function ai(e){switch(e){case"navigation":return he`
25
25
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
26
26
  <circle cx="6" cy="7" r="1.5"></circle>
27
27
  <path d="M10 7h8"></path>
@@ -55,7 +55,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
55
55
  <path d="m7 10 3 3-3 3"></path>
56
56
  <path d="M12 16h5"></path>
57
57
  </svg>
58
- `}}function Gh(){return[{id:"workspace.files",title:"Files",icon:ni("files"),order:10,render:Qh},{id:"workspace.git",title:"Git",icon:ni("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:eu},{id:"workspace.terminal",title:"Terminal",icon:ni("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Yh}]}function Qh(e){return l`
58
+ `}}function nu(){return[{id:"workspace.files",title:"Files",icon:ai("files"),order:10,render:au},{id:"workspace.git",title:"Git",icon:ai("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:hu},{id:"workspace.terminal",title:"Terminal",icon:ai("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:pu}]}function au(e){return l`
59
59
  <section class="toolbar">
60
60
  <strong>Files</strong>
61
61
  ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
@@ -63,30 +63,30 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
63
63
  </section>
64
64
  <section class="split">
65
65
  <div class="list tree">
66
- ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Hn(e,t,0))}
66
+ ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Gn(e,t,0))}
67
67
  </div>
68
68
  <div class="viewer">
69
- ${Jh(e)}
69
+ ${cu(e)}
70
70
  </div>
71
71
  </section>
72
- `}function Hn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
73
- <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Zh(e,t)}}>
72
+ `}function Gn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
73
+ <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{lu(e,t)}}>
74
74
  <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
75
75
  <span>${t.name}</span>
76
76
  </button>
77
- ${o?s.map(n=>Hn(e,n,i+1)):null}
78
- `}function Zh(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function Jh(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Xh(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${Rs(t.size)}</p>`:(qn(),l`
77
+ ${o?s.map(n=>Gn(e,n,i+1)):null}
78
+ `}function lu(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function cu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?du(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${Cs(t.size)}</p>`:(Qn(),l`
79
79
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
80
80
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
81
- `)}function Xh(e,t){const i=`${t.mimeType??"image"} · ${Rs(t.size)}`;if(t.size>qh)return l`
81
+ `)}function du(e,t){const i=`${t.mimeType??"image"} · ${Cs(t.size)}`;if(t.size>su)return l`
82
82
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
83
- <p class="muted">Image too large to preview: ${Rs(t.size)} · limit ${Kh}</p>
84
- `;const s=Wc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
83
+ <p class="muted">Image too large to preview: ${Cs(t.size)} · limit ${ou}</p>
84
+ `;const s=Fc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
85
85
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
86
86
  <div class="image-preview">
87
87
  <img src=${s} alt=${t.path} decoding="async" />
88
88
  </div>
89
- `}function Yh(e){return su(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function eu(e){const t=e.gitStatus;return l`
89
+ `}function pu(e){return gu(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function hu(e){const t=e.gitStatus;return l`
90
90
  <section class="toolbar">
91
91
  <strong>Git</strong>
92
92
  ${e.gitStale?l`<span class="stale">stale</span>`:null}
@@ -95,29 +95,29 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
95
95
  <section class="split">
96
96
  <div class="list">
97
97
  ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
98
- <p class="summary">${ou(t)}</p>
98
+ <p class="summary">${mu(t)}</p>
99
99
  ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
100
100
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
101
- <span>${ru(i.index,i.workingTree)}</span>
101
+ <span>${vu(i.index,i.workingTree)}</span>
102
102
  <span>${i.path}</span>
103
103
  </button>
104
104
  `)}
105
105
  `:l`<p class="muted">Not a git repository.</p>`}
106
106
  </div>
107
107
  <div class="viewer">
108
- ${tu(e)}
108
+ ${uu(e)}
109
109
  </div>
110
110
  </section>
111
- `}function tu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
111
+ `}function uu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
112
112
  <div class=${s.length===1?"diffs single":"diffs"}>
113
- ${s.map(o=>iu(o))}
113
+ ${s.map(o=>fu(o))}
114
114
  </div>
115
- `}function iu(e){return qn(),l`
115
+ `}function fu(e){return Qn(),l`
116
116
  <section class="diff-section">
117
117
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
118
118
  <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
119
119
  </section>
120
- `}function qn(){Un(()=>import("./CodeViewer-CIG4PxA9.js"),__vite__mapDeps([0,1,2,3]))}function su(){Un(()=>import("./TerminalPanel-CKtvS-3H.js"),__vite__mapDeps([4,5,6,1,2]))}function ou(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 ru(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Rs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Xi(t)} KB`;const i=t/1024;return i<1024?`${Xi(i)} MB`:`${Xi(i/1024)} GB`}function Xi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const nu={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:jh(),workspacePanels:Gh()}})},au={"--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"},lu={"--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":"#5a47b0","--pi-selection-bg":"#1d2547","--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"},cu={"--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"},du={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:lu},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:cu},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:au}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},pu=/^[a-z][a-z0-9.-]*$/u;function hu(e){return pu.test(e)}const uu="machine.";function fu(e,t){if(e==="")throw new Error("Machine id is required");if(!hu(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${uu}${gu(e)}.${t}`}function gu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function pr(e="/pi-web-plugins/manifest.json",t={}){const i=await mu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=wu(n,r);s.push({id:t.machineId===void 0?o.id:fu(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function mu(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 vu(await t.json())}}function vu(e){if(!Si(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Si(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,machineSpecific:bu(t.machineSpecific)}})}}function bu(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function wu(e,t){if(!Si(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!yu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function yu(e){return Si(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Si(e){return typeof e=="object"&&e!==null}const Su=/^[a-z][a-z0-9.-]*$/u,xu=/^[a-z][a-z0-9.-]*$/u,Kn=new WeakMap,Vn=new WeakMap;class ku{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&Cu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Mu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=$u(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}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))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(Yi(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(Yi(c,t)):void 0},render:c=>i.render(Yi(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}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}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Su.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!xu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${Iu(i)}`);return i}}function $u(e,t){return Kn.get(e)?.(t)??e}function Yi(e,t){return Vn.get(e)?.(t)??e}function Pu(e,t){return Kn.set(e,t),e}function Ru(e,t){return Vn.set(e,t),e}function Cu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function Iu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Mu(e){return e.state.selectedMachine?.id??"local"}const Tu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Au(){return typeof window>"u"||!("matchMedia"in window)?[]:Tu.map(e=>window.matchMedia(e))}function hr(e,t=Eu()){return e.some(i=>i.matches)||Du(t)}function Eu(){return typeof navigator>"u"?void 0:navigator}function Du(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Wu=250;class _u{constructor(t=Ou()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},Wu)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Ou(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Lu="(max-width: 760px)";class ju{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=hr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Nu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Au(),this.viewportPositionRepairer=i.viewportPositionRepairer??new _u,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=hr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Nu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Lu)}const xi=["machines","projects","workspaces","sessions"];function zu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function to(e,t){if(e!=="none")return e??zu(t)}function Fu(e,t){return t.isMobileLayout?to(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Bu(e,t,i){return to(e,i.state)===t?"none":t}function Uu(e,t,i){return i?t:e}function Hu(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Vu(i)}function qu(e){return xi[xi.indexOf(e)+1]}class Ku{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return to(this.expanded,this.getState())}isCollapsed(t){return Fu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Bu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Hu(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Uu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=qu(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Gu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Vu(e){const t=new Set(e);return xi.filter(i=>t.has(i))}function Gu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Qu{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Gn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Gn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Cs="pi-web:panel-sizes:v1",Zu={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Ju{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??io(),this.panelSizes=tf(this.storage)}hostConnected(){}constraints(t){return Bt(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=rf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=nf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){sf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${fr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${fr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Bt(e){return Zu[e]}function Xu(e,t,i){return e==="navigation"?i-t:t-i}function Yu(e,t,i,s,o=Bt(e)){return ue(e,t+Xu(e,i,s),o)}function ef(e,t,i,s={}){const o=s.constraints??Bt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=af(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Bt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function tf(e=io()){try{const t=e?.getItem(Cs);if(t==null||t==="")return{};const i=JSON.parse(t);return of(i)}catch{return{}}}function sf(e,t=io()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Cs);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(Cs,JSON.stringify(i))}catch{}}function of(e){if(!lf(e)||e.version!==1)return{};const t={},i=ur(e.navigationPanelWidth),s=ur(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function ur(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function rf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function nf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function af(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function fr(e){return`${String(Math.round(e))}px`}function io(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function lf(e){return typeof e=="object"&&e!==null}function gr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:cf(e.get("tool")),view:df(e.get("view"))}}function es(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),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}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function cf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Qn(e)?e:void 0}function df(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Qn(e)?e:void 0}function Qn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function mr(){return pf(new URLSearchParams(window.location.search).get("settings"))}function ts(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function pf(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function hf(e,t){return t===void 0?e:e.map(i=>ff(i,t))}function uf(e,t){const i=new Set(Xs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return hf(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Zn(s):s)}function ff(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Zn(e):{...e,shortcut:i}}function Zn(e){const t={...e};return delete t.shortcut,t}function gf(e,t){const i=t.api??ct,s=t.pollIntervalMs??1e3,o=t.setTimeout??vf(),r=t.clearTimeout??bf();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:mf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function mf(e,t,i,s,o){return vr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&vr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function vr(e){return e.status==="succeeded"||e.status==="failed"}function vf(){return(e,t)=>globalThis.setTimeout(e,t)}function bf(){return e=>{globalThis.clearTimeout(e)}}function wf(e,t){return t[e.path]}function yf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Sf(e,t,i){return Xn(xf(e,t,i))}function Jn(e){return Xn(Object.values(e??{}))}function Xn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function xf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Qt=0,kf=120;function Ut(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Yn():$f(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Qt,f=i.top-c-Qt;return[...h<kf&&f>h?[`bottom: ${at(r-i.top+Qt)};`,`max-height: ${at(Math.max(0,f))};`]:[`top: ${at(i.bottom+Qt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,o-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function $f(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Yn()}function Yn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function at(e){return`${String(Math.round(e))}px`}function ea(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function _i(e,t="Active"){const i=ea(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Pf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ta(e){return e.composedPath().some(t=>Rf(t,Pf))}function Rf(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 Oi(e,t){ta(e)||t()}function Li(e,t){return ta(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{br(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{br(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{wr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{wr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function ji(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function br(e,t){const i=sa(e),s=oa(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||ia(i,o+t)}function wr(e,t){const i=sa(e);i.length!==0&&ia(i,t<0?i.length-1:t)}function ia(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function sa(e){const t=oa(e)?.getRootNode();return t===void 0||!Cf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Cf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function oa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const If=_`
120
+ `}function Qn(){Vn(()=>import("./CodeViewer-Bv8l_MFi.js"),__vite__mapDeps([0,1,2,3]))}function gu(){Vn(()=>import("./TerminalPanel-BZKsaE9s.js"),__vite__mapDeps([4,5,6,1,2]))}function mu(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 vu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Cs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Yi(t)} KB`;const i=t/1024;return i<1024?`${Yi(i)} MB`:`${Yi(i/1024)} GB`}function Yi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const bu={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Zh(),workspacePanels:nu()}})},wu={"--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"},yu={"--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":"#5a47b0","--pi-selection-bg":"#1d2547","--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"},Su={"--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"},xu={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:yu},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Su},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:wu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ku=/^[a-z][a-z0-9.-]*$/u;function $u(e){return ku.test(e)}const Pu="machine.";function Ru(e,t){if(e==="")throw new Error("Machine id is required");if(!$u(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Pu}${Iu(e)}.${t}`}function Iu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function fr(e="/pi-web-plugins/manifest.json",t={}){const i=await Cu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=Tu(n,r);s.push({id:t.machineId===void 0?o.id:Ru(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function Cu(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 Mu(await t.json())}}function Mu(e){if(!xi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!xi(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,machineSpecific:Au(t.machineSpecific)}})}}function Au(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function Tu(e,t){if(!xi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Eu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Eu(e){return xi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function xi(e){return typeof e=="object"&&e!==null}const Du=/^[a-z][a-z0-9.-]*$/u,Wu=/^[a-z][a-z0-9.-]*$/u,Zn=new WeakMap,Jn=new WeakMap;class _u{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&Nu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Fu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=Ou(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}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))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(es(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(es(c,t)):void 0},render:c=>i.render(es(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}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}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Du.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Wu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${zu(i)}`);return i}}function Ou(e,t){return Zn.get(e)?.(t)??e}function es(e,t){return Jn.get(e)?.(t)??e}function Lu(e,t){return Zn.set(e,t),e}function ju(e,t){return Jn.set(e,t),e}function Nu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function zu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Fu(e){return e.state.selectedMachine?.id??"local"}const Bu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Uu(){return typeof window>"u"||!("matchMedia"in window)?[]:Bu.map(e=>window.matchMedia(e))}function gr(e,t=Hu()){return e.some(i=>i.matches)||qu(t)}function Hu(){return typeof navigator>"u"?void 0:navigator}function qu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Ku=250;class Vu{constructor(t=Gu()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},Ku)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Gu(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Qu="(max-width: 760px)";class Zu{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=gr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Ju(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Uu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Vu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=gr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Ju(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Qu)}const ki=["machines","projects","workspaces","sessions"];function Xu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function so(e,t){if(e!=="none")return e??Xu(t)}function Yu(e,t){return t.isMobileLayout?so(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function ef(e,t,i){return so(e,i.state)===t?"none":t}function tf(e,t,i){return i?t:e}function sf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),nf(i)}function of(e){return ki[ki.indexOf(e)+1]}class rf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return so(this.expanded,this.getState())}isCollapsed(t){return Yu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(ef(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(sf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(tf(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=of(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){af(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function nf(e){const t=new Set(e);return ki.filter(i=>t.has(i))}function af(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class lf{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Xn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Xn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ms="pi-web:panel-sizes:v1",cf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class df{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??oo(),this.panelSizes=ff(this.storage)}hostConnected(){}constraints(t){return Ut(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=vf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=bf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){gf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${vr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${vr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ut(e){return cf[e]}function pf(e,t,i){return e==="navigation"?i-t:t-i}function hf(e,t,i,s,o=Ut(e)){return ue(e,t+pf(e,i,s),o)}function uf(e,t,i,s={}){const o=s.constraints??Ut(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=wf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ut(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function ff(e=oo()){try{const t=e?.getItem(Ms);if(t==null||t==="")return{};const i=JSON.parse(t);return mf(i)}catch{return{}}}function gf(e,t=oo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ms);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(Ms,JSON.stringify(i))}catch{}}function mf(e){if(!yf(e)||e.version!==1)return{};const t={},i=mr(e.navigationPanelWidth),s=mr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function mr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function vf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function bf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function wf(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function vr(e){return`${String(Math.round(e))}px`}function oo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yf(e){return typeof e=="object"&&e!==null}function br(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Sf(e.get("tool")),view:xf(e.get("view"))}}function ts(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),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}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Sf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function xf(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function Yn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function wr(){return kf(new URLSearchParams(window.location.search).get("settings"))}function is(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function kf(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function $f(e,t){return t===void 0?e:e.map(i=>Rf(i,t))}function Pf(e,t){const i=new Set(eo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return $f(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ea(s):s)}function Rf(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ea(e):{...e,shortcut:i}}function ea(e){const t={...e};return delete t.shortcut,t}function If(e,t){const i=t.api??pt,s=t.pollIntervalMs??1e3,o=t.setTimeout??Mf(),r=t.clearTimeout??Af();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:Cf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Cf(e,t,i,s,o){return yr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&yr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function yr(e){return e.status==="succeeded"||e.status==="failed"}function Mf(){return(e,t)=>globalThis.setTimeout(e,t)}function Af(){return e=>{globalThis.clearTimeout(e)}}function Tf(e,t){return t[e.path]}function Ef(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Df(e,t,i){return ia(Wf(e,t,i))}function ta(e){return ia(Object.values(e??{}))}function ia(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Wf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Zt=0,_f=120;function Ht(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?sa():Of(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Zt,f=i.top-c-Zt;return[...h<_f&&f>h?[`bottom: ${lt(r-i.top+Zt)};`,`max-height: ${lt(Math.max(0,f))};`]:[`top: ${lt(i.bottom+Zt)};`,`max-height: ${lt(Math.max(0,h))};`],`right: ${lt(Math.max(0,o-u))};`,`max-width: ${lt(Math.max(0,u-n))};`].join(" ")}function Of(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():sa()}function sa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function lt(e){return`${String(Math.round(e))}px`}function oa(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Oi(e,t="Active"){const i=oa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Lf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ra(e){return e.composedPath().some(t=>jf(t,Lf))}function jf(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 Li(e,t){ra(e)||t()}function ji(e,t){return ra(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Sr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Sr(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{xr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{xr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function Ni(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Sr(e,t){const i=aa(e),s=la(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||na(i,o+t)}function xr(e,t){const i=aa(e);i.length!==0&&na(i,t<0?i.length-1:t)}function na(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function aa(e){const t=la(e)?.getRootNode();return t===void 0||!Nf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Nf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function la(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const zf=O`
121
121
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
122
122
  :host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
123
123
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -215,7 +215,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
215
215
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
216
216
  .empty { margin: auto; color: var(--pi-muted); }
217
217
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
218
- `,Mf=_`
218
+ `,Ff=O`
219
219
  :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
220
220
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
221
221
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -270,7 +270,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
270
270
  .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
271
271
  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; }
272
272
  p { margin: 10px; }
273
- `,Ni=_`
273
+ `,zi=O`
274
274
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
275
275
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
276
276
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -331,7 +331,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
331
331
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
332
332
  .workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
333
333
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
334
- `,Tf=_`
334
+ `,Bf=O`
335
335
  :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
336
336
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
337
337
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -419,7 +419,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
419
419
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
420
420
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
421
421
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
422
- `,Af=_`
422
+ `,Uf=O`
423
423
  :host { display: block; }
424
424
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
425
425
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -444,7 +444,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
444
444
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
445
445
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
446
446
  th { background: var(--pi-surface); }
447
- `,Ef=_`
447
+ `,Hf=O`
448
448
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
449
449
  .bar { display: flex; justify-content: flex-end; 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; }
450
450
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -454,7 +454,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
454
454
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
455
455
  .muted { color: var(--pi-dim); }
456
456
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
457
- `,Df=_`
457
+ `,qf=O`
458
458
  :host { display: block; }
459
459
  .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); }
460
460
  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; }
@@ -462,7 +462,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
462
462
  button.selected, button:hover { background: var(--pi-selection-bg); }
463
463
  span { color: var(--pi-muted); font-size: 12px; }
464
464
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
465
- `,ra=_`
465
+ `,ca=O`
466
466
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
467
467
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
468
468
  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; }
@@ -476,7 +476,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
476
476
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
477
477
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
478
478
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
479
- `,Wf=_`
479
+ `,Kf=O`
480
480
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
481
481
  .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; }
482
482
  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; }
@@ -494,7 +494,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
494
494
  .group { grid-column: 1 / -1; font-size: 12px; }
495
495
  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; }
496
496
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
497
- `,_f=_`
497
+ `,Vf=O`
498
498
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
499
499
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
500
500
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -542,7 +542,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
542
542
  button { padding: 5px 7px; }
543
543
  .icon-button { width: 34px; height: 34px; }
544
544
  }
545
- `;var Of=Object.defineProperty,Lf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Lf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Of(t,i,o),o};let J=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,ji(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
545
+ `;var Gf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Gf(t,i,o),o};let J=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
546
546
  <section>
547
547
  <h2>${this.renderHeading()}</h2>
548
548
  ${this.collapsed?null:l`
@@ -551,12 +551,12 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
551
551
  </div>
552
552
  `}
553
553
  </section>
554
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=na(e)&&this.onRemove!==void 0;return l`
554
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=da(e)&&this.onRemove!==void 0;return l`
555
555
  <div
556
556
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
557
557
  tabindex="0"
558
558
  title=${e.baseUrl??e.name}
559
- @click=${o=>{Oi(o,()=>this.onSelect?.(e))}}
559
+ @click=${o=>{Li(o,()=>this.onSelect?.(e))}}
560
560
  @keydown=${o=>{this.handleMachineKeydown(o,e)}}
561
561
  >
562
562
  <div class="action-main">
@@ -565,7 +565,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
565
565
  </div>
566
566
  ${s?this.renderMachineMenu(e):null}
567
567
  </div>
568
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Jn(this.activities[e.id]);return _i(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=jf(e.id);return l`
568
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return Oi(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=Zf(e.id);return l`
569
569
  <div class="action-menu">
570
570
  <button
571
571
  class="action-menu-toggle"
@@ -581,13 +581,13 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
581
581
  </div>
582
582
  `:null}
583
583
  </div>
584
- `}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ut(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Li(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[Ni,_`
584
+ `}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[zi,O`
585
585
  .machine-row.no-actions .action-main { border-radius: 8px; }
586
586
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
587
587
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
588
588
  .machine-menu-panel button.danger { color: var(--pi-danger); }
589
589
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
590
- `];ae([d({attribute:!1})],J.prototype,"machines",2);ae([d({attribute:!1})],J.prototype,"selected",2);ae([d({attribute:!1})],J.prototype,"statuses",2);ae([d({attribute:!1})],J.prototype,"activities",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([d({attribute:!1})],J.prototype,"onSelect",2);ae([d({attribute:!1})],J.prototype,"onRemove",2);ae([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ae([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ae([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);ae([b()],J.prototype,"openMenuMachineId",2);ae([b()],J.prototype,"menuStyle",2);J=ae([E("machine-list")],J);function na(e){return e.kind==="remote"}function jf(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Nf=Object.defineProperty,zf=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?zf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Nf(t,i,o),o};let G=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},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)}async focusSelectedOrFirst(){return await this.updateComplete,ji(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
590
+ `];ae([d({attribute:!1})],J.prototype,"machines",2);ae([d({attribute:!1})],J.prototype,"selected",2);ae([d({attribute:!1})],J.prototype,"statuses",2);ae([d({attribute:!1})],J.prototype,"activities",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([d({attribute:!1})],J.prototype,"onSelect",2);ae([d({attribute:!1})],J.prototype,"onRemove",2);ae([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ae([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ae([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);ae([w()],J.prototype,"openMenuMachineId",2);ae([w()],J.prototype,"menuStyle",2);J=ae([D("machine-list")],J);function da(e){return e.kind==="remote"}function Zf(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Jf=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Jf(t,i,o),o};let G=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},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)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
591
591
  <section>
592
592
  <h2>${this.renderHeading()}</h2>
593
593
  ${this.collapsed?null:l`
@@ -597,7 +597,7 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
597
597
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
598
598
  tabindex="0"
599
599
  title=${e.path}
600
- @click=${t=>{Oi(t,()=>this.onSelect?.(e))}}
600
+ @click=${t=>{Li(t,()=>this.onSelect?.(e))}}
601
601
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
602
602
  >
603
603
  <div class="action-main">
@@ -617,19 +617,19 @@ ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.
617
617
  </div>
618
618
  `}
619
619
  </section>
620
- `}handleProjectKeydown(e,t){Li(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Sf(e,this.workspacesByProjectId[e.id]??[],this.activities);return _i(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ut(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
620
+ `}handleProjectKeydown(e,t){ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Df(e,this.workspacesByProjectId[e.id]??[],this.activities);return Oi(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
621
621
 
622
- This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};G.styles=Ni;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([b()],G.prototype,"openMenuProjectId",2);ie([b()],G.prototype,"menuStyle",2);G=ie([E("project-list")],G);function yr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Ff(t)}`)}function Ff(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Bf(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<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 l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Bf(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Uf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var o=s>1?void 0:s?Hf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Uf(t,i,o),o};let q=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,ji(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
622
+ This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};G.styles=zi;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([w()],G.prototype,"openMenuProjectId",2);ie([w()],G.prototype,"menuStyle",2);G=ie([D("project-list")],G);function kr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Yf(t)}`)}function Yf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&eg(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<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 l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function eg(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var tg=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var o=s>1?void 0:s?ig(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tg(t,i,o),o};let q=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
623
623
  <section>
624
624
  <h2>${this.renderHeading()}</h2>
625
625
  ${this.collapsed?null:l`
626
626
  <div class="list-body">
627
- ${this.workspaces.map(e=>{const t=qf(e),i=this.workspaceLabelItems(e);return l`
627
+ ${this.workspaces.map(e=>{const t=sg(e),i=this.workspaceLabelItems(e);return l`
628
628
  <div
629
629
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
630
630
  tabindex="0"
631
631
  title=${t}
632
- @click=${s=>{Oi(s,()=>this.onSelect?.(e))}}
632
+ @click=${s=>{Li(s,()=>this.onSelect?.(e))}}
633
633
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
634
634
  >
635
635
  <div class="action-main">
@@ -641,18 +641,18 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
641
641
  </div>
642
642
  `}
643
643
  </section>
644
- `}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=yf(wf(e,this.activities));return _i(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
644
+ `}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Ef(Tf(e,this.activities));return Oi(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
645
645
  <span class="workspace-primary">
646
646
  <span class="workspace-primary-label">${e}</span>
647
647
  ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
648
648
  </span>
649
649
  ${t.length===0?null:l`
650
650
  <small class="workspace-secondary">
651
- <span class="workspace-label">${yr(t)}</span>
651
+ <span class="workspace-label">${kr(t)}</span>
652
652
  </small>
653
653
  `}
654
654
  ${this.renderActivity(i)}
655
- `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Vf(i.id);return l`
655
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=rg(i.id);return l`
656
656
  <div class="action-menu">
657
657
  <button
658
658
  class="action-menu-toggle"
@@ -669,7 +669,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
669
669
  </div>
670
670
  `:null}
671
671
  </div>
672
- `}renderWorkspaceActions(e){if(!Kf(e))return;const t=this.isDeleting(e);return l`
672
+ `}renderWorkspaceActions(e){if(!og(e))return;const t=this.isDeleting(e);return l`
673
673
  <div class="workspace-menu-actions">
674
674
  <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
675
675
  </div>
@@ -686,11 +686,11 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
686
686
  ${t.length===0?null:l`
687
687
  <div class="workspace-detail-row">
688
688
  <dt>Details</dt>
689
- <dd><span class="workspace-label">${yr(t)}</span></dd>
689
+ <dd><span class="workspace-label">${kr(t)}</span></dd>
690
690
  </div>
691
691
  `}
692
692
  </dl>
693
- `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Ut(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Li(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=Ni;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([b()],q.prototype,"openMenuWorkspaceId",2);X([b()],q.prototype,"menuStyle",2);q=X([E("workspace-list")],q);function qf(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function Kf(e){return e.isGitWorktree&&!e.isMain}function Vf(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Gf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Gf(t,i,o),o};function kt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,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){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.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()}async focusSelectedOrFirst(){return await this.updateComplete,ji(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Xf(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>$t(r)==="current"),s=aa(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Zf(this.sessions);return l`
693
+ `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=zi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([w()],q.prototype,"openMenuWorkspaceId",2);X([w()],q.prototype,"menuStyle",2);q=X([D("workspace-list")],q);function sg(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function og(e){return e.isGitWorktree&&!e.isMain}function rg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var ng=Object.defineProperty,ag=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var o=s>1?void 0:s?ag(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ng(t,i,o),o};function Rt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,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){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.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()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=dg(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>It(r)==="current"),s=pa(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=lg(this.sessions);return l`
694
694
  <section>
695
695
  ${this.renderHeading(e.length+s.length,i)}
696
696
  ${this.collapsed?null:l`
@@ -713,7 +713,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
713
713
  ${this.renderCurrentSelectionButton(t)}
714
714
  <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
715
715
  </h2>
716
- `;const i=this.selected===void 0?"No session selected":kt(this.selected),s=this.selected?.path??i;return l`
716
+ `;const i=this.selected===void 0?"No session selected":Rt(this.selected),s=this.selected?.path??i;return l`
717
717
  <h2>
718
718
  <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span>${this.collapsed?l`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
719
719
  ${this.renderCurrentSelectionButton(t)}
@@ -743,18 +743,18 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
743
743
  <button @click=${()=>{this.closeSelection("archived")}}>Done</button>
744
744
  ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
745
745
  </div>
746
- `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=$t(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
746
+ `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=It(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
747
747
  <div
748
748
  class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
749
749
  style=${`--depth:${String(o)}`}
750
750
  tabindex="0"
751
751
  title=${s.path}
752
- @click=${p=>{Oi(p,()=>{this.activateSessionRow(s,i)})}}
752
+ @click=${p=>{Li(p,()=>{this.activateSessionRow(s,i)})}}
753
753
  @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
754
754
  >
755
755
  <div class="action-main ${n?"selecting":""}">
756
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${kt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
757
- <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${kt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} messages</small>
756
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Rt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
757
+ <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Rt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} messages</small>
758
758
  ${this.renderActivity(s)}
759
759
  </div>
760
760
  <div class="action-menu">
@@ -768,13 +768,13 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
768
768
  <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
769
769
  ${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(s,t)}}>Archive with descendants (${t})</button>`:null}
770
770
  ${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
771
- ${this.canReload?l`<button title=${Xe(this.statuses[s.id],this.activities[s.id])?"Stop current session activity before reloading":"Reload session from disk"} ?disabled=${Xe(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(s)}}>Reload</button>`:null}
771
+ ${this.canReload?l`<button title=${Ye(this.statuses[s.id],this.activities[s.id])?"Stop current session activity before reloading":"Reload session from disk"} ?disabled=${Ye(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(s)}}>Reload</button>`:null}
772
772
  `}
773
773
  </div>
774
774
  `:null}
775
775
  </div>
776
776
  </div>
777
- `}handleSessionKeydown(e,t,i){Li(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&$t(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${kt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${kt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=is(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=is(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>$t(i)===e).map(i=>i.id);this.selectedSessionIds=is(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&$t(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ut(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){const t=Jf(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return _i(t,t==="sending"?"Sending message":"Session active")}};R.styles=[Ni,_`
777
+ `}handleSessionKeydown(e,t,i){ji(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&It(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${Rt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${Rt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=ss(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=ss(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>It(i)===e).map(i=>i.id);this.selectedSessionIds=ss(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&It(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){const t=cg(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Oi(t,t==="sending"?"Sending message":"Session active")}};R.styles=[zi,O`
778
778
  h2 { min-height: 30px; }
779
779
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
780
780
  .bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
@@ -788,7 +788,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
788
788
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
789
789
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
790
790
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
791
- `];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([b()],R.prototype,"openMenuSessionId",2);M([b()],R.prototype,"menuStyle",2);M([b()],R.prototype,"archivedExpanded",2);M([b()],R.prototype,"selectionScopes",2);M([b()],R.prototype,"selectedSessionIds",2);R=M([E("session-list")],R);function $t(e){return e.archived===!0?"archived":"current"}function is(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Zf(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Jf(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function Xf(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 o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return aa(e.filter(s=>i.has(s.id)))}function aa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const so={CHILD:2,ELEMENT:6},oo=e=>(...t)=>({_$litDirective$:e,values:t});let ro=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:Yf}=dl,Sr=e=>e,xr=()=>document.createComment(""),Pt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(xr(),o),n=s.insertBefore(xr(),o);i=new Yf(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=Sr(c).nextSibling;Sr(s).insertBefore(c,o),c=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),eg={},tg=(e,t=eg)=>e._$AH=t,ig=e=>e._$AH,ss=e=>{e._$AR(),e._$AA.remove()};const kr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},sg=oo(class extends ro{constructor(e){if(super(e),e.type!==so.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 o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=ig(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=Ve(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=Ve(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Ve(o[h],r[P]),Pt(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=Ve(o[f],r[v]),Pt(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=kr(n,v,P),u=kr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const H=u.get(n[v]),ot=H!==void 0?o[H]:null;if(ot===null){const mt=Pt(e,o[h]);Ve(mt,r[v]),c[v]=mt}else c[v]=Ve(ot,r[v]),Pt(e,o[h],ot),o[H]=null;v++}else ss(o[f]),f--;else ss(o[h]),h++;for(;v<=P;){const H=Pt(e,c[P+1]);Ve(H,r[v]),c[v++]=H}for(;h<=f;){const H=o[h++];H!==null&&ss(H)}return this.ut=n,tg(e,c),Ue}}),og="pi-web:chat-groups:",rg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem($r(e));return t===null||t===""?void 0:ag(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem($r(e),JSON.stringify(t))}catch{}}};class ng{constructor(t=rg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Pr(r,this.openGroupKeys)&&Pr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function $r(e){return`${og}${e}`}function ag(e){if(Array.isArray(e))return{open:os(e),closedDefaultOpen:[]};if(lg(e))return{open:Array.isArray(e.open)?os(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?os(e.closedDefaultOpen):[]}}function os(e){return e.filter(t=>typeof t=="string")}function Pr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function lg(e){return typeof e=="object"&&e!==null}function cg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>Rr(a,v)),u=a.parts.filter(v=>!Rr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function dg(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,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function Rr(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 pg=30;function hg(e,t){const i=fg(vg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function ug(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=gg(s,t.markerOffset);return}e.scrollTop=mg(e.scrollHeight,t.distanceFromBottom)}function fg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function gg(e,t){return e-t}function mg(e,t){return Math.max(0,e-t)}function vg(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const bg=600,wg=1;function yg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Sg(e)||xg(e)}function Sg(e){return e.scrollTop<(e.topThreshold??Math.max(bg,e.clientHeight))}function xg(e){return e.scrollHeight<=e.clientHeight+wg}const kg="pi-web:chat-scroll:",$g=180,Pg=48,Rg=2,Cg={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},Ig={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Mg{constructor(t=Cg,i=Ig){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=$g){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=Rg){if(t===""||i===void 0||!ns(i))return"skipped";try{if(ca(i,o)){const a={mode:"bottom"};return this.storage.setItem(rs(t),JSON.stringify(a)),"saved"}const r=Eg(i,s);if(r===void 0)return"skipped";const n=Ag(i,r);return this.storage.setItem(rs(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ns(i))return{status:"skipped"};const r=Dg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(rs(t));if(i===null||i==="")return;const s=JSON.parse(i);return Tg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ns(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function rs(e){return`${kg}${e}`}function Tg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function ns(e){return e.clientHeight>0&&e.scrollHeight>0}function la(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ca(e,t=Pg){return la(e)<t}function Ag(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:no(t)??"",offset:t.getBoundingClientRect().top-i}}function Eg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(no(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Cr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function Dg(e,t){return e.find(i=>no(i)===t)}function no(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var Wg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,ao=(e,t,i,s)=>{for(var o=s>1?void 0:s?_g(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wg(t,i,o),o};let Lt=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Ir(this.positionPercent),t=Ir(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
791
+ `];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([w()],R.prototype,"openMenuSessionId",2);M([w()],R.prototype,"menuStyle",2);M([w()],R.prototype,"archivedExpanded",2);M([w()],R.prototype,"selectionScopes",2);M([w()],R.prototype,"selectedSessionIds",2);R=M([D("session-list")],R);function It(e){return e.archived===!0?"archived":"current"}function ss(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function lg(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function cg(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Ye(t,i)?"session":void 0}function dg(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 o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return pa(e.filter(s=>i.has(s.id)))}function pa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const ro={CHILD:2,ELEMENT:6},no=e=>(...t)=>({_$litDirective$:e,values:t});let ao=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:pg}=fl,$r=e=>e,Pr=()=>document.createComment(""),Ct=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(Pr(),o),n=s.insertBefore(Pr(),o);i=new pg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=$r(c).nextSibling;$r(s).insertBefore(c,o),c=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),hg={},ug=(e,t=hg)=>e._$AH=t,fg=e=>e._$AH,os=e=>{e._$AR(),e._$AA.remove()};const Rr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},gg=no(class extends ao{constructor(e){if(super(e),e.type!==ro.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 o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=fg(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=Ve(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=Ve(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Ve(o[h],r[P]),Ct(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=Ve(o[f],r[v]),Ct(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=Rr(n,v,P),u=Rr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const H=u.get(n[v]),rt=H!==void 0?o[H]:null;if(rt===null){const wt=Ct(e,o[h]);Ve(wt,r[v]),c[v]=wt}else c[v]=Ve(rt,r[v]),Ct(e,o[h],rt),o[H]=null;v++}else os(o[f]),f--;else os(o[h]),h++;for(;v<=P;){const H=Ct(e,c[P+1]);Ve(H,r[v]),c[v++]=H}for(;h<=f;){const H=o[h++];H!==null&&os(H)}return this.ut=n,ug(e,c),Ue}}),mg="pi-web:chat-groups:",vg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Ir(e));return t===null||t===""?void 0:wg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Ir(e),JSON.stringify(t))}catch{}}};class bg{constructor(t=vg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Cr(r,this.openGroupKeys)&&Cr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Ir(e){return`${mg}${e}`}function wg(e){if(Array.isArray(e))return{open:rs(e),closedDefaultOpen:[]};if(yg(e))return{open:Array.isArray(e.open)?rs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?rs(e.closedDefaultOpen):[]}}function rs(e){return e.filter(t=>typeof t=="string")}function Cr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function yg(e){return typeof e=="object"&&e!==null}function Sg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>Mr(a,v)),u=a.parts.filter(v=>!Mr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function xg(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,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function Mr(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 kg=30;function $g(e,t){const i=Rg(Mg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Pg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ig(s,t.markerOffset);return}e.scrollTop=Cg(e.scrollHeight,t.distanceFromBottom)}function Rg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function Ig(e,t){return e-t}function Cg(e,t){return Math.max(0,e-t)}function Mg(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const Ag=600,Tg=1;function Eg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Dg(e)||Wg(e)}function Dg(e){return e.scrollTop<(e.topThreshold??Math.max(Ag,e.clientHeight))}function Wg(e){return e.scrollHeight<=e.clientHeight+Tg}const _g="pi-web:chat-scroll:",Og=180,Lg=48,jg=2,Ng={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},zg={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Fg{constructor(t=Ng,i=zg){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=Og){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=jg){if(t===""||i===void 0||!as(i))return"skipped";try{if(ua(i,o)){const a={mode:"bottom"};return this.storage.setItem(ns(t),JSON.stringify(a)),"saved"}const r=Hg(i,s);if(r===void 0)return"skipped";const n=Ug(i,r);return this.storage.setItem(ns(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!as(i))return{status:"skipped"};const r=qg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(ns(t));if(i===null||i==="")return;const s=JSON.parse(i);return Bg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!as(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ns(e){return`${_g}${e}`}function Bg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function as(e){return e.clientHeight>0&&e.scrollHeight>0}function ha(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ua(e,t=Lg){return ha(e)<t}function Ug(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:lo(t)??"",offset:t.getBoundingClientRect().top-i}}function Hg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(lo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Ar(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function qg(e,t){return e.find(i=>lo(i)===t)}function lo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var Kg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,co=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kg(t,i,o),o};let jt=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Tr(this.positionPercent),t=Tr(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
792
792
  <div
793
793
  class="meter"
794
794
  style=${`--position:${e.toFixed(2)}%;`}
@@ -804,19 +804,19 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
804
804
  <div class="marker"></div>
805
805
  </div>
806
806
  </div>
807
- `}};Lt.styles=_`
807
+ `}};jt.styles=O`
808
808
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
809
809
  :host(:hover), :host(:focus-within) { opacity: .92; }
810
810
  .meter { height: 100%; }
811
811
  .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); }
812
812
  .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)); }
813
813
  .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%); }
814
- `;ao([d({type:Number})],Lt.prototype,"positionPercent",2);ao([d({type:Number})],Lt.prototype,"loadedPercent",2);Lt=ao([E("conversation-meter")],Lt);function Ir(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Is extends ro{constructor(t){if(super(t),this.it=z,t.type!==so.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===z||t==null)return this._t=void 0,this.it=t;if(t===Ue)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:[]}}}Is.directiveName="unsafeHTML",Is.resultType=1;const Og=oo(Is);function lo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tt=lo();function da(e){tt=e}var Ge={exec:()=>null};function C(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(Z.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var Lg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Z={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)}}>`)},jg=/^(?:[ \t]*(?:\n|$))+/,Ng=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,zg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ht=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Fg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,co=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,pa=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ha=C(pa).replace(/bull/g,co).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(),Bg=C(pa).replace(/bull/g,co).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(),po=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ug=/^[^\n]+/,ho=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Hg=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ho).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),qg=C(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,co).getRegex(),zi="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",uo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Kg=C("^ {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",uo).replace("tag",zi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ua=C(po).replace("hr",Ht).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",zi).getRegex(),Vg=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ua).getRegex(),fo={blockquote:Vg,code:Ng,def:Hg,fences:zg,heading:Fg,hr:Ht,html:Kg,lheading:ha,list:qg,newline:jg,paragraph:ua,table:Ge,text:Ug},Mr=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ht).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",zi).getRegex(),Gg={...fo,lheading:Bg,table:Mr,paragraph:C(po).replace("hr",Ht).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Mr).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",zi).getRegex()},Qg={...fo,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",uo).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:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(po).replace("hr",Ht).replace("heading",` *#{1,6} *[^
815
- ]`).replace("lheading",ha).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Zg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Jg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,fa=/^( {2,}|\\)\n(?!\s*$)/,Xg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,gt=/[\p{P}\p{S}]/u,Fi=/[\s\p{P}\p{S}]/u,go=/[^\s\p{P}\p{S}]/u,Yg=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Fi).getRegex(),ga=/(?!~)[\p{P}\p{S}]/u,em=/(?!~)[\s\p{P}\p{S}]/u,tm=/(?:[^\s\p{P}\p{S}]|~)/u,im=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Lg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ma=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,sm=C(ma,"u").replace(/punct/g,gt).getRegex(),om=C(ma,"u").replace(/punct/g,ga).getRegex(),va="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",rm=C(va,"gu").replace(/notPunctSpace/g,go).replace(/punctSpace/g,Fi).replace(/punct/g,gt).getRegex(),nm=C(va,"gu").replace(/notPunctSpace/g,tm).replace(/punctSpace/g,em).replace(/punct/g,ga).getRegex(),am=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,go).replace(/punctSpace/g,Fi).replace(/punct/g,gt).getRegex(),lm=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,gt).getRegex(),cm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",dm=C(cm,"gu").replace(/notPunctSpace/g,go).replace(/punctSpace/g,Fi).replace(/punct/g,gt).getRegex(),pm=C(/\\(punct)/,"gu").replace(/punct/g,gt).getRegex(),hm=C(/^<(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(),um=C(uo).replace("(?:-->|$)","-->").getRegex(),fm=C("^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",um).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ki=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,gm=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ki).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ba=C(/^!?\[(label)\]\[(ref)\]/).replace("label",ki).replace("ref",ho).getRegex(),wa=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",ho).getRegex(),mm=C("reflink|nolink(?!\\()","g").replace("reflink",ba).replace("nolink",wa).getRegex(),Tr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,mo={_backpedal:Ge,anyPunctuation:pm,autolink:hm,blockSkip:im,br:fa,code:Jg,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:sm,emStrongRDelimAst:rm,emStrongRDelimUnd:am,escape:Zg,link:gm,nolink:wa,punctuation:Yg,reflink:ba,reflinkSearch:mm,tag:fm,text:Xg,url:Ge},vm={...mo,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",ki).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ki).getRegex()},Ms={...mo,emStrongRDelimAst:nm,emStrongLDelim:om,delLDelim:lm,delRDelim:dm,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Tr).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:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Tr).getRegex()},bm={...Ms,br:C(fa).replace("{2,}","*").getRegex(),text:C(Ms.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Zt={normal:fo,gfm:Gg,pedantic:Qg},Rt={normal:mo,gfm:Ms,breaks:bm,pedantic:vm},wm={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ar=e=>wm[e];function Me(e,t){if(t){if(Z.escapeTest.test(e))return e.replace(Z.escapeReplace,Ar)}else if(Z.escapeTestNoEncode.test(e))return e.replace(Z.escapeReplaceNoEncode,Ar);return e}function Er(e){try{e=encodeURI(e).replace(Z.percentDecode,"%")}catch{return null}return e}function Dr(e,t){let i=e.replace(Z.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(Z.splitPipe),o=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(;o<s.length;o++)s[o]=s[o].trim().replace(Z.slashPipe,"|");return s}function Fe(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Wr(e){let t=e.split(`
814
+ `;co([d({type:Number})],jt.prototype,"positionPercent",2);co([d({type:Number})],jt.prototype,"loadedPercent",2);jt=co([D("conversation-meter")],jt);function Tr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class As extends ao{constructor(t){if(super(t),this.it=F,t.type!==ro.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)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:[]}}}As.directiveName="unsafeHTML",As.resultType=1;const Gg=no(As);function po(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var it=po();function fa(e){it=e}var Ge={exec:()=>null};function ct(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(Z.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var Qg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Z={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:ct(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ct(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ct(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ct(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ct(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ct(e=>new RegExp(`^ {0,${e}}>`))},Zg=/^(?:[ \t]*(?:\n|$))+/,Jg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Xg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Yg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ho=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ga=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ma=I(ga).replace(/bull/g,ho).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(),em=I(ga).replace(/bull/g,ho).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(),uo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,tm=/^[^\n]+/,fo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,im=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sm=I(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ho).getRegex(),Fi="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",go=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,om=I("^ {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",go).replace("tag",Fi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),va=I(uo).replace("hr",qt).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]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),rm=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",va).getRegex(),mo={blockquote:rm,code:Jg,def:im,fences:Xg,heading:Yg,hr:qt,html:om,lheading:ma,list:sm,newline:Zg,paragraph:va,table:Ge,text:tm},Er=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qt).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",Fi).getRegex(),nm={...mo,lheading:em,table:Er,paragraph:I(uo).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex()},am={...mo,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",go).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:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(uo).replace("hr",qt).replace("heading",` *#{1,6} *[^
815
+ ]`).replace("lheading",ma).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,cm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ba=/^( {2,}|\\)\n(?!\s*$)/,dm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,bt=/[\p{P}\p{S}]/u,Bi=/[\s\p{P}\p{S}]/u,vo=/[^\s\p{P}\p{S}]/u,pm=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Bi).getRegex(),wa=/(?!~)[\p{P}\p{S}]/u,hm=/(?!~)[\s\p{P}\p{S}]/u,um=/(?:[^\s\p{P}\p{S}]|~)/u,fm=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Qg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ya=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gm=I(ya,"u").replace(/punct/g,bt).getRegex(),mm=I(ya,"u").replace(/punct/g,wa).getRegex(),Sa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",vm=I(Sa,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),bm=I(Sa,"gu").replace(/notPunctSpace/g,um).replace(/punctSpace/g,hm).replace(/punct/g,wa).getRegex(),wm=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),ym=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,bt).getRegex(),Sm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",xm=I(Sm,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),km=I(/\\(punct)/,"gu").replace(/punct/g,bt).getRegex(),$m=I(/^<(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(),Pm=I(go).replace("(?:-->|$)","-->").getRegex(),Rm=I("^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",Pm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),$i=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Im=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",$i).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xa=I(/^!?\[(label)\]\[(ref)\]/).replace("label",$i).replace("ref",fo).getRegex(),ka=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",fo).getRegex(),Cm=I("reflink|nolink(?!\\()","g").replace("reflink",xa).replace("nolink",ka).getRegex(),Dr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bo={_backpedal:Ge,anyPunctuation:km,autolink:$m,blockSkip:fm,br:ba,code:cm,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:gm,emStrongRDelimAst:vm,emStrongRDelimUnd:wm,escape:lm,link:Im,nolink:ka,punctuation:pm,reflink:xa,reflinkSearch:Cm,tag:Rm,text:dm,url:Ge},Mm={...bo,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",$i).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$i).getRegex()},Ts={...bo,emStrongRDelimAst:bm,emStrongLDelim:mm,delLDelim:ym,delRDelim:xm,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dr).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:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Dr).getRegex()},Am={...Ts,br:I(ba).replace("{2,}","*").getRegex(),text:I(Ts.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Jt={normal:mo,gfm:nm,pedantic:am},Mt={normal:bo,gfm:Ts,breaks:Am,pedantic:Mm},Tm={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Wr=e=>Tm[e];function Ae(e,t){if(t){if(Z.escapeTest.test(e))return e.replace(Z.escapeReplace,Wr)}else if(Z.escapeTestNoEncode.test(e))return e.replace(Z.escapeReplaceNoEncode,Wr);return e}function _r(e){try{e=encodeURI(e).replace(Z.percentDecode,"%")}catch{return null}return e}function Or(e,t){let i=e.replace(Z.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(Z.splitPipe),o=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(;o<s.length;o++)s[o]=s[o].trim().replace(Z.slashPipe,"|");return s}function Fe(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Lr(e){let t=e.split(`
816
816
  `),i=t.length-1;for(;i>=0&&Z.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
817
- `)}function ym(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 Sm(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function _r(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function xm(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
817
+ `)}function Em(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 Dm(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function jr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function Wm(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
818
818
  `).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
819
- `)}var $i=class{options;rules;lexer;constructor(e){this.options=e||tt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Wr(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=xm(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=Fe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Fe(t[0],`
819
+ `)}var Pi=class{options;rules;lexer;constructor(e){this.options=e||it}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Lr(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=Wm(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=Fe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Fe(t[0],`
820
820
  `),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:Fe(t[0],`
821
821
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Fe(t[0],`
822
822
  `).split(`
@@ -829,19 +829,19 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
829
829
  `),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-v.raw.length)+H.raw,o=o.substring(0,o.length-v.text.length)+H.text;break}else if(f?.type==="list"){let v=f,P=v.raw+`
830
830
  `+i.join(`
831
831
  `),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-f.raw.length)+H.raw,o=o.substring(0,o.length-v.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
832
- `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={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 r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Sm(t[2].split(`
832
+ `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={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 r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Dm(t[2].split(`
833
833
  `,1)[0],t[1].length),f=e.split(`
834
834
  `,1)[0],v=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):v?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),v&&this.rules.other.blankLine.test(f)&&(p+=f+`
835
- `,e=e.substring(f.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),ot=this.rules.other.hrRegex(P),mt=this.rules.other.fencesBeginRegex(P),wo=this.rules.other.headingBeginRegex(P),Aa=this.rules.other.htmlBeginRegex(P),Ea=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Ui=e.split(`
836
- `,1)[0],vt;if(f=Ui,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),vt=f):vt=f.replace(this.rules.other.tabCharGlobal," "),mt.test(f)||wo.test(f)||Aa.test(f)||Ea.test(f)||H.test(f)||ot.test(f))break;if(vt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
837
- `+vt.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||mt.test(h)||wo.test(h)||ot.test(h))break;u+=`
838
- `+f}v=!f.trim(),p+=Ui+`
839
- `,e=e.substring(Ui.length+1),h=vt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Wr(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"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Fe(t[0],`
840
- `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Dr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
835
+ `,e=e.substring(f.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),rt=this.rules.other.hrRegex(P),wt=this.rules.other.fencesBeginRegex(P),So=this.rules.other.headingBeginRegex(P),_a=this.rules.other.htmlBeginRegex(P),Oa=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Hi=e.split(`
836
+ `,1)[0],yt;if(f=Hi,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),yt=f):yt=f.replace(this.rules.other.tabCharGlobal," "),wt.test(f)||So.test(f)||_a.test(f)||Oa.test(f)||H.test(f)||rt.test(f))break;if(yt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
837
+ `+yt.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||wt.test(h)||So.test(h)||rt.test(h))break;u+=`
838
+ `+f}v=!f.trim(),p+=Hi+`
839
+ `,e=e.substring(Hi.length+1),h=yt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Lr(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"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Fe(t[0],`
840
+ `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Or(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
841
841
  `):[],r={type:"table",raw:Fe(t[0],`
842
- `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Dr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Fe(t[0],`
842
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Or(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Fe(t[0],`
843
843
  `),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)===`
844
- `?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 r=Fe(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=ym(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=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)),_r(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.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," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return _r(i,o,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 o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let f=h.slice(2,-2);return{type:"strong",raw:h,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),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(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 o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}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 o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==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}}}},ke=class Ts{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||tt,this.options.tokenizer=this.options.tokenizer||new $i,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:Z,block:Zt.normal,inline:Rt.normal};this.options.pedantic?(i.block=Zt.pedantic,i.inline=Rt.pedantic):this.options.gfm&&(i.block=Zt.gfm,this.options.breaks?i.inline=Rt.breaks:i.inline=Rt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Zt,inline:Rt}}static lex(t,i){return new Ts(i).lex(t)}static lexInline(t,i){return new Ts(i).inlineTokens(t)}lex(t){t=t.replace(Z.carriageReturn,`
844
+ `?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 r=Fe(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=Em(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=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)),jr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.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," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return jr(i,o,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 o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let f=h.slice(2,-2);return{type:"strong",raw:h,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),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(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 o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}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 o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==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}}}},ke=class Es{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||it,this.options.tokenizer=this.options.tokenizer||new Pi,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:Z,block:Jt.normal,inline:Mt.normal};this.options.pedantic?(i.block=Jt.pedantic,i.inline=Mt.pedantic):this.options.gfm&&(i.block=Jt.gfm,this.options.breaks?i.inline=Mt.breaks:i.inline=Mt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Jt,inline:Mt}}static lex(t,i){return new Es(i).lex(t)}static lexInline(t,i){return new Es(i).inlineTokens(t)}lex(t){t=t.replace(Z.carriageReturn,`
845
845
  `),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(Z.tabCharGlobal," ").replace(Z.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
846
846
  `:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
847
847
  `)?"":`
@@ -855,9 +855,9 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
855
855
  `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
856
856
  `)?"":`
857
857
  `)+r.raw,a.text+=`
858
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);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,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);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)}},Pi=class{options;parser;constructor(e){this.options=e||tt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Z.notSpaceStart)?.[0],o=e.replace(Z.endingNewline,"")+`
859
- `;return s?'<pre><code class="language-'+Me(s)+'">'+(i?o:Me(o,!0))+`</code></pre>
860
- `:"<pre><code>"+(i?o:Me(o,!0))+`</code></pre>
858
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);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,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);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)}},Ri=class{options;parser;constructor(e){this.options=e||it}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Z.notSpaceStart)?.[0],o=e.replace(Z.endingNewline,"")+`
859
+ `;return s?'<pre><code class="language-'+Ae(s)+'">'+(i?o:Ae(o,!0))+`</code></pre>
860
+ `:"<pre><code>"+(i?o:Ae(o,!0))+`</code></pre>
861
861
  `}blockquote({tokens:e}){return`<blockquote>
862
862
  ${this.parser.parse(e)}</blockquote>
863
863
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -873,19 +873,19 @@ ${this.parser.parse(e)}</blockquote>
873
873
  `}tablerow({text:e}){return`<tr>
874
874
  ${e}</tr>
875
875
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
876
- `}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>${Me(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),o=Er(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Me(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Er(e);if(o===null)return Me(i);e=o;let r=`<img src="${e}" alt="${Me(i)}"`;return t&&(r+=` title="${Me(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Me(e.text)}},vo=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}},$e=class As{options;renderer;textRenderer;constructor(t){this.options=t||tt,this.options.renderer=this.options.renderer||new Pi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new vo}static parse(t,i){return new As(i).parse(t)}static parseInline(t,i){return new As(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,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 r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.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 o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;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}},It=class{options;block;constructor(e){this.options=e||tt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},km=class{defaults=lo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Pi;TextRenderer=vo;Lexer=ke;Tokenizer=$i;Hooks=It;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 o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.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(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Pi(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new $i(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new It;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];It.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&It.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(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 r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
877
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Me(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ye=new km;function A(e,t){return Ye.parse(e,t)}A.options=A.setOptions=function(e){return Ye.setOptions(e),A.defaults=Ye.defaults,da(A.defaults),A};A.getDefaults=lo;A.defaults=tt;A.use=function(...e){return Ye.use(...e),A.defaults=Ye.defaults,da(A.defaults),A};A.walkTokens=function(e,t){return Ye.walkTokens(e,t)};A.parseInline=Ye.parseInline;A.Parser=$e;A.parser=$e.parse;A.Renderer=Pi;A.TextRenderer=vo;A.Lexer=ke;A.lexer=ke.lex;A.Tokenizer=$i;A.Hooks=It;A.parse=A;A.options;A.setOptions;A.use;A.walkTokens;A.parseInline;$e.parse;ke.lex;const ya=new A.Renderer;ya.html=({text:e})=>Rm(e);const $m=300,Ct=new Map;function Pm(e){const t=Ct.get(e);if(t!==void 0)return t;const i=A.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:ya}),s=Cm(i);if(Ct.set(e,s),Ct.size>$m){const o=Ct.keys().next().value;o!==void 0&&Ct.delete(o)}return s}function Rm(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Cm(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 o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!Im(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function Im(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Mm=Object.defineProperty,Tm=Object.getOwnPropertyDescriptor,Sa=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mm(t,i,o),o};let Ri=class extends I{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)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${Og(Pm(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 o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Am(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)}};Ri.styles=Af;Sa([d()],Ri.prototype,"text",2);Ri=Sa([E("formatted-text")],Ri);async function Am(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var Em=Object.defineProperty,Dm=Object.getOwnPropertyDescriptor,qt=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Em(t,i,o),o};const Or=180;let et=class extends I{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=Wm(e.args),s=_m(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Om(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
876
+ `}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>${Ae(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),o=_r(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ae(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=_r(e);if(o===null)return Ae(i);e=o;let r=`<img src="${e}" alt="${Ae(i)}"`;return t&&(r+=` title="${Ae(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ae(e.text)}},wo=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}},$e=class Ds{options;renderer;textRenderer;constructor(t){this.options=t||it,this.options.renderer=this.options.renderer||new Ri,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new wo}static parse(t,i){return new Ds(i).parse(t)}static parseInline(t,i){return new Ds(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,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 r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.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 o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;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}},Tt=class{options;block;constructor(e){this.options=e||it}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},_m=class{defaults=po();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ri;TextRenderer=wo;Lexer=ke;Tokenizer=Pi;Hooks=Tt;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 o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.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(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ri(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Pi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new Tt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];Tt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&Tt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(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 r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
877
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ae(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},et=new _m;function T(e,t){return et.parse(e,t)}T.options=T.setOptions=function(e){return et.setOptions(e),T.defaults=et.defaults,fa(T.defaults),T};T.getDefaults=po;T.defaults=it;T.use=function(...e){return et.use(...e),T.defaults=et.defaults,fa(T.defaults),T};T.walkTokens=function(e,t){return et.walkTokens(e,t)};T.parseInline=et.parseInline;T.Parser=$e;T.parser=$e.parse;T.Renderer=Ri;T.TextRenderer=wo;T.Lexer=ke;T.lexer=ke.lex;T.Tokenizer=Pi;T.Hooks=Tt;T.parse=T;T.options;T.setOptions;T.use;T.walkTokens;T.parseInline;$e.parse;ke.lex;const $a=new T.Renderer;$a.html=({text:e})=>jm(e);const Om=300,At=new Map;function Lm(e){const t=At.get(e);if(t!==void 0)return t;const i=T.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$a}),s=Nm(i);if(At.set(e,s),At.size>Om){const o=At.keys().next().value;o!==void 0&&At.delete(o)}return s}function jm(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Nm(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 o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!zm(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function zm(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,Pa=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};let Ii=class extends C{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)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${Gg(Lm(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 o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Um(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)}};Ii.styles=Uf;Pa([d()],Ii.prototype,"text",2);Ii=Pa([D("formatted-text")],Ii);async function Um(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var Hm=Object.defineProperty,qm=Object.getOwnPropertyDescriptor,Kt=(e,t,i,s)=>{for(var o=s>1?void 0:s?qm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hm(t,i,o),o};const Nr=180;let tt=class extends C{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=Km(e.args),s=Vm(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Gm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
878
878
  <section class=${`tool-card ${e.status}`}>
879
879
  <div class="tool-header">
880
880
  <div class="tool-title">
881
- <span class="status-icon" aria-hidden="true">${jm(e.status)}</span>
881
+ <span class="status-icon" aria-hidden="true">${Zm(e.status)}</span>
882
882
  <strong>${e.toolName}</strong>
883
883
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
884
884
  </div>
885
885
  <div class="tool-meta">
886
- ${Lr(e)===void 0?null:l`<span>${Lr(e)}</span>`}
886
+ ${zr(e)===void 0?null:l`<span>${zr(e)}</span>`}
887
887
  ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
888
- <span class="status-label">${Nm(e.status)}</span>
888
+ <span class="status-label">${Jm(e.status)}</span>
889
889
  </div>
890
890
  </div>
891
891
 
@@ -900,7 +900,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
900
900
  <pre>${e}</pre>
901
901
  </details>
902
902
  `}renderDiffBody(e,t){const i=e.split(`
903
- `),s=!this.showFullDiff&&i.length>Or,o=s?i.slice(0,Or):i;return l`
903
+ `),s=!this.showFullDiff&&i.length>Nr,o=s?i.slice(0,Nr):i;return l`
904
904
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
905
905
  <summary>
906
906
  <span>${t}</span>
@@ -910,14 +910,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
910
910
  <span>${s?`Showing ${String(o.length)} of ${String(i.length)} lines`:"Full diff"}</span>
911
911
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
912
912
  </div>
913
- <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Lm(r)}>${r}</span>`)}</code></pre>
913
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Qm(r)}>${r}</span>`)}</code></pre>
914
914
  ${s?l`
915
915
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
916
916
  Show all ${String(i.length)} diff lines
917
917
  </button>
918
918
  `:null}
919
919
  </details>
920
- `}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}}};et.styles=_`
920
+ `}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}}};tt.styles=O`
921
921
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
922
922
  .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); }
923
923
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -957,19 +957,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
957
957
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
958
958
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
959
959
  .show-more { justify-self: start; }
960
- `;qt([d({attribute:!1})],et.prototype,"execution",2);qt([b()],et.prototype,"showFullDiff",2);qt([b()],et.prototype,"copied",2);qt([b()],et.prototype,"diffOpen",2);et=qt([E("tool-execution-view")],et);function Wm(e){return Es(e,"path")??Es(e,"file_path")}function Lr(e){if(e.toolName!=="edit")return;const t=ai(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof ai(e.args,"oldText")=="string"&&typeof ai(e.args,"newText")=="string")return"1 edit"}function _m(e){return Es(e,"diff")}function Om(e){let t=0,i=0;for(const s of e.split(`
961
- `))xa(s)?t++:ka(s)&&i++;return{added:t,removed:i}}function Lm(e){return xa(e)?"added":ka(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function xa(e){return e.startsWith("+")&&!e.startsWith("+++")}function ka(e){return e.startsWith("-")&&!e.startsWith("---")}function jm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Nm(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function zm(e){return typeof e=="object"&&e!==null}function ai(e,t){return zm(e)?e[t]:void 0}function Es(e,t){const i=ai(e,t);return typeof i=="string"?i:void 0}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};const Um=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Hm=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),as=["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 jr(){return as[Math.floor(Math.random()*as.length)]??as[0]}function Nr(e){return li(e,0,100)}function li(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let j=class extends I{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new ng,this.scrollController=new Mg,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.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),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.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(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")&&this.restoreScrollPosition(),!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("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
960
+ `;Kt([d({attribute:!1})],tt.prototype,"execution",2);Kt([w()],tt.prototype,"showFullDiff",2);Kt([w()],tt.prototype,"copied",2);Kt([w()],tt.prototype,"diffOpen",2);tt=Kt([D("tool-execution-view")],tt);function Km(e){return Ws(e,"path")??Ws(e,"file_path")}function zr(e){if(e.toolName!=="edit")return;const t=li(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof li(e.args,"oldText")=="string"&&typeof li(e.args,"newText")=="string")return"1 edit"}function Vm(e){return Ws(e,"diff")}function Gm(e){let t=0,i=0;for(const s of e.split(`
961
+ `))Ra(s)?t++:Ia(s)&&i++;return{added:t,removed:i}}function Qm(e){return Ra(e)?"added":Ia(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Ra(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ia(e){return e.startsWith("-")&&!e.startsWith("---")}function Zm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Jm(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Xm(e){return typeof e=="object"&&e!==null}function li(e,t){return Xm(e)?e[t]:void 0}function Ws(e,t){const i=li(e,t);return typeof i=="string"?i:void 0}var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ym(t,i,o),o};const tv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),iv=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ls=["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 Fr(){return ls[Math.floor(Math.random()*ls.length)]??ls[0]}function Br(e){return ci(e,0,100)}function ci(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let z=class extends C{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new bg,this.scrollController=new Fg,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.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),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.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(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")&&this.restoreScrollPosition(),!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("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
962
962
  <div class="chat-wrap">
963
963
  ${this.renderConversationRail()}
964
964
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
965
965
  ${this.renderHistoryBoundary()}
966
- ${sg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
966
+ ${gg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
967
967
  ${this.renderQueuedMessages()}
968
968
  ${this.renderSessionActivity()}
969
969
  </div>
970
970
  ${this.renderActivityDock()}
971
971
  </div>
972
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=cg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
972
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Sg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
973
973
  <div class="activity-dock active" aria-live="polite">
974
974
  <span class="dot"></span>
975
975
  <span class="activity-text">Sending your message…</span>
@@ -1003,7 +1003,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1003
1003
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
1004
1004
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
1005
1005
  </aside>
1006
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?jr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=jr(),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?Nr(this.messages.length/e*100):100;return l`<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=li(this.currentConversationIndex??t,0,e-1);return Nr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
1006
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Fr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Fr(),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?Br(this.messages.length/e*100):100;return l`<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=ci(this.currentConversationIndex??t,0,e-1);return Br(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
1007
1007
  <div class="history-boundary">
1008
1008
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
1009
1009
  <span>Scroll up to load earlier messages</span>
@@ -1020,7 +1020,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1020
1020
  <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
1021
1021
  <summary>
1022
1022
  <b class="label">${s?"live events":"events"}</b>
1023
- <span>${dg(e)}</span>
1023
+ <span>${xg(e)}</span>
1024
1024
  </summary>
1025
1025
  <div class="group-body">
1026
1026
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -1047,7 +1047,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1047
1047
  </div>
1048
1048
  `}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(`
1049
1049
 
1050
- `);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 c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.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:Um.format(t),full:Hm.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"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1050
+ `);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 c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.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:tv.format(t),full:iv.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"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1051
1051
  <details class="part skill-invocation">
1052
1052
  <summary><b>[skill]</b> ${e.name}</summary>
1053
1053
  <small>${e.location}</small>
@@ -1063,46 +1063,46 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1063
1063
  <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1064
1064
  <formatted-text .text=${e.text}></formatted-text>
1065
1065
  </details>
1066
- `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}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&&yg({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?ca(e):!0}isAtBottom(){const e=this.chat;return e?la(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}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(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return hg(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(ug(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<pg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}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=li(i,0,Math.max(0,e-1));return}this.currentConversationIndex=li(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}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===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Cr(e,t)??Cr(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};j.styles=Tf;U([d({attribute:!1})],j.prototype,"messages",2);U([d()],j.prototype,"sessionId",2);U([d({type:Number})],j.prototype,"messageStart",2);U([d({type:Number})],j.prototype,"messageEnd",2);U([d({type:Number})],j.prototype,"messageTotal",2);U([d({type:Boolean})],j.prototype,"hasMore",2);U([d({type:Boolean})],j.prototype,"loadingMore",2);U([d({type:Boolean})],j.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],j.prototype,"isSendingPrompt",2);U([d({type:Boolean})],j.prototype,"isCompacting",2);U([d({type:Number})],j.prototype,"pendingMessageCount",2);U([d({attribute:!1})],j.prototype,"status",2);U([d({attribute:!1})],j.prototype,"activity",2);U([d({attribute:!1})],j.prototype,"onLoadMore",2);U([B(".chat")],j.prototype,"chat",2);U([b()],j.prototype,"pinnedToBottom",2);U([b()],j.prototype,"expandedMetaKey",2);U([b()],j.prototype,"copiedMessageKey",2);U([b()],j.prototype,"currentConversationIndex",2);U([b()],j.prototype,"loadMoreRequested",2);j=U([E("chat-view")],j);const qm=["image/jpeg","image/png","image/gif","image/webp"],Km=new Set(qm);function Vm(e){return typeof e=="string"&&Km.has(e)}function Gm(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const Qm="Only PNG, JPEG, GIF, and WebP images are supported.",Zm="Failed to read an attachment.";async function Jm(e,t){const i=[];let s;for(const o of e){if(!Vm(o.type)){s=Qm;continue}try{const r=await t(o);i.push({name:Xm(o),mimeType:o.type,data:r,size:o.size})}catch{s=Zm}}return{attachments:i,...s===void 0?{}:{error:s}}}function Xm(e){return e.name!==""?e.name:`pasted-image.${Gm(e.type)}`}const $a="pi-web:attachment-delivery";function Pa(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ym(e=Pa()){try{return e?.getItem($a)==="folder"?"folder":"inline"}catch{return"inline"}}function ev(e,t=Pa()){try{t?.setItem($a,e)}catch{}}function tv(){return he`
1066
+ `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}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&&Eg({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?ua(e):!0}isAtBottom(){const e=this.chat;return e?ha(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}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(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return $g(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Pg(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<kg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}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=ci(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ci(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}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===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Ar(e,t)??Ar(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};z.styles=Bf;U([d({attribute:!1})],z.prototype,"messages",2);U([d()],z.prototype,"sessionId",2);U([d({type:Number})],z.prototype,"messageStart",2);U([d({type:Number})],z.prototype,"messageEnd",2);U([d({type:Number})],z.prototype,"messageTotal",2);U([d({type:Boolean})],z.prototype,"hasMore",2);U([d({type:Boolean})],z.prototype,"loadingMore",2);U([d({type:Boolean})],z.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],z.prototype,"isSendingPrompt",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Number})],z.prototype,"pendingMessageCount",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"activity",2);U([d({attribute:!1})],z.prototype,"onLoadMore",2);U([B(".chat")],z.prototype,"chat",2);U([w()],z.prototype,"pinnedToBottom",2);U([w()],z.prototype,"expandedMetaKey",2);U([w()],z.prototype,"copiedMessageKey",2);U([w()],z.prototype,"currentConversationIndex",2);U([w()],z.prototype,"loadMoreRequested",2);z=U([D("chat-view")],z);const sv=["image/jpeg","image/png","image/gif","image/webp"],ov=new Set(sv);function rv(e){return typeof e=="string"&&ov.has(e)}function nv(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const av="Only PNG, JPEG, GIF, and WebP images are supported.",lv="Failed to read an attachment.";async function cv(e,t){const i=[];let s;for(const o of e){if(!rv(o.type)){s=av;continue}try{const r=await t(o);i.push({name:dv(o),mimeType:o.type,data:r,size:o.size})}catch{s=lv}}return{attachments:i,...s===void 0?{}:{error:s}}}function dv(e){return e.name!==""?e.name:`pasted-image.${nv(e.type)}`}const Ca="pi-web:attachment-delivery";function Ma(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function pv(e=Ma()){try{return e?.getItem(Ca)==="folder"?"folder":"inline"}catch{return"inline"}}function hv(e,t=Ma()){try{t?.setItem(Ca,e)}catch{}}function uv(){return he`
1067
1067
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1068
1068
  <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
1069
1069
  </svg>
1070
- `}function Ra(){return he`
1070
+ `}function Aa(){return he`
1071
1071
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1072
1072
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1073
1073
  <path d="M21 3 11.5 12.5"></path>
1074
1074
  </svg>
1075
- `}function iv(){return he`
1075
+ `}function fv(){return he`
1076
1076
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1077
1077
  <path d="M4 7h11"></path>
1078
1078
  <path d="M4 12h7"></path>
1079
1079
  <path d="M4 17h7"></path>
1080
1080
  <path d="m15 14 5 3-5 3z"></path>
1081
1081
  </svg>
1082
- `}function sv(){return Ra()}function ov(){return he`
1082
+ `}function gv(){return Aa()}function mv(){return he`
1083
1083
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1084
1084
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1085
1085
  </svg>
1086
- `}function rv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,f=20-h,v=p<e.filled;return he`<rect class=${v?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${f} width=${n} height=${h} rx="1"></rect>`});return he`
1086
+ `}function vv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,f=20-h,v=p<e.filled;return he`<rect class=${v?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${f} width=${n} height=${h} rx="1"></rect>`});return he`
1087
1087
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1088
1088
  ${a}
1089
1089
  </svg>
1090
- `}const nv=["off","minimal","low","medium","high","xhigh"];function Ds(e){return e===void 0||e===""?"off":e}function av(e,t){const i=t.length>=2?t:nv,s=i.length-1,o=Ds(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class lv extends ro{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===so.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 o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const bo=oo(lv);var cv=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,Bi=(e,t,i,s)=>{for(var o=s>1?void 0:s?dv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&cv(t,i,o),o};let ht=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1090
+ `}const bv=["off","minimal","low","medium","high","xhigh"];function _s(e){return e===void 0||e===""?"off":e}function wv(e,t){const i=t.length>=2?t:bv,s=i.length-1,o=_s(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class yv extends ao{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===ro.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 o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const yo=no(yv);var Sv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Ui=(e,t,i,s)=>{for(var o=s>1?void 0:s?xv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sv(t,i,o),o};let gt=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1091
1091
  <div class="menu">
1092
1092
  ${this.items.map((e,t)=>l`
1093
- <button class=${t===this.selectedIndex?"selected":""} ${bo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1093
+ <button class=${t===this.selectedIndex?"selected":""} ${yo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1094
1094
  <strong>${e.insertText}</strong>
1095
1095
  <span>${e.detail}</span>
1096
1096
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1097
1097
  </button>
1098
1098
  `)}
1099
1099
  </div>
1100
- `:null}};ht.styles=Df;Bi([d({attribute:!1})],ht.prototype,"items",2);Bi([d({type:Number})],ht.prototype,"selectedIndex",2);Bi([d({attribute:!1})],ht.prototype,"onPick",2);ht=Bi([E("autocomplete-menu")],ht);var pv=Object.defineProperty,hv=Object.getOwnPropertyDescriptor,N=(e,t,i,s)=>{for(var o=s>1?void 0:s?hv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&pv(t,i,o),o};let O=class extends I{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Ym(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new yo,this.readOnlyCompartment=new yo}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Jt(i,t);s!==void 0&&mi(s,this.draft);const o=Jt(this.machineId,this.sessionId);this.draft=o!==void 0?xn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=Qs(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1100
+ `:null}};gt.styles=qf;Ui([d({attribute:!1})],gt.prototype,"items",2);Ui([d({type:Number})],gt.prototype,"selectedIndex",2);Ui([d({attribute:!1})],gt.prototype,"onPick",2);gt=Ui([D("autocomplete-menu")],gt);var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,L=(e,t,i,s)=>{for(var o=s>1?void 0:s?$v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kv(t,i,o),o};let _=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=pv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new xo,this.readOnlyCompartment=new xo}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Xt(i,t);s!==void 0&&vi(s,this.draft);const o=Xt(this.machineId,this.sessionId);this.draft=o!==void 0?Pn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&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,s=this.disabled||this.sending;return l`
1101
1101
  <footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
1102
1102
  <div class="editor-wrap">
1103
1103
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
1104
1104
  <input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${o=>{this.handleFileInput(o)}} />
1105
- <button class="editor-attach icon-button" ?disabled=${s} title="Attach images" aria-label="Attach images" @click=${()=>{this.attachmentInput?.click()}}>${tv()}</button>
1105
+ <button class="editor-attach icon-button" ?disabled=${s} title="Attach images" aria-label="Attach images" @click=${()=>{this.attachmentInput?.click()}}>${uv()}</button>
1106
1106
  ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1107
1107
  ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1108
1108
  ${this.renderAttachments()}
@@ -1110,15 +1110,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1110
1110
  </div>
1111
1111
  <div class="actions">
1112
1112
  ${this.renderCompactStatus()}
1113
- <button class="icon-button send-button" ?disabled=${s} title=${i?"Queue until the current activity finishes":"Send message"} aria-label=${i?"Queue message":"Send message"} @click=${()=>{this.send("followUp")}}>${i?iv():Ra()}</button>
1114
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send("steer")}}>${sv()}</button>`:null}
1115
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${ov()}</button>
1113
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"Queue until the current activity finishes":"Send message"} aria-label=${i?"Queue message":"Send message"} @click=${()=>{this.send("followUp")}}>${i?fv():Aa()}</button>
1114
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send("steer")}}>${gv()}</button>`:null}
1115
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${mv()}</button>
1116
1116
  </div>
1117
1117
  </footer>
1118
1118
  `}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 l`
1119
1119
  <div class="compact-status" aria-label="Session status">
1120
1120
  <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1121
- <button class="select-thinking icon-button" title=${`Thinking level: ${Ds(e.thinkingLevel)}`} aria-label=${`Thinking level: ${Ds(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${rv(av(e.thinkingLevel,this.availableThinkingLevels))}</button>
1121
+ <button class="select-thinking icon-button" title=${`Thinking level: ${_s(e.thinkingLevel)}`} aria-label=${`Thinking level: ${_s(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${vv(wv(e.thinkingLevel,this.availableThinkingLevels))}</button>
1122
1122
  </div>
1123
1123
  `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:l`
1124
1124
  <div class="attachments" aria-label="Pending attachments">
@@ -1138,15 +1138,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1138
1138
  `:null}
1139
1139
  ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1140
1140
  </div>
1141
- `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",ev(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=zr(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=zr(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await Jm(e,gv);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new rt({parent:this.editorHost,state:Hi.create({doc:this.draft,extensions:[Da(),Ua(),Wa(),_a.of(" "),Oa(Ba,{fallback:!0}),rt.lineWrapping,rt.contentAttributes.of(e=>bv(e.state.sliceDoc(0,e.state.selection.main.head))),La("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(rt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Hi.readOnly.of(this.disabled)),rt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),ja.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=>Ha(e)||Fa(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>So.shift?.(e)??!1},{key:"Backspace",run:e=>qa(e)},...Na,...za])]})}))}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:xo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(rt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Hi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Jt(this.machineId,this.sessionId);t!==void 0&&mi(t,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!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(uv);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 L.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(fv);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=In(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Cn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}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):So.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,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:xo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=Jt(this.machineId,this.sessionId);e!==void 0&&Gs(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};O.styles=_f;N([d({type:Boolean})],O.prototype,"disabled",2);N([d()],O.prototype,"sessionId",2);N([d()],O.prototype,"cwd",2);N([d()],O.prototype,"machineId",2);N([d({type:Boolean})],O.prototype,"canSteer",2);N([d({type:Boolean})],O.prototype,"isCompacting",2);N([d({type:Boolean})],O.prototype,"canStop",2);N([d({attribute:!1})],O.prototype,"status",2);N([d({type:Boolean})],O.prototype,"sending",2);N([d({attribute:!1})],O.prototype,"onSend",2);N([d({attribute:!1})],O.prototype,"onStop",2);N([d({attribute:!1})],O.prototype,"onSelectModel",2);N([d({attribute:!1})],O.prototype,"onSelectThinking",2);N([d({attribute:!1})],O.prototype,"availableThinkingLevels",2);N([B(".markdown-editor")],O.prototype,"editorHost",2);N([B(".attachment-input")],O.prototype,"attachmentInput",2);N([b()],O.prototype,"draft",2);N([b()],O.prototype,"completions",2);N([b()],O.prototype,"selectedIndex",2);N([b()],O.prototype,"attachments",2);N([b()],O.prototype,"attachmentDelivery",2);N([b()],O.prototype,"attachmentError",2);O=N([E("prompt-editor")],O);function Jt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Sn(e,t)}function uv(){return[]}function fv(){return[]}function zr(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function gv(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("Failed to read file"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("Unexpected file reader result"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const mv={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},vv={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function bv(e){return Qs(e).kind==="normal"?mv:vv}function Xt(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 wv(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var yv=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,Ca=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&yv(t,i,o),o};let Ci=class extends I{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Xt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Xt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1141
+ `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",hv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Ur(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=Ur(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await cv(e,Iv);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new nt({parent:this.editorHost,state:qi.create({doc:this.draft,extensions:[La(),Va(),ja(),Na.of(" "),za(Ka,{fallback:!0}),nt.lineWrapping,nt.contentAttributes.of(e=>Av(e.state.sliceDoc(0,e.state.selection.main.head))),Fa("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(nt.editable.of(!this.disabled)),this.readOnlyCompartment.of(qi.readOnly.of(this.disabled)),nt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ba.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=>Ga(e)||qa(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>ko.shift?.(e)??!1},{key:"Backspace",run:e=>Qa(e)},...Ua,...Ha])]})}))}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:$o.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(nt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(qi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Xt(this.machineId,this.sessionId);t!==void 0&&vi(t,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!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await j.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(Pv);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 j.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(Rv);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=En(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Tn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}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):ko.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,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:$o.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=Xt(this.machineId,this.sessionId);e!==void 0&&Zs(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};_.styles=Vf;L([d({type:Boolean})],_.prototype,"disabled",2);L([d()],_.prototype,"sessionId",2);L([d()],_.prototype,"cwd",2);L([d()],_.prototype,"machineId",2);L([d()],_.prototype,"projectId",2);L([d()],_.prototype,"workspaceId",2);L([d({type:Boolean})],_.prototype,"workspaceScopedFileSuggestions",2);L([d({type:Boolean})],_.prototype,"canSteer",2);L([d({type:Boolean})],_.prototype,"isCompacting",2);L([d({type:Boolean})],_.prototype,"canStop",2);L([d({attribute:!1})],_.prototype,"status",2);L([d({type:Boolean})],_.prototype,"sending",2);L([d({attribute:!1})],_.prototype,"onSend",2);L([d({attribute:!1})],_.prototype,"onStop",2);L([d({attribute:!1})],_.prototype,"onSelectModel",2);L([d({attribute:!1})],_.prototype,"onSelectThinking",2);L([d({attribute:!1})],_.prototype,"availableThinkingLevels",2);L([B(".markdown-editor")],_.prototype,"editorHost",2);L([B(".attachment-input")],_.prototype,"attachmentInput",2);L([w()],_.prototype,"draft",2);L([w()],_.prototype,"completions",2);L([w()],_.prototype,"selectedIndex",2);L([w()],_.prototype,"attachments",2);L([w()],_.prototype,"attachmentDelivery",2);L([w()],_.prototype,"attachmentError",2);_=L([D("prompt-editor")],_);function Xt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return $n(e,t)}function Pv(){return[]}function Rv(){return[]}function Ur(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function Iv(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("Failed to read file"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("Unexpected file reader result"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const Cv={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Mv={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Av(e){return Js(e).kind==="normal"?Cv:Mv}function Yt(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 Tv(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,Ta=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ev(t,i,o),o};let Ci=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Yt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Yt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1142
1142
  <div class="bar">
1143
- <span>↑${Xt(s.input)}</span>
1144
- <span>↓${Xt(s.output)}</span>
1143
+ <span>↑${Yt(s.input)}</span>
1144
+ <span>↓${Yt(s.output)}</span>
1145
1145
  <span class="context">${i}</span>
1146
- <span>${wv(e.cost)}</span>
1146
+ <span>${Tv(e.cost)}</span>
1147
1147
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1148
1148
  </div>
1149
- `}};Ci.styles=Ef;Ca([d({attribute:!1})],Ci.prototype,"status",2);Ci=Ca([E("status-bar")],Ci);var xv=Object.defineProperty,kv=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?kv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xv(t,i,o),o};let Pe=class extends I{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1149
+ `}};Ci.styles=Hf;Ta([d({attribute:!1})],Ci.prototype,"status",2);Ci=Ta([D("status-bar")],Ci);var Wv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?_v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wv(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1150
1150
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1151
1151
  <section @mousedown=${t=>{t.stopPropagation()}}>
1152
1152
  <header>
@@ -1156,7 +1156,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1156
1156
  ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1157
1157
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1158
1158
  ${e.map((t,i)=>l`
1159
- <button class=${i===this.selectedIndex?"selected":""} ${bo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1159
+ <button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1160
1160
  <span>${t.label}</span>
1161
1161
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1162
1162
  </button>
@@ -1165,7 +1165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1165
1165
  </div>
1166
1166
  </section>
1167
1167
  </div>
1168
- `}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)}}};Pe.styles=ra;Ne([d()],Pe.prototype,"title",2);Ne([d({type:Boolean})],Pe.prototype,"searchable",2);Ne([d({attribute:!1})],Pe.prototype,"options",2);Ne([d({attribute:!1})],Pe.prototype,"selectedValue",2);Ne([d({attribute:!1})],Pe.prototype,"onPick",2);Ne([d({attribute:!1})],Pe.prototype,"onCancel",2);Ne([b()],Pe.prototype,"selectedIndex",2);Ne([b()],Pe.prototype,"query",2);Pe=Ne([E("command-picker")],Pe);var $v=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$v(t,i,o),o};let Le=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1168
+ `}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)}}};Re.styles=ca;Ne([d()],Re.prototype,"title",2);Ne([d({type:Boolean})],Re.prototype,"searchable",2);Ne([d({attribute:!1})],Re.prototype,"options",2);Ne([d({attribute:!1})],Re.prototype,"selectedValue",2);Ne([d({attribute:!1})],Re.prototype,"onPick",2);Ne([d({attribute:!1})],Re.prototype,"onCancel",2);Ne([w()],Re.prototype,"selectedIndex",2);Ne([w()],Re.prototype,"query",2);Re=Ne([D("command-picker")],Re);var Ov=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?Lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ov(t,i,o),o};let Le=class extends C{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1169
1169
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1170
1170
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1171
1171
  <header>
@@ -1178,19 +1178,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1178
1178
  </header>
1179
1179
  <div class="options">
1180
1180
  ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1181
- <button class=${i===this.selectedIndex?"selected":""} ${bo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1181
+ <button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1182
1182
  <span class="main">
1183
1183
  <strong>${t.title}</strong>
1184
1184
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1185
1185
  </span>
1186
- ${t.shortcut!==void 0?l`<kbd>${ri(t.shortcut)}</kbd>`:null}
1186
+ ${t.shortcut!==void 0?l`<kbd>${ni(t.shortcut)}</kbd>`:null}
1187
1187
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1188
1188
  </button>
1189
1189
  `)}
1190
1190
  </div>
1191
1191
  </section>
1192
1192
  </div>
1193
- `}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)}};Le.styles=Wf;it([d({attribute:!1})],Le.prototype,"actions",2);it([d({attribute:!1})],Le.prototype,"onRun",2);it([d({attribute:!1})],Le.prototype,"onCancel",2);it([B("input")],Le.prototype,"input",2);it([b()],Le.prototype,"queryText",2);it([b()],Le.prototype,"selectedIndex",2);Le=it([E("action-palette")],Le);var Rv=Object.defineProperty,Cv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Cv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rv(t,i,o),o};let se=class extends I{render(){const e=this.state;return e===void 0?null:l`
1193
+ `}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)}};Le.styles=Kf;st([d({attribute:!1})],Le.prototype,"actions",2);st([d({attribute:!1})],Le.prototype,"onRun",2);st([d({attribute:!1})],Le.prototype,"onCancel",2);st([B("input")],Le.prototype,"input",2);st([w()],Le.prototype,"queryText",2);st([w()],Le.prototype,"selectedIndex",2);Le=st([D("action-palette")],Le);var jv=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&jv(t,i,o),o};let se=class extends C{render(){const e=this.state;return e===void 0?null:l`
1194
1194
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1195
1195
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1196
1196
  <header>
@@ -1213,11 +1213,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1213
1213
  <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>
1214
1214
  </div>
1215
1215
  `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>l`
1216
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Fr(t.authType)}</small></button>
1216
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Hr(t.authType)}</small></button>
1217
1217
  `)}</div>`}}renderProviderButton(e){return l`
1218
1218
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1219
- <span>${e.name}${e.status.source!==void 0?l` <em>${Mv(e)}</em>`:null}</span>
1220
- <small>${e.id} · ${Fr(e.authType)}</small>
1219
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Fv(e)}</em>`:null}</span>
1220
+ <small>${e.id} · ${Hr(e.authType)}</small>
1221
1221
  </button>
1222
1222
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1223
1223
  <div class="form">
@@ -1240,7 +1240,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1240
1240
  ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
1241
1241
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1242
1242
  </div>
1243
- `}focusInputIfNeeded(){const e=Iv(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?.()}};se.styles=[ra,_`
1243
+ `}focusInputIfNeeded(){const e=zv(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?.()}};se.styles=[ca,O`
1244
1244
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1245
1245
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1246
1246
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1255,7 +1255,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1255
1255
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1256
1256
  .inline-options { display: grid; gap: 8px; }
1257
1257
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1258
- `];be([d({attribute:!1})],se.prototype,"state",2);be([d({attribute:!1})],se.prototype,"onChooseMethod",2);be([d({attribute:!1})],se.prototype,"onSelectProvider",2);be([d({attribute:!1})],se.prototype,"onApiKeyInput",2);be([d({attribute:!1})],se.prototype,"onSaveApiKey",2);be([d({attribute:!1})],se.prototype,"onLogoutProvider",2);be([d({attribute:!1})],se.prototype,"onOAuthInput",2);be([d({attribute:!1})],se.prototype,"onOAuthRespond",2);be([d({attribute:!1})],se.prototype,"onOAuthCancel",2);be([d({attribute:!1})],se.prototype,"onCancel",2);be([B("input")],se.prototype,"input",2);se=be([E("auth-dialog")],se);function Fr(e){return e==="oauth"?"subscription":"API key"}function Iv(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 Mv(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 Tv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?Av(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Tv(t,i,o),o};let ge=class extends I{constructor(){super(...arguments),this.machineId="local",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 L.projectDirectories(this.path,this.machineId);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 l`
1258
+ `];be([d({attribute:!1})],se.prototype,"state",2);be([d({attribute:!1})],se.prototype,"onChooseMethod",2);be([d({attribute:!1})],se.prototype,"onSelectProvider",2);be([d({attribute:!1})],se.prototype,"onApiKeyInput",2);be([d({attribute:!1})],se.prototype,"onSaveApiKey",2);be([d({attribute:!1})],se.prototype,"onLogoutProvider",2);be([d({attribute:!1})],se.prototype,"onOAuthInput",2);be([d({attribute:!1})],se.prototype,"onOAuthRespond",2);be([d({attribute:!1})],se.prototype,"onOAuthCancel",2);be([d({attribute:!1})],se.prototype,"onCancel",2);be([B("input")],se.prototype,"input",2);se=be([D("auth-dialog")],se);function Hr(e){return e==="oauth"?"subscription":"API key"}function zv(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 Fv(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 Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let ge=class extends C{constructor(){super(...arguments),this.machineId="local",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 j.projectDirectories(this.path,this.machineId);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 l`
1259
1259
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1260
1260
  <section @click=${e=>{e.stopPropagation()}}>
1261
1261
  <header>
@@ -1287,7 +1287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1287
1287
  </footer>
1288
1288
  </section>
1289
1289
  </div>
1290
- `}};ge.styles=_`
1290
+ `}};ge.styles=O`
1291
1291
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1292
1292
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1293
1293
  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; }
@@ -1305,7 +1305,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1305
1305
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1306
1306
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1307
1307
  button:disabled { opacity: .5; cursor: not-allowed; }
1308
- `;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([b()],ge.prototype,"path",2);De([b()],ge.prototype,"createMissing",2);De([b()],ge.prototype,"suggestions",2);De([b()],ge.prototype,"selected",2);De([b()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([E("project-dialog")],ge);var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ev(t,i,o),o};let me=class extends I{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Wv(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&ls(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||ls(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?ls(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1308
+ `;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([w()],ge.prototype,"path",2);De([w()],ge.prototype,"createMissing",2);De([w()],ge.prototype,"suggestions",2);De([w()],ge.prototype,"selected",2);De([w()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([D("project-dialog")],ge);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Kv(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&cs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||cs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?cs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1309
1309
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1310
1310
  <section @click=${s=>{s.stopPropagation()}}>
1311
1311
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1340,7 +1340,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1340
1340
  </form>
1341
1341
  </section>
1342
1342
  </div>
1343
- `}};me.styles=_`
1343
+ `}};me.styles=O`
1344
1344
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1345
1345
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1346
1346
  section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1360,8 +1360,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1360
1360
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1361
1361
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1362
1362
  button:disabled { opacity: .5; cursor: not-allowed; }
1363
- `;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([b()],me.prototype,"url",2);We([b()],me.prototype,"name",2);We([b()],me.prototype,"token",2);We([b()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([E("machine-dialog")],me);function Wv(e){const t=e.trim();if(t==="")return"";const i=Br(t)??Br(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):_v(t)}function ls(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function Br(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function _v(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Ov(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function Lv(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1364
- `):""}}function jv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:Nv(e.allowedHostsText),i}function Nv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var zv=Object.defineProperty,Fv=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?Fv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&zv(t,i,o),o};let ve=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Ov(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Lv(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1363
+ `;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([w()],me.prototype,"url",2);We([w()],me.prototype,"name",2);We([w()],me.prototype,"token",2);We([w()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([D("machine-dialog")],me);function Kv(e){const t=e.trim();if(t==="")return"";const i=qr(t)??qr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Vv(t)}function cs(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function qr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Vv(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Gv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function Qv(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1364
+ `):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1365
+ `)??""}}function Zv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const n=Number(o);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:Jv(e.allowedHostsText);const r=Xv(e.allowedPathsText);return r.length>0&&(i.pathAccess={allowedPaths:r}),i}function Jv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Xv(e){const t=e.split(`
1366
+ `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Yv(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Yv(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}var eb=Object.defineProperty,tb=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?tb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&eb(t,i,o),o};let ve=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Gv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Qv(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1365
1367
  <div class="section-heading">
1366
1368
  <div>
1367
1369
  <h2>General configuration</h2>
@@ -1382,7 +1384,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1382
1384
  <span>Host</span>
1383
1385
  ${this.renderOverrideBadge("host")}
1384
1386
  </span>
1385
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Ur(t)})}}>
1387
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Kr(t)})}}>
1386
1388
  <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1387
1389
  </label>
1388
1390
 
@@ -1391,7 +1393,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1391
1393
  <span>Port</span>
1392
1394
  ${this.renderOverrideBadge("port")}
1393
1395
  </span>
1394
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Ur(t)})}}>
1396
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Kr(t)})}}>
1395
1397
  <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1396
1398
  </label>
1397
1399
 
@@ -1400,14 +1402,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1400
1402
  <span>Allowed hosts</span>
1401
1403
  ${this.renderOverrideBadge("allowedHosts")}
1402
1404
  </span>
1403
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Uv(t)==="all"?"all":"list"})}}>
1405
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:ob(t)==="all"?"all":"list"})}}>
1404
1406
  <option value="list">Only listed hosts</option>
1405
1407
  <option value="all">Allow every host</option>
1406
1408
  </select>
1407
- <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Hv(t)})}}></textarea>
1409
+ <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Vr(t)})}}></textarea>
1408
1410
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1409
1411
  </div>
1410
1412
 
1413
+ <label class="field">
1414
+ <span class="field-heading">
1415
+ <span>External filesystem roots</span>
1416
+ </span>
1417
+ <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:Vr(t)})}}></textarea>
1418
+ <small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1419
+ </label>
1420
+
1411
1421
  ${this.renderEffectiveConfig()}
1412
1422
 
1413
1423
  <footer class="form-actions">
@@ -1421,10 +1431,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1421
1431
  <dl>
1422
1432
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1423
1433
  <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1424
- <div><dt>Allowed hosts</dt><dd>${Bv(e.allowedHosts)}</dd></div>
1434
+ <div><dt>Allowed hosts</dt><dd>${ib(e.allowedHosts)}</dd></div>
1435
+ <div><dt>External roots</dt><dd>${sb(e.pathAccess?.allowedPaths)}</dd></div>
1425
1436
  </dl>
1426
1437
  </section>
1427
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(jv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=qv(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=_`
1438
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Zv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=rb(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=O`
1428
1439
  :host { display: block; }
1429
1440
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1430
1441
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1466,7 +1477,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1466
1477
  .section-heading .secondary { justify-self: start; }
1467
1478
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1468
1479
  }
1469
- `;_e([d({attribute:!1})],ve.prototype,"configResponse",2);_e([d({type:Boolean})],ve.prototype,"loading",2);_e([d({type:Boolean})],ve.prototype,"saving",2);_e([d()],ve.prototype,"error",2);_e([d()],ve.prototype,"savedMessage",2);_e([d({attribute:!1})],ve.prototype,"onReload",2);_e([d({attribute:!1})],ve.prototype,"onSave",2);_e([b()],ve.prototype,"draft",2);_e([b()],ve.prototype,"localError",2);ve=_e([E("settings-general-panel")],ve);function Bv(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function Ur(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Uv(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Hv(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function qv(e){return e instanceof Error?e.message:String(e)}var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kv(t,i,o),o};let Ee=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1;return l`
1480
+ `;_e([d({attribute:!1})],ve.prototype,"configResponse",2);_e([d({type:Boolean})],ve.prototype,"loading",2);_e([d({type:Boolean})],ve.prototype,"saving",2);_e([d()],ve.prototype,"error",2);_e([d()],ve.prototype,"savedMessage",2);_e([d({attribute:!1})],ve.prototype,"onReload",2);_e([d({attribute:!1})],ve.prototype,"onSave",2);_e([w()],ve.prototype,"draft",2);_e([w()],ve.prototype,"localError",2);ve=_e([D("settings-general-panel")],ve);function ib(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function sb(e){return e===void 0||e.length===0?l`<span class="muted">External paths denied</span>`:e.join(", ")}function Kr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function ob(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Vr(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function rb(e){return e instanceof Error?e.message:String(e)}var nb=Object.defineProperty,ab=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?ab(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&nb(t,i,o),o};let Ee=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return l`
1470
1481
  <div class="section-heading">
1471
1482
  <div>
1472
1483
  <h2>Session daemon</h2>
@@ -1491,20 +1502,38 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1491
1502
  type="checkbox"
1492
1503
  .checked=${i}
1493
1504
  ?disabled=${this.loading||this.saving||t}
1494
- @change=${s=>{this.toggleSpawnSessions(s)}}
1505
+ @change=${r=>{this.toggleSpawnSessions(r)}}
1495
1506
  >
1496
1507
  <span>Enable the <code>spawn_session</code> tool</span>
1497
1508
  </label>
1498
1509
  <small>When enabled, LLMs can start new sessions, constrained to a workspace (any worktree) of the same registered project so every spawned session stays visible here. On by default.</small>
1499
1510
  </div>
1511
+ <div class="field">
1512
+ <span class="field-heading">
1513
+ <span>Allow agents to start tracked subsessions</span>
1514
+ <span class="beta-badge">beta</span>
1515
+ ${s?l`<span class="override-badge">environment override</span>`:null}
1516
+ </span>
1517
+ <label class="toggle">
1518
+ <input
1519
+ type="checkbox"
1520
+ .checked=${o}
1521
+ ?disabled=${this.loading||this.saving||s||!i}
1522
+ @change=${r=>{this.toggleSubsessions(r)}}
1523
+ >
1524
+ <span>Enable the <code>spawn_subsession</code> tools</span>
1525
+ </label>
1526
+ <small>Beta: agents can start child sessions they stay attached to (<code>spawn_subsession</code>, <code>list_subsessions</code>, <code>check_subsession</code>, <code>read_subsession</code>) and are notified when a child finishes. Requires "Allow agents to start sessions". Off by default.</small>
1527
+ </div>
1500
1528
  <section class="effective-card" aria-label="Effective configuration summary">
1501
1529
  <h3>Effective after environment overrides</h3>
1502
1530
  <dl>
1503
1531
  <div><dt>Spawn sessions</dt><dd>${i?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
1532
+ <div><dt>Subsessions</dt><dd>${o?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
1504
1533
  </dl>
1505
1534
  </section>
1506
1535
  `}
1507
- `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}};Ee.styles=_`
1536
+ `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=O`
1508
1537
  :host { display: block; }
1509
1538
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1510
1539
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1532,6 +1561,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1532
1561
  .toggle input { width: 16px; height: 16px; }
1533
1562
  .toggle input:disabled { cursor: not-allowed; }
1534
1563
  .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1564
+ .beta-badge { border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); background: var(--pi-bg); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
1535
1565
  .effective-card { display: grid; gap: 10px; }
1536
1566
  .effective-card dl { display: grid; gap: 8px; margin: 0; }
1537
1567
  .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
@@ -1543,7 +1573,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1543
1573
  .section-heading .secondary { justify-self: start; }
1544
1574
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1545
1575
  }
1546
- `;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([E("settings-sessiond-panel")],Ee);var Gv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Gv(t,i,o),o};let Re=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1576
+ `;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([D("settings-sessiond-panel")],Ee);var lb=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?cb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&lb(t,i,o),o};let Ie=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1547
1577
  <div class="section-heading">
1548
1578
  <div>
1549
1579
  <h2>Plugins</h2>
@@ -1570,7 +1600,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1570
1600
  <span>${e.enabled?"Enabled":"Disabled"}</span>
1571
1601
  </label>
1572
1602
  </article>
1573
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Re.styles=_`
1603
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ie.styles=O`
1574
1604
  :host { display: block; }
1575
1605
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1576
1606
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1603,7 +1633,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1603
1633
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1604
1634
  .toggle { justify-self: start; }
1605
1635
  }
1606
- `;ze([d({attribute:!1})],Re.prototype,"pluginsResponse",2);ze([d({attribute:!1})],Re.prototype,"configResponse",2);ze([d({type:Boolean})],Re.prototype,"loading",2);ze([d({type:Boolean})],Re.prototype,"saving",2);ze([d()],Re.prototype,"error",2);ze([d()],Re.prototype,"savedMessage",2);ze([d({attribute:!1})],Re.prototype,"onReload",2);ze([d({attribute:!1})],Re.prototype,"onTogglePlugin",2);Re=ze([E("settings-plugins-panel")],Re);var Zv=Object.defineProperty,Jv=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?Jv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zv(t,i,o),o};const Hr={capture:!0};let oe=class extends I{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=On(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Ot(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=tb(this.actions),t=this.shortcutResolutions();return l`
1636
+ `;ze([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);ze([d({attribute:!1})],Ie.prototype,"configResponse",2);ze([d({type:Boolean})],Ie.prototype,"loading",2);ze([d({type:Boolean})],Ie.prototype,"saving",2);ze([d()],Ie.prototype,"error",2);ze([d()],Ie.prototype,"savedMessage",2);ze([d({attribute:!1})],Ie.prototype,"onReload",2);ze([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=ze([D("settings-plugins-panel")],Ie);var db=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&db(t,i,o),o};const Gr={capture:!0};let oe=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=zn(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Lt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=gb(this.actions),t=this.shortcutResolutions();return l`
1607
1637
  <div class="section-heading">
1608
1638
  <div>
1609
1639
  <h2>Keyboard shortcuts</h2>
@@ -1627,19 +1657,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1627
1657
  </section>
1628
1658
  `)}
1629
1659
  `}
1630
- `}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Ii(e.id,i),o=rb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Ji(r),a=n?.ok===!0?n.shortcut:ob(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=eb(t);return l`
1631
- <article class=${Xv(t)}>
1660
+ `}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Mi(e.id,i),o=wb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Xi(r),a=n?.ok===!0?n.shortcut:bb(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=fb(t);return l`
1661
+ <article class=${hb(t)}>
1632
1662
  <div class="shortcut-main">
1633
1663
  <strong>${e.title}</strong>
1634
1664
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1635
1665
  <small class="shortcut-id">${e.id}</small>
1636
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ri(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1666
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ni(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1637
1667
  </div>
1638
1668
  <div class="shortcut-editor">
1639
1669
  <div class="shortcut-status">
1640
- ${a!==void 0&&a!==""?l`<kbd>${ri(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
1641
- <small class=${u}>${nb(u)}${p?" · Unsaved":""}</small>
1642
- ${f===void 0?null:l`<small class=${Yv(t)}>${f}</small>`}
1670
+ ${a!==void 0&&a!==""?l`<kbd>${ni(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
1671
+ <small class=${u}>${yb(u)}${p?" · Unsaved":""}</small>
1672
+ ${f===void 0?null:l`<small class=${ub(t)}>${f}</small>`}
1643
1673
  </div>
1644
1674
  <label class="shortcut-input-label">
1645
1675
  <span>Shortcut</span>
@@ -1652,7 +1682,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1652
1682
  autocapitalize="off"
1653
1683
  spellcheck="false"
1654
1684
  ?disabled=${this.saving}
1655
- @input=${v=>{this.updateDraft(e.id,ab(v))}}
1685
+ @input=${v=>{this.updateDraft(e.id,Sb(v))}}
1656
1686
  >
1657
1687
  </label>
1658
1688
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1664,7 +1694,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1664
1694
  </div>
1665
1695
  </div>
1666
1696
  </article>
1667
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Ii(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ri(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Ji(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?sb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(Xs(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Ji(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Wn)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Hr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Hr),this.recordingListenerActive=!1)}};oe.styles=_`
1697
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Mi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ni(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Xi(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?vb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(eo(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Xi(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},jn)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!1)}};oe.styles=O`
1668
1698
  :host { display: block; }
1669
1699
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1670
1700
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1719,7 +1749,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1719
1749
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1720
1750
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1721
1751
  }
1722
- `;we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"configResponse",2);we([d({type:Boolean})],oe.prototype,"loading",2);we([d({type:Boolean})],oe.prototype,"saving",2);we([d()],oe.prototype,"error",2);we([d()],oe.prototype,"savedMessage",2);we([d({attribute:!1})],oe.prototype,"onReload",2);we([d({attribute:!1})],oe.prototype,"onSave",2);we([b()],oe.prototype,"drafts",2);we([b()],oe.prototype,"localError",2);we([b()],oe.prototype,"recording",2);oe=we([E("settings-shortcuts-panel")],oe);function Xv(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Yv(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function eb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function tb(e){const t=new Map;for(const i of[...e].sort(ib)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function ib(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function Ii(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function sb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ob(e,t){const i=Ii(e.id,t);if(i!==null)return i??e.shortcut}function rb(e,t){const i=Ii(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function nb(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function ab(e){return e.target instanceof HTMLInputElement?e.target.value:""}var lb=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?cb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&lb(t,i,o),o};let re=class extends I{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1752
+ `;we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"configResponse",2);we([d({type:Boolean})],oe.prototype,"loading",2);we([d({type:Boolean})],oe.prototype,"saving",2);we([d()],oe.prototype,"error",2);we([d()],oe.prototype,"savedMessage",2);we([d({attribute:!1})],oe.prototype,"onReload",2);we([d({attribute:!1})],oe.prototype,"onSave",2);we([w()],oe.prototype,"drafts",2);we([w()],oe.prototype,"localError",2);we([w()],oe.prototype,"recording",2);oe=we([D("settings-shortcuts-panel")],oe);function hb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function ub(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function fb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function gb(e){const t=new Map;for(const i of[...e].sort(mb)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function mb(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function Mi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function vb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function bb(e,t){const i=Mi(e.id,t);if(i!==null)return i??e.shortcut}function wb(e,t){const i=Mi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function yb(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function Sb(e){return e.target instanceof HTMLInputElement?e.target.value:""}var xb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xb(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1723
1753
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1724
1754
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1725
1755
  <header class="settings-header">
@@ -1789,7 +1819,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1789
1819
  <strong>${t}</strong>
1790
1820
  <small>${i}</small>
1791
1821
  </button>
1792
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([hi.config(),vs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${cs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await hi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${cs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await vs.plugins()}catch(e){this.error=`Failed to refresh plugins: ${cs(e)}`}}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};re.styles=_`
1822
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ui.config(),ws.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${ds(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ui.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${ds(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await ws.plugins()}catch(e){this.error=`Failed to refresh plugins: ${ds(e)}`}}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};re.styles=O`
1793
1823
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1794
1824
  .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
1795
1825
  .settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1816,7 +1846,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1816
1846
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1817
1847
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1818
1848
  }
1819
- `;ye([d({attribute:!1})],re.prototype,"section",2);ye([d({attribute:!1})],re.prototype,"actions",2);ye([d({attribute:!1})],re.prototype,"onNavigate",2);ye([d({attribute:!1})],re.prototype,"onClose",2);ye([d({attribute:!1})],re.prototype,"onConfigSaved",2);ye([b()],re.prototype,"configResponse",2);ye([b()],re.prototype,"pluginsResponse",2);ye([b()],re.prototype,"loading",2);ye([b()],re.prototype,"saving",2);ye([b()],re.prototype,"error",2);ye([b()],re.prototype,"savedMessage",2);re=ye([E("settings-dialog")],re);function cs(e){return e instanceof Error?e.message:String(e)}var db=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&db(t,i,o),o};let ce=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},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(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
1849
+ `;ye([d({attribute:!1})],re.prototype,"section",2);ye([d({attribute:!1})],re.prototype,"actions",2);ye([d({attribute:!1})],re.prototype,"onNavigate",2);ye([d({attribute:!1})],re.prototype,"onClose",2);ye([d({attribute:!1})],re.prototype,"onConfigSaved",2);ye([w()],re.prototype,"configResponse",2);ye([w()],re.prototype,"pluginsResponse",2);ye([w()],re.prototype,"loading",2);ye([w()],re.prototype,"saving",2);ye([w()],re.prototype,"error",2);ye([w()],re.prototype,"savedMessage",2);re=ye([D("settings-dialog")],re);function ds(e){return e instanceof Error?e.message:String(e)}var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$b(t,i,o),o};let ce=class extends C{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},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(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
1820
1850
  ${this.hideToolTabs?null:l`
1821
1851
  <header>
1822
1852
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -1846,32 +1876,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1846
1876
  <h2>${e.title}</h2>
1847
1877
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
1848
1878
  </section>
1849
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();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.workspaceHeaderStripElement(),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)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ce.styles=Mf;Ce([d({attribute:!1})],ce.prototype,"workspace",2);Ce([d({attribute:!1})],ce.prototype,"panelContext",2);Ce([d({attribute:!1})],ce.prototype,"emptyState",2);Ce([d()],ce.prototype,"tool",2);Ce([d({attribute:!1})],ce.prototype,"panels",2);Ce([d({type:Boolean})],ce.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],ce.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],ce.prototype,"workspaceHeaderStrip",2);Ce([b()],ce.prototype,"workspaceHeaderCanScrollLeft",2);Ce([b()],ce.prototype,"workspaceHeaderCanScrollRight",2);ce=Ce([E("workspace-panel")],ce);var hb=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?ub(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&hb(t,i,o),o};let ne=class extends I{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=fb(this.machines),t=gb(this.machine),i=vb(this.project),s=wb(this.workspace),o=Sb(this.session);return l`
1879
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();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.workspaceHeaderStripElement(),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)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ce.styles=Ff;Ce([d({attribute:!1})],ce.prototype,"workspace",2);Ce([d({attribute:!1})],ce.prototype,"panelContext",2);Ce([d({attribute:!1})],ce.prototype,"emptyState",2);Ce([d()],ce.prototype,"tool",2);Ce([d({attribute:!1})],ce.prototype,"panels",2);Ce([d({type:Boolean})],ce.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],ce.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],ce.prototype,"workspaceHeaderStrip",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollLeft",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollRight",2);ce=Ce([D("workspace-panel")],ce);var Rb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rb(t,i,o),o};let ne=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Cb(this.machines),t=Mb(this.machine),i=Tb(this.project),s=Db(this.workspace),o=_b(this.session);return l`
1850
1880
  <nav class=${this.contextBarClass()} aria-label="Current location">
1851
1881
  <span class="context-bar-label">Location</span>
1852
1882
  <ol class="context-items" @scroll=${this.onContextScroll}>
1853
1883
  ${e?l`
1854
1884
  <li class="context-item">
1855
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${mb(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
1885
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Ab(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
1856
1886
  <span class="context-kind">Machine</span>
1857
1887
  <span class="context-value">${t}</span>
1858
1888
  </button>
1859
1889
  </li>
1860
1890
  `:null}
1861
1891
  <li class="context-item">
1862
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${bb(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
1892
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Eb(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
1863
1893
  <span class="context-kind">Project</span>
1864
1894
  <span class="context-value">${i}</span>
1865
1895
  </button>
1866
1896
  </li>
1867
1897
  <li class="context-item">
1868
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${yb(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1898
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Wb(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1869
1899
  <span class="context-kind">Workspace</span>
1870
1900
  <span class="context-value">${s}</span>
1871
1901
  </button>
1872
1902
  </li>
1873
1903
  <li class="context-item">
1874
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${xb(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1904
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Ob(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1875
1905
  <span class="context-kind">Session</span>
1876
1906
  <span class="context-value">${o}</span>
1877
1907
  </button>
@@ -1885,7 +1915,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1885
1915
  <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1886
1916
  </svg>
1887
1917
  </button>
1888
- `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),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.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ne.styles=_`
1918
+ `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),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.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ne.styles=O`
1889
1919
  /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1890
1920
  :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1891
1921
  .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
@@ -1911,7 +1941,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1911
1941
  .context-kind { display: none; }
1912
1942
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1913
1943
  button { cursor: pointer; }
1914
- `;Se([d({attribute:!1})],ne.prototype,"machines",2);Se([d({attribute:!1})],ne.prototype,"machine",2);Se([d({attribute:!1})],ne.prototype,"project",2);Se([d({attribute:!1})],ne.prototype,"workspace",2);Se([d({attribute:!1})],ne.prototype,"session",2);Se([d({attribute:!1})],ne.prototype,"refreshControl",2);Se([d({attribute:!1})],ne.prototype,"onOpenSection",2);Se([d({attribute:!1})],ne.prototype,"onShowActions",2);Se([B(".context-items")],ne.prototype,"contextItems",2);Se([b()],ne.prototype,"canScrollLeft",2);Se([b()],ne.prototype,"canScrollRight",2);ne=Se([E("app-context-bar")],ne);function fb(e){return e.length>1}function gb(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function mb(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function vb(e){return e?.name??"No project"}function bb(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function wb(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function yb(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function Sb(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"No session"}function xb(e){return e===void 0?"No session selected":e.path}var kb=Object.defineProperty,$b=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?$b(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kb(t,i,o),o};let je=class extends I{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
1944
+ `;Se([d({attribute:!1})],ne.prototype,"machines",2);Se([d({attribute:!1})],ne.prototype,"machine",2);Se([d({attribute:!1})],ne.prototype,"project",2);Se([d({attribute:!1})],ne.prototype,"workspace",2);Se([d({attribute:!1})],ne.prototype,"session",2);Se([d({attribute:!1})],ne.prototype,"refreshControl",2);Se([d({attribute:!1})],ne.prototype,"onOpenSection",2);Se([d({attribute:!1})],ne.prototype,"onShowActions",2);Se([B(".context-items")],ne.prototype,"contextItems",2);Se([w()],ne.prototype,"canScrollLeft",2);Se([w()],ne.prototype,"canScrollRight",2);ne=Se([D("app-context-bar")],ne);function Cb(e){return e.length>1}function Mb(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function Ab(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Tb(e){return e?.name??"No project"}function Eb(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function Db(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Wb(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function _b(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"No session"}function Ob(e){return e===void 0?"No session selected":e.path}var Lb=Object.defineProperty,jb=Object.getOwnPropertyDescriptor,ot=(e,t,i,s)=>{for(var o=s>1?void 0:s?jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Lb(t,i,o),o};let je=class extends C{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
1915
1945
  <div class=${this.frameClass()}>
1916
1946
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1917
1947
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -1923,7 +1953,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1923
1953
  `})}
1924
1954
  </div>
1925
1955
  </div>
1926
- `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Vh(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),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.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=_`
1956
+ `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:ru(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),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.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=O`
1927
1957
  :host { flex: 0 0 auto; min-width: 0; }
1928
1958
  .mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
1929
1959
  .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; }
@@ -1949,12 +1979,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1949
1979
  .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
1950
1980
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1951
1981
  }
1952
- `;st([d({attribute:!1})],je.prototype,"tabs",2);st([d({attribute:!1})],je.prototype,"selectedView",2);st([d({attribute:!1})],je.prototype,"onSelect",2);st([B(".mobile-tabs")],je.prototype,"mobileTabs",2);st([b()],je.prototype,"canScrollLeft",2);st([b()],je.prototype,"canScrollRight",2);je=st([E("app-mobile-main-tabs")],je);var Pb=Object.defineProperty,Rb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pb(t,i,o),o};let te=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=ds(e,this.statuses),i=e.name;return l`
1982
+ `;ot([d({attribute:!1})],je.prototype,"tabs",2);ot([d({attribute:!1})],je.prototype,"selectedView",2);ot([d({attribute:!1})],je.prototype,"onSelect",2);ot([B(".mobile-tabs")],je.prototype,"mobileTabs",2);ot([w()],je.prototype,"canScrollLeft",2);ot([w()],je.prototype,"canScrollRight",2);je=ot([D("app-mobile-main-tabs")],je);var Nb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?zb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Nb(t,i,o),o};let te=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=ps(e,this.statuses),i=e.name;return l`
1953
1983
  <div class="machine-switcher">
1954
1984
  <button
1955
1985
  type="button"
1956
1986
  class="machine-switcher-button"
1957
- title=${Kr(e)}
1987
+ title=${Zr(e)}
1958
1988
  aria-label=${`Machine: ${i}. Switch machine.`}
1959
1989
  aria-expanded=${String(this.open)}
1960
1990
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -1965,7 +1995,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1965
1995
  <span class="machine-switcher-kicker">Machine</span>
1966
1996
  <span class="machine-switcher-label">${i}</span>
1967
1997
  </span>
1968
- <span class=${`machine-status ${t}`}>${qr(t)}</span>
1998
+ <span class=${`machine-status ${t}`}>${Qr(t)}</span>
1969
1999
  <span class="machine-chevron" aria-hidden="true">▾</span>
1970
2000
  </button>
1971
2001
  ${this.open?l`
@@ -1974,18 +2004,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1974
2004
  </div>
1975
2005
  `:null}
1976
2006
  </div>
1977
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=ds(e,this.statuses),s=na(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
2007
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=ps(e,this.statuses),s=da(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
1978
2008
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
1979
2009
  <button
1980
2010
  type="button"
1981
2011
  class="machine-option-main"
1982
- title=${Kr(e)}
2012
+ title=${Zr(e)}
1983
2013
  data-machine-id=${e.id}
1984
2014
  @click=${()=>{this.select(e)}}
1985
2015
  @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
1986
2016
  >
1987
2017
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
1988
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${qr(i)}</small>
2018
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Qr(i)}</small>
1989
2019
  </button>
1990
2020
  ${s?l`
1991
2021
  <div class="machine-option-actions">
@@ -2005,7 +2035,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2005
2035
  </div>
2006
2036
  `:null}
2007
2037
  </div>
2008
- `}renderActivity(e){const t=ds(e,this.statuses);if(t==="offline"||t==="error")return;const i=Jn(this.activities[e.id]);return ea(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Vr(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Vr(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Ut(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};te.styles=_`
2038
+ `}renderActivity(e){const t=ps(e,this.statuses);if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return oa(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Jr(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Jr(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Ht(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};te.styles=O`
2009
2039
  :host { min-width: 0; display: block; }
2010
2040
  .machine-switcher { min-width: 0; }
2011
2041
  .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
@@ -2038,10 +2068,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2038
2068
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2039
2069
  .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
2040
2070
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2041
- `;pe([d({attribute:!1})],te.prototype,"machines",2);pe([d({attribute:!1})],te.prototype,"selected",2);pe([d({attribute:!1})],te.prototype,"statuses",2);pe([d({attribute:!1})],te.prototype,"activities",2);pe([d({attribute:!1})],te.prototype,"onSelect",2);pe([d({attribute:!1})],te.prototype,"onRemove",2);pe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);pe([b()],te.prototype,"open",2);pe([b()],te.prototype,"menuStyle",2);pe([b()],te.prototype,"openActionsMachineId",2);pe([b()],te.prototype,"actionMenuStyle",2);te=pe([E("machine-switcher")],te);function ds(e,t){return t[e.id]?.status??e.status??"unknown"}function qr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Kr(e){return e.baseUrl??e.name}function Vr(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Yt(t.bottom)};`,`left: ${Yt(o)};`,`width: ${Yt(s)};`,`max-height: ${Yt(r)};`].join(" ")}function Yt(e){return`${String(Math.round(e))}px`}var Cb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cb(t,i,o),o};let x=class extends I{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2071
+ `;pe([d({attribute:!1})],te.prototype,"machines",2);pe([d({attribute:!1})],te.prototype,"selected",2);pe([d({attribute:!1})],te.prototype,"statuses",2);pe([d({attribute:!1})],te.prototype,"activities",2);pe([d({attribute:!1})],te.prototype,"onSelect",2);pe([d({attribute:!1})],te.prototype,"onRemove",2);pe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);pe([w()],te.prototype,"open",2);pe([w()],te.prototype,"menuStyle",2);pe([w()],te.prototype,"openActionsMachineId",2);pe([w()],te.prototype,"actionMenuStyle",2);te=pe([D("machine-switcher")],te);function ps(e,t){return t[e.id]?.status??e.status??"unknown"}function Qr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Zr(e){return e.baseUrl??e.name}function Jr(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ei(t.bottom)};`,`left: ${ei(o)};`,`width: ${ei(s)};`,`max-height: ${ei(r)};`].join(" ")}function ei(e){return`${String(Math.round(e))}px`}var Fb=Object.defineProperty,Bb=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fb(t,i,o),o};let x=class extends C{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2042
2072
  <header>
2043
2073
  <strong>PI WEB</strong>
2044
- ${Mi(this.machines)?l`
2074
+ ${Ai(this.machines)?l`
2045
2075
  <machine-switcher
2046
2076
  .machines=${this.machines}
2047
2077
  .selected=${this.selectedMachine}
@@ -2058,7 +2088,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2058
2088
  <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
2059
2089
  </div>
2060
2090
  </header>
2061
- ${this.compact&&Mi(this.machines)?l`
2091
+ ${this.compact&&Ai(this.machines)?l`
2062
2092
  <machine-list
2063
2093
  .machines=${this.machines}
2064
2094
  .selected=${this.selectedMachine}
@@ -2131,7 +2161,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2131
2161
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2132
2162
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2133
2163
  ></session-list>
2134
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Mb(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Tb(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=_`
2164
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Ub(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Hb(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=O`
2135
2165
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2136
2166
  :host([compact]) { flex: 1 1 auto; }
2137
2167
  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); }
@@ -2154,7 +2184,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2154
2184
  :host([compact]) workspace-list[collapsed],
2155
2185
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2156
2186
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2157
- `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([E("app-navigation-panel")],x);function Mi(e){return e.length>1}function Mb(e,t){const i=Ia(t);return i[i.indexOf(e)-1]}function Tb(e,t){const i=Ia(t);return i[i.indexOf(e)+1]??"chat"}function Ia(e){return xi.filter(t=>t!=="machines"||Mi(e))}var Ab=Object.defineProperty,Eb=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?Eb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ab(t,i,o),o};const Db=new Set(["ArrowLeft","ArrowRight","Home","End"]),Wb=420,_b=4;let K=class extends I{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2187
+ `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([D("app-navigation-panel")],x);function Ai(e){return e.length>1}function Ub(e,t){const i=Ea(t);return i[i.indexOf(e)-1]}function Hb(e,t){const i=Ea(t);return i[i.indexOf(e)+1]??"chat"}function Ea(e){return ki.filter(t=>t!=="machines"||Ai(e))}var qb=Object.defineProperty,Kb=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?Kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&qb(t,i,o),o};const Vb=new Set(["ArrowLeft","ArrowRight","Home","End"]),Gb=420,Qb=4;let K=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2158
2188
  ${this.renderResizeHandle()}
2159
2189
  <button
2160
2190
  type="button"
@@ -2165,7 +2195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2165
2195
  aria-expanded=${String(!this.collapsed)}
2166
2196
  @click=${()=>{this.onToggle?.()}}
2167
2197
  >${this.renderIcon()}</button>
2168
- `}renderResizeHandle(){if(!this.resizable)return z;const e=this.resizeConstraints();return l`
2198
+ `}renderResizeHandle(){if(!this.resizable)return F;const e=this.resizeConstraints();return l`
2169
2199
  <div
2170
2200
  class="resize-handle"
2171
2201
  role="separator"
@@ -2184,7 +2214,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2184
2214
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2185
2215
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2186
2216
  ></div>
2187
- `}resizeAriaValueNow(){return this.panelWidth===void 0?z:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=_b)&&(t.moved=!0,this.commitPanelWidth(Yu(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Db.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=ef(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Wb){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Bt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=_`
2217
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Qb)&&(t.moved=!0,this.commitPanelWidth(hf(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Vb.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=uf(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Gb){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Ut(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=O`
2188
2218
  :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
2189
2219
  :host([side="navigation"]) { grid-column: 2; }
2190
2220
  :host([side="workspace"]) { grid-column: 4; }
@@ -2203,7 +2233,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2203
2233
  @media (max-width: 760px) {
2204
2234
  :host([side="navigation"]) { display: none; }
2205
2235
  }
2206
- `;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([E("app-panel-edge-control")],K);var Ob=Object.defineProperty,Lb=Object.getOwnPropertyDescriptor,Ma=(e,t,i,s)=>{for(var o=s>1?void 0:s?Lb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ob(t,i,o),o};let Ti=class extends I{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
2236
+ `;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([D("app-panel-edge-control")],K);var Zb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,Da=(e,t,i,s)=>{for(var o=s>1?void 0:s?Jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zb(t,i,o),o};let Ti=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
2207
2237
  <button
2208
2238
  class="app-refresh-button"
2209
2239
  title=${e}
@@ -2217,12 +2247,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2217
2247
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2218
2248
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2219
2249
  </svg>
2220
- `}};Ti.styles=_`
2250
+ `}};Ti.styles=O`
2221
2251
  :host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
2222
2252
  :host, :host * { -webkit-user-select: none; user-select: none; }
2223
2253
  .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
2224
2254
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2225
- `;Ma([d({attribute:!1})],Ti.prototype,"onReload",2);Ti=Ma([E("app-refresh-control")],Ti);var jb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&jb(t,i,o),o};const zb=900*1e3,Fb=750,Ws=[1e3,3e3,8e3,15e3,3e4],Gr={capture:!0},ps="auto:on",Qr="auto:off",ei="theme:",hs=jt("core:workspace.files"),us=jt("core:workspace.git"),ti=jt("core:workspace.terminal"),Bb=320,Ub=2,Hb="(min-width: 1181px)";let de=class extends I{constructor(){super(...arguments),this.state=Gc(),this.sessions=new _p(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Mp),this.activity=new Qc(()=>this.state,e=>{this.setState(e)}),this.auth=new Xc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Qp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Vp),this.projects=new ad(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new nd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new id(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new rd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new lh,this.realtime=new Yo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Yp,this.terminalSelection=new nh,this.appShell=new ju(this),this.panelCollapse=new Qu(this),this.panelResize=new Ju(this),this.navigationSections=new Ku(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=qb(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=kh()??yh,this.activeThemeId=eo,this.isRefreshingApp=!1,this.settingsSection=mr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Gr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},zb),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Gr),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Gb(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),Kb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=gr();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=Fb){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await vn.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Ta(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await hi.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(gr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?Xr():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Xr():{selectedFilePath:Gi(hs,"file"),selectedDiffPath:Gi(us,"diff"),selectedTerminalId:Gi(ti,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){es(e,{replace:!0}),xe(hs,"file",void 0,{replace:!0}),xe(us,"diff",void 0,{replace:!0}),xe(ti,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Zb(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Ws.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await fs(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),es({machineId:this.state.selectedMachine?.id,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),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(ir(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(ir(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){es(sr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){xe(hs,"file",e.selectedFilePath,{replace:!0}),xe(us,"diff",e.selectedDiffPath,{replace:!0}),xe(ti,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??eh(e.id);if(await this.restoreRouteFor(sr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}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()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=Yr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=gf(e,{api:{runTerminalCommand:(r,n)=>ct.runTerminalCommand(r,n,t),listCommandRuns:r=>ct.listCommandRuns(r,t),getCommandRun:r=>ct.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){xe(ti,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,ts(e)}closeSettings(){this.settingsSection=void 0,ts(void 0)}navigateSettings(e){this.settingsSection=e,ts(e)}restoreSettingsRoute(){this.settingsSection=mr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),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),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Yo;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Vb(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):Qb(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):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),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await ct.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=Jr(e),s=Jr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2255
+ `;Da([d({attribute:!1})],Ti.prototype,"onReload",2);Ti=Da([D("app-refresh-control")],Ti);var Xb=Object.defineProperty,Yb=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Yb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Xb(t,i,o),o};const ew=900*1e3,tw=750,Os=[1e3,3e3,8e3,15e3,3e4],Xr={capture:!0},hs="auto:on",Yr="auto:off",ti="theme:",us=Nt("core:workspace.files"),fs=Nt("core:workspace.git"),ii=Nt("core:workspace.terminal"),iw=320,sw=2,ow="(min-width: 1181px)";let de=class extends C{constructor(){super(...arguments),this.state=td(),this.sessions=new Vp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Fp),this.activity=new id(()=>this.state,e=>{this.setState(e)}),this.auth=new rd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new ah(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new rh),this.projects=new fd(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new ud(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new cd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new hd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new yh,this.realtime=new ir,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new ph,this.terminalSelection=new bh,this.appShell=new Zu(this),this.panelCollapse=new lf(this),this.panelResize=new df(this),this.navigationSections=new rf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=rw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=_h()??Eh,this.activeThemeId=io,this.isRefreshingApp=!1,this.settingsSection=wr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},ew),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!lw(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),nw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=br();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=tw){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await yn.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Wa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ui.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(br(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?sn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?sn():{selectedFilePath:Qi(us,"file"),selectedDiffPath:Qi(fs,"diff"),selectedTerminalId:Qi(ii,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){ts(e,{replace:!0}),xe(us,"file",void 0,{replace:!0}),xe(fs,"diff",void 0,{replace:!0}),xe(ii,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=dw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Os.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gs(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),ts({machineId:this.state.selectedMachine?.id,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),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(rr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(rr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ts(nr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){xe(us,"file",e.selectedFilePath,{replace:!0}),xe(fs,"diff",e.selectedDiffPath,{replace:!0}),xe(ii,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??hh(e.id);if(await this.restoreRouteFor(nr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}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()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=on(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=If(e,{api:{runTerminalCommand:(r,n)=>pt.runTerminalCommand(r,n,t),listCommandRuns:r=>pt.listCommandRuns(r,t),getCommandRun:r=>pt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){xe(ii,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,is(e)}closeSettings(){this.settingsSection=void 0,is(void 0)}navigateSettings(e){this.settingsSection=e,is(e)}restoreSettingsRoute(){this.settingsSection=wr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),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),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new ir;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>aw(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):cw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):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),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await pt.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=tn(e),s=tn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2226
2256
  <workspace-panel
2227
2257
  id="workspace-panel"
2228
2258
  .workspace=${e}
@@ -2268,7 +2298,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2268
2298
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2269
2299
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2270
2300
  ></app-panel-edge-control>
2271
- `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-Ub-Bb);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(Hb).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,pt.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,pt.sessionsReload)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}renderNavigationPanel(){return l`
2301
+ `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-sw-iw);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(ow).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsReload)}supportsWorkspaceFileSuggestions(e=g(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&ht(t,Ze.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}renderNavigationPanel(){return l`
2272
2302
  <app-navigation-panel
2273
2303
  .machines=${this.state.machines}
2274
2304
  .selectedMachine=${this.state.selectedMachine}
@@ -2284,7 +2314,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2284
2314
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2285
2315
  .workspaces=${this.state.workspaces}
2286
2316
  .selectedWorkspace=${this.state.selectedWorkspace}
2287
- .deletingWorkspaceIds=${Lh(this.state.workspaceDeletionRuns)}
2317
+ .deletingWorkspaceIds=${Qh(this.state.workspaceDeletionRuns)}
2288
2318
  .sessions=${this.state.sessions}
2289
2319
  .sessionStatuses=${this.state.sessionStatuses}
2290
2320
  .sessionActivities=${this.state.sessionActivities}
@@ -2324,14 +2354,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2324
2354
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2325
2355
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2326
2356
  ></app-navigation-panel>
2327
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Mi(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await fs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await fs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=Zr(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>bs.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Zr(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return Ru({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},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,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return uf(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>pr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>pr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>Pu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Zp(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Bn(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2357
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,o=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},o),o()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ai(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await gs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=en(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>ys.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=en(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return ju({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},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,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Pf(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>fr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>fr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>Lu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!lh(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Kn(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2328
2358
 
2329
2359
  This will run git worktree remove and delete:
2330
2360
  ${e.path}
2331
2361
 
2332
- The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await bs.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${Jb(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=Ps(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(_h(t.id));if(g(this.state)!==e)return;const s=Oh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))yi(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(yi);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=Yr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ps(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:Xb(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
2362
+ The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await ys.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${pw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=Is(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(Vh(t.id));if(g(this.state)!==e)return;const s=Gh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))Si(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(Si);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=on(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Is(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:hw(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
2333
2363
 
2334
- This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}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 o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}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(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Qr:ps;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${ei}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${ei}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ps||e===Qr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ps},this.applyPreferredTheme(!0);return}if(!e.startsWith(ei))return;const t=e.slice(ei.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Ph(t),e&&$h(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Rh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Fn(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("auto pair"),e.description!==void 0&&t.push(e.description),t.join(" · ")}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=>{const s=Yb(i);return{value:i,label:`${i}${i===t?" ✓ current":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2364
+ This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}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 o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}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(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Yr:hs;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${ti}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${ti}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hs||e===Yr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===hs},this.applyPreferredTheme(!0);return}if(!e.startsWith(ti))return;const t=e.slice(ti.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Lh(t),e&&Oh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return jh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return qn(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("auto pair"),e.description!==void 0&&t.push(e.description),t.join(" · ")}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=>{const s=uw(i);return{value:i,label:`${i}${i===t?" ✓ current":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2335
2365
  <app-context-bar
2336
2366
  .machines=${this.state.machines}
2337
2367
  .machine=${this.state.selectedMachine}
@@ -2352,14 +2382,14 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
2352
2382
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2353
2383
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2354
2384
  ${this.renderNavigationPanelEdgeControl()}
2355
- <main class=${Gn(e.mainView)}>
2385
+ <main class=${Xn(e.mainView)}>
2356
2386
  ${this.renderContextBar()}
2357
2387
  ${this.renderMobileMainTabs()}
2358
2388
  ${e.error?l`<div class="error">${e.error}</div>`:null}
2359
2389
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2360
2390
  ${e.selectedSession?l`
2361
2391
  <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
2362
- <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .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} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${(t,i,s,o)=>{this.sendPrompt(t,i,s,o)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2392
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .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} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${(t,i,s,o)=>{this.sendPrompt(t,i,s,o)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2363
2393
  <status-bar .status=${e.status}></status-bar>
2364
2394
  ${e.commandDialog!==void 0?l`<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}
2365
2395
  ${e.modelDialog!==void 0?l`<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}
@@ -2375,4 +2405,4 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
2375
2405
  ${e.themeDialog!==void 0?l`<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}
2376
2406
  ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2377
2407
  </div>
2378
- `}};de.styles=If;Ie([b()],de.prototype,"state",2);Ie([B("chat-view")],de.prototype,"chatView",2);Ie([B("prompt-editor")],de.prototype,"promptEditor",2);Ie([B("app-navigation-panel")],de.prototype,"navigationPanel",2);Ie([B("#navigation-panel")],de.prototype,"navigationPanelFrame",2);Ie([B("#workspace-panel")],de.prototype,"workspacePanelFrame",2);Ie([b()],de.prototype,"activeThemeId",2);Ie([b()],de.prototype,"isRefreshingApp",2);Ie([b()],de.prototype,"settingsSection",2);Ie([b()],de.prototype,"shortcutConfig",2);de=Ie([E("pi-web-app")],de);function qb(){const e=new ku;return e.register({id:"core",plugin:nu}),e.register({id:"themes",plugin:du}),e}function Zr(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function Kb(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Vb(e,t){return Ta(e,t)}function Ta(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Gb(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Jr(e){return Xe(e.status,e.activity)}function Qb(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Xr(){return{}}function Yr(e,t){return JSON.stringify([e,t])}function Zb(e){const t=Math.min(e,Ws.length-1);return Ws[t]??3e4}function Jb(e){return e instanceof Error?e.message:String(e)}function Xb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function fs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Yb(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)";default:return}}export{_ as a,l as b,ct as c,pw as d,B as e,cw as f,I as i,d as n,b as r,dw as s,E as t};
2408
+ `}};de.styles=zf;Me([w()],de.prototype,"state",2);Me([B("chat-view")],de.prototype,"chatView",2);Me([B("prompt-editor")],de.prototype,"promptEditor",2);Me([B("app-navigation-panel")],de.prototype,"navigationPanel",2);Me([B("#navigation-panel")],de.prototype,"navigationPanelFrame",2);Me([B("#workspace-panel")],de.prototype,"workspacePanelFrame",2);Me([w()],de.prototype,"activeThemeId",2);Me([w()],de.prototype,"isRefreshingApp",2);Me([w()],de.prototype,"settingsSection",2);Me([w()],de.prototype,"shortcutConfig",2);de=Me([D("pi-web-app")],de);function rw(){const e=new _u;return e.register({id:"core",plugin:bu}),e.register({id:"themes",plugin:xu}),e}function en(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function nw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function aw(e,t){return Wa(e,t)}function Wa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function lw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function tn(e){return Ye(e.status,e.activity)}function cw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function sn(){return{}}function on(e,t){return JSON.stringify([e,t])}function dw(e){const t=Math.min(e,Os.length-1);return Os[t]??3e4}function pw(e){return e instanceof Error?e.message:String(e)}function hw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function uw(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)";default:return}}export{O as a,l as b,pt as c,Rw as d,B as e,$w as f,C as i,d as n,w as r,Pw as s,D as t};