@jmfederico/pi-web 1.202606.2 → 1.202606.4

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 (62) hide show
  1. package/README.md +11 -6
  2. package/dist/cli.js +14 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/assets/{CodeViewer-iYSv2-dg.js → CodeViewer-CIG4PxA9.js} +1 -1
  5. package/dist/client/assets/{TerminalPanel-BpFW6j27.js → TerminalPanel-CKtvS-3H.js} +1 -1
  6. package/dist/client/assets/{index-D4dbiKXF.js → index-DDid7ddU.js} +367 -199
  7. package/dist/client/index.html +1 -1
  8. package/dist/config.js +51 -3
  9. package/dist/config.js.map +1 -1
  10. package/dist/pi-web-plugins/updates/pi-web-plugin.js +52 -56
  11. package/dist/pi-web-plugins/updates/updatesLogic.js +65 -0
  12. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +1 -5
  13. package/dist/server/app.js +5 -3
  14. package/dist/server/app.js.map +1 -1
  15. package/dist/server/configRoutes.js +7 -0
  16. package/dist/server/configRoutes.js.map +1 -1
  17. package/dist/server/index.js +2 -2
  18. package/dist/server/index.js.map +1 -1
  19. package/dist/server/piWebStatus.js +22 -9
  20. package/dist/server/piWebStatus.js.map +1 -1
  21. package/dist/server/sessiond.js +16 -2
  22. package/dist/server/sessiond.js.map +1 -1
  23. package/dist/server/sessions/attachmentService.js +61 -0
  24. package/dist/server/sessions/attachmentService.js.map +1 -0
  25. package/dist/server/sessions/oauthLoginFlowService.js +7 -0
  26. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -1
  27. package/dist/server/sessions/piSessionManagerGateway.js +11 -2
  28. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
  29. package/dist/server/sessions/piSessionService.js +107 -19
  30. package/dist/server/sessions/piSessionService.js.map +1 -1
  31. package/dist/server/sessions/sessionArchiveStore.js +4 -2
  32. package/dist/server/sessions/sessionArchiveStore.js.map +1 -1
  33. package/dist/server/sessions/sessionCommandService.js +5 -1
  34. package/dist/server/sessions/sessionCommandService.js.map +1 -1
  35. package/dist/server/sessions/sessionRoutes.js +43 -13
  36. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  37. package/dist/server/sessions/spawnSessionTool.js +36 -0
  38. package/dist/server/sessions/spawnSessionTool.js.map +1 -0
  39. package/dist/server/sessions/spawnTargetResolver.js +36 -0
  40. package/dist/server/sessions/spawnTargetResolver.js.map +1 -0
  41. package/dist/server/terminals/terminalRoutes.js +10 -4
  42. package/dist/server/terminals/terminalRoutes.js.map +1 -1
  43. package/dist/server/workingDirectory.js +44 -0
  44. package/dist/server/workingDirectory.js.map +1 -0
  45. package/dist/shared/apiTypes.d.ts +41 -3
  46. package/dist/shared/apiTypes.js +2 -0
  47. package/dist/shared/apiTypes.js.map +1 -1
  48. package/dist/shared/capabilities.js +4 -2
  49. package/dist/shared/capabilities.js.map +1 -1
  50. package/dist/shared/federatedRoutes.js +1 -0
  51. package/dist/shared/federatedRoutes.js.map +1 -1
  52. package/dist/shared/piWebStatusParsing.js +0 -15
  53. package/dist/shared/piWebStatusParsing.js.map +1 -1
  54. package/dist/shared/promptAttachments.js +73 -0
  55. package/dist/shared/promptAttachments.js.map +1 -0
  56. package/dist/shared/thinkingLevels.d.ts +27 -0
  57. package/dist/shared/thinkingLevels.js +31 -0
  58. package/dist/shared/thinkingLevels.js.map +1 -0
  59. package/dist/shared/workspaceDeletion.js +1 -1
  60. package/dist/shared/workspaceDeletion.js.map +1 -1
  61. package/docs/plugins.md +3 -3
  62. package/package.json +26 -15
@@ -1,25 +1,27 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-iYSv2-dg.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BpFW6j27.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as mo,w as tt,J as Ni,R as $a,S as Pa,G as Ra,U as Ca,V as Ia,A as Ma,W as Ta,X as Aa,Y as Ea,Z as vo,x as bo,_ as Da}from"./vendor-editor-core-B4Sq6exx.js";import{m as Wa,i as _a,d as Oa}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 Jt=globalThis,Ts=Jt.ShadowRoot&&(Jt.ShadyCSS===void 0||Jt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,As=Symbol(),wo=new WeakMap;let Qr=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==As)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(Ts&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=wo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&wo.set(i,t))}return t}toString(){return this.cssText}};const La=e=>new Qr(typeof e=="string"?e:e+"",void 0,As),W=(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 Qr(i,e,As)},ja=(e,t)=>{if(Ts)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=Jt.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},yo=Ts?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return La(i)})(e):e;const{is:Na,defineProperty:za,getOwnPropertyDescriptor:Fa,getOwnPropertyNames:Ba,getOwnPropertySymbols:Ua,getPrototypeOf:Ha}=Object,Pi=globalThis,So=Pi.trustedTypes,qa=So?So.emptyScript:"",Ka=Pi.reactiveElementPolyfillSupport,Pt=(e,t)=>e,oi={toAttribute(e,t){switch(t){case Boolean:e=e?qa: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}},Es=(e,t)=>!Na(e,t),xo={attribute:!0,type:String,converter:oi,reflect:!1,useDefault:!1,hasChanged:Es};Symbol.metadata??=Symbol("metadata"),Pi.litPropertyMetadata??=new WeakMap;let ot=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=xo){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&&za(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=Fa(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)??xo}static _$Ei(){if(this.hasOwnProperty(Pt("elementProperties")))return;const t=Ha(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Pt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Pt("properties"))){const i=this.properties,s=[...Ba(i),...Ua(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(yo(o))}else t!==void 0&&i.push(yo(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:oi).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:oi;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??Es)(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){}};ot.elementStyles=[],ot.shadowRootOptions={mode:"open"},ot[Pt("elementProperties")]=new Map,ot[Pt("finalized")]=new Map,Ka?.({ReactiveElement:ot}),(Pi.reactiveElementVersions??=[]).push("2.1.2");const Ds=globalThis,ko=e=>e,ri=Ds.trustedTypes,$o=ri?ri.createPolicy("lit-html",{createHTML:e=>e}):void 0,Zr="$lit$",ze=`lit$${Math.random().toFixed(9).slice(2)}$`,Jr="?"+ze,Va=`<${Jr}>`,Ge=document,It=()=>Ge.createComment(""),Mt=e=>e===null||typeof e!="object"&&typeof e!="function",Ws=Array.isArray,Ga=e=>Ws(e)||typeof e?.[Symbol.iterator]=="function",zi=`[
3
- \f\r]`,ft=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Po=/-->/g,Ro=/>/g,Be=RegExp(`>|${zi}(?:([^\\s"'>=/]+)(${zi}*=${zi}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Co=/'/g,Io=/"/g,Xr=/^(?:script|style|textarea|title)$/i,Yr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Yr(1),rt=Yr(2),Fe=Symbol.for("lit-noChange"),L=Symbol.for("lit-nothing"),Mo=new WeakMap,Ke=Ge.createTreeWalker(Ge,129);function en(e,t){if(!Ws(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return $o!==void 0?$o.createHTML(t):t}const Qa=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ft;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===ft?u[1]==="!--"?n=Po:u[1]!==void 0?n=Ro:u[2]!==void 0?(Xr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Be):u[3]!==void 0&&(n=Be):n===Be?u[0]===">"?(n=o??ft,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Be:u[3]==='"'?Io:Co):n===Io||n===Co?n=Be:n===Po||n===Ro?n=ft:(n=Be,o=void 0);const v=n===Be&&e[a+1].startsWith("/>")?" ":"";r+=n===ft?c+Va:h>=0?(s.push(p),c.slice(0,h)+Zr+c.slice(h)+ze+v):c+ze+(h===-2?a:v)}return[en(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Tt{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]=Qa(t,i);if(this.el=Tt.createElement(p,s),Ke.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Ke.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Zr)){const f=u[n++],v=o.getAttribute(h).split(ze),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?Ja:P[1]==="?"?Xa:P[1]==="@"?Ya:Ri}),o.removeAttribute(h)}else h.startsWith(ze)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Xr.test(o.tagName)){const h=o.textContent.split(ze),f=h.length-1;if(f>0){o.textContent=ri?ri.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],It()),Ke.nextNode(),c.push({type:2,index:++r});o.append(h[f],It())}}}else if(o.nodeType===8)if(o.data===Jr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(ze,h+1))!==-1;)c.push({type:7,index:r}),h+=ze.length-1}r++}}static createElement(t,i){const s=Ge.createElement("template");return s.innerHTML=t,s}}function at(e,t,i=e,s){if(t===Fe)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Mt(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=at(e,o._$AS(e,t.values),o,s)),t}class Za{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??Ge).importNode(i,!0);Ke.currentNode=o;let r=Ke.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ct(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new el(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Ke.nextNode(),n++)}return Ke.currentNode=Ge,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 ct{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=L,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=at(this,t,i),Mt(t)?t===L||t==null||t===""?(this._$AH!==L&&this._$AR(),this._$AH=L):t!==this._$AH&&t!==Fe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ga(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!==L&&Mt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ge.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=Tt.createElement(en(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Za(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Mo.get(t.strings);return i===void 0&&Mo.set(t.strings,i=new Tt(t)),i}k(t){Ws(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 ct(this.O(It()),this.O(It()),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=ko(t).nextSibling;ko(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Ri=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=L,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=L}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=at(this,t,i,0),n=!Mt(t)||t!==this._$AH&&t!==Fe,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=at(this,a[s+c],i,c),p===Fe&&(p=this._$AH[c]),n||=!Mt(p)||p!==this._$AH[c],p===L?t=L:t!==L&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===L?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Ja=class extends Ri{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===L?void 0:t}},Xa=class extends Ri{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==L)}},Ya=class extends Ri{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=at(this,t,i,0)??L)===Fe)return;const s=this._$AH,o=t===L&&s!==L||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==L&&(s===L||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 el{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){at(this,t)}}const tl={I:ct},il=Ds.litHtmlPolyfillSupport;il?.(Tt,ct),(Ds.litHtmlVersions??=[]).push("3.3.2");const sl=(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 ct(t.insertBefore(It(),r),r,void 0,i??{})}return o._$AI(e),o};const _s=globalThis;let C=class extends ot{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=sl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};C._$litElement$=!0,C.finalized=!0,_s.litElementHydrateSupport?.({LitElement:C});const ol=_s.litElementPolyfillSupport;ol?.({LitElement:C});(_s.litElementVersions??=[]).push("4.2.2");const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const rl={attribute:!0,type:String,converter:oi,reflect:!1,hasChanged:Es},nl=(e=rl,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"?nl(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 al=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function z(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return al(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(ll(n)??o.statusText)}const r=await o.json();return t(r)}function ll(e){if(cl(e))return typeof e.error=="string"?e.error:void 0}function cl(e){return typeof e=="object"&&e!==null}const Os={sessionsDeleteArchived:"sessions.deleteArchived"},dl=Object.values(Os),pl=new Set(dl);function hl(e){return typeof e=="string"&&pl.has(e)}function tn(e,t){return e?.capabilities?.includes(t)===!0}function Rt(e){return typeof e=="object"&&e!==null}function y(e){if(!Rt(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 pe(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function D(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 ul(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function fl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function gl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:ul(t.messages),start:pe(t,"start"),total:pe(t,"total")}}function ml(e){const t=y(e);return N(sn)(t.machines)}function sn(e){const t=y(e),i=wl(t,"kind"),s=$(t,"baseUrl"),o=on(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 vl(e){const t=y(e),i=on(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ni(t.web)},...t.sessiond===void 0?{}:{sessiond:ni(t.sessiond)},...s===void 0?{}:{error:s}}}function bl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:an(t.components)},...t.capabilities===void 0?{}:{capabilities:Ls(t.capabilities)},...i===void 0?{}:{error:i}}}function wl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function on(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 To(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function yl(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:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree")}}function ds(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:pe(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function gt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:pe(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Sl)(t.queuedMessages),...w("messageCount",Te(t,"messageCount")),tokens:xl(t.tokens),cost:pe(t,"cost"),...kl(t.model),...Ol(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function Sl(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 xl(e){const t=y(e);return{input:pe(t,"input"),output:pe(t,"output"),cacheRead:pe(t,"cacheRead"),cacheWrite:pe(t,"cacheWrite"),total:pe(t,"total")}}function rn(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",Te(t,"contextWindow")),...w("reasoning",t.reasoning)}}function kl(e){return e===void 0?{}:{model:rn(e)}}function $l(e){const t=y(e);return{models:N(rn)(t.models)}}function Pl(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Rl(e){const t=y(e);return{levels:N(Pl)(t.levels)}}function Cl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Il(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 Ml(e){const t=y(e),i=t.source===void 0?void 0:Il(t.source);return{configured:D(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Tl(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:Cl(t.authType),status:Ml(t.status)}}function Al(e){const t=y(e);return{providers:N(Tl)(t.providers)}}function Ft(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:El(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Dl(t.auth)),...w("prompt",Wl(t.prompt)),...w("select",_l(t.select))}}function El(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Dl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Wl(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,...w("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function _l(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(cn)(t.options)}}function Ol(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Lo(t,"tokens"),contextWindow:pe(t,"contextWindow"),percent:Lo(t,"percent")}}}function Ll(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,...w("description",$(t,"description"))}}function nn(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(Nl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Nl(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,...w("size",Te(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function zl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",$(t,"language")),...w("mediaType",Fl(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:pe(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function Fl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Bl(e){const t=y(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",Te(t,"ahead")),...w("behind",Te(t,"behind")),files:N(Ul)(t.files)}}function Ul(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(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 Hl(e){const t=y(e);return{...w("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function Fi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...w("exitCode",Te(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function Ct(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:ql(t.status),...w("exitCode",Te(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:Kl(t.metadata,"metadata")}}function ql(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Kl(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 Vl(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Gl(e){const t=y(e);return{workspaces:N(Vl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Eo(e){const t=y(e);return{path:m(t,"path"),exists:D(t,"exists"),config:Do(t.config),effectiveConfig:Do(t.effectiveConfig),envOverrides:Xl(t.envOverrides)}}function Do(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",Te(t,"port")),...w("allowedHosts",Ql(t.allowedHosts)),...w("shortcuts",Zl(t.shortcuts)),...w("plugins",Jl(t.plugins))}}function Ql(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 Zl(e){if(e!==void 0){if(!Rt(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 Jl(e){if(e!==void 0){if(!Rt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Rt(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&&(!Rt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Xl(e){const t=y(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts")}}function Yl(e){const t=y(e);return{plugins:N(ec)(t.plugins)}}function ec(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:tc(t.scope),machineSpecific:ic(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function tc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function ic(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:rc(t.components),release:ac(t.release),commands:lc(t.commands),messages:N(cc)(t.messages)}}function oc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:an(t.components),capabilities:Ls(t.capabilities)}}function rc(e){const t=y(e);return{web:ni(t.web),sessiond:ni(t.sessiond)}}function an(e){const t=y(e);return{web:Wo(t.web),sessiond:Wo(t.sessiond)}}function Wo(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:Ls(t.capabilities),...w("error",$(t,"error"))}}function ni(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...w("installation",nc(t.installation)),...w("error",$(t,"error"))}}function nc(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,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot"))}}function ac(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function lc(e){const t=y(e);return{...w("update",$(t,"update")),...w("restart",$(t,"restart")),...w("restartWeb",$(t,"restartWeb")),...w("restartSessiond",$(t,"restartSessiond")),...w("status",$(t,"status"))}}function cc(e){const t=y(e);return{id:m(t,"id"),severity:dc(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function ln(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Ls(e){if(!Array.isArray(e)||!e.every(hl))throw new Error("Invalid PI WEB capabilities");return e}function dc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function _o(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(cn)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...pc(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function cn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function pc(e){return e===void 0?{}:{session:ds(e)}}function Bt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function ps(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function hc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function uc(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Oo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:fl(t.sessionIds,"sessionIds"),s=Te(t,"archivedCount"),o=Te(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function fc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function gc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function mc(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Te(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 Lo(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 w(e,t){return t===void 0?{}:{[e]:t}}function vc(e){return typeof e=="string"?e:e.id}function bc(e){return typeof e=="string"?void 0:e.cwd}function wc(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 yc(e,t,i="local"){const s=new URLSearchParams,o=bc(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(vc(e))}/messages${r===""?"":`?${r}`}`}function Sc(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 M=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function xc(e){return typeof e=="string"?e:e.id}function dn(e){return typeof e=="string"?void 0:e.cwd}function pn(e,t="local"){return`${M(t)}/sessions/${encodeURIComponent(xc(e))}`}function X(e,t,i="local"){return`${pn(e,i)}/${t}`}function Ut(e,t,i="local"){return`${X(e,t,i)}${hn(e)}`}function kc(e,t="local"){return`${pn(e,t)}${hn(e)}`}function hn(e){const t=dn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function te(e,t={}){const i=dn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const un={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${M(e)}/pi-web/status`,sc),piWebRuntime:()=>S("/api/pi-web/runtime",oc)},$c={machines:()=>S("/api/machines",ml),addMachine:e=>S("/api/machines",sn,{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`,vl),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,bl)},ai={config:()=>S("/api/config",Eo),saveConfig:e=>S("/api/config",Eo,{method:"PUT",body:JSON.stringify({config:e})})},hs={plugins:()=>S("/api/plugins",Yl)},fn={workspaceActivity:(e="local")=>S(`${M(e)}/activity`,Gl)},Pc={projects:(e="local")=>S(`${M(e)}/projects`,N(To)),addProject:(e,t,i,s="local")=>S(`${M(s)}/projects`,To,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${M(t)}/projects/${encodeURIComponent(e)}`,ps,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${M(t)}/project-directories?q=${encodeURIComponent(e)}`,N(nn))},us={workspaces:(e,t="local")=>S(`${M(t)}/projects/${e}/workspaces`,N(yl)),deleteWorkspace:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ct,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,jl),workspaceFile:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,zl)},Rc={sessions:(e,t="local")=>S(`${M(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ds)),startSession:(e,t="local")=>S(`${M(t)}/sessions`,ds,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(yc(e,t,i),gl),status:(e,t="local")=>S(Ut(e,"status",t),gt),models:(e,t="local")=>S(Ut(e,"models",t),$l),setModel:(e,t,i,s="local")=>S(X(e,"model",s),gt,{method:"POST",body:te(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(X(e,"model/cycle",i),gt,{method:"POST",body:te(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Ut(e,"thinking-levels",t),Rl),setThinkingLevel:(e,t,i="local")=>S(X(e,"thinking-level",i),gt,{method:"POST",body:te(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(X(e,"thinking-level/cycle",t),gt,{method:"POST",body:te(e)}),commands:(e,t="local")=>S(Ut(e,"commands",t),N(Ll)),prompt:(e,t,i,s="local")=>S(X(e,"prompt",s),Bt,{method:"POST",body:te(e,i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>S(X(e,"shell",i),Bt,{method:"POST",body:te(e,{text:t})}),runCommand:(e,t,i="local")=>S(X(e,"commands/run",i),_o,{method:"POST",body:te(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(X(e,"commands/respond",s),_o,{method:"POST",body:te(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(X(e,"abort",t),hc,{method:"POST",body:te(e)}),stop:(e,t="local")=>S(X(e,"stop",t),uc,{method:"POST",body:te(e)}),archive:(e,t="local")=>S(X(e,"archive",t),Oo,{method:"POST",body:te(e)}),archiveWithDescendants:(e,t="local")=>S(X(e,"archive-tree",t),Oo,{method:"POST",body:te(e)}),restore:(e,t="local")=>S(X(e,"restore",t),fc,{method:"POST",body:te(e)}),deleteArchived:(e,t="local")=>S(kc(e,t),gc,{method:"DELETE"}),detachParent:(e,t="local")=>S(X(e,"detach-parent",t),mc,{method:"POST",body:te(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(`${M(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Al)},saveApiKey:(e,t,i="local")=>S(`${M(i)}/auth/api-key`,Bt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${M(t)}/auth/logout`,Bt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${M(t)}/auth/oauth`,Ft,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}`,Ft),respondOAuthFlow:(e,t,i,s="local")=>S(`${M(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Ft,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Ft,{method:"POST"})},nt={terminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Fi)),startTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Fi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ps,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ps,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Fi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ct,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${M(t)}/terminal-command-runs${Ic(e)}`,N(Ct)),getCommandRun:(e,t="local")=>Cc(e,t),cancelCommandRun:(e,t="local")=>S(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ct,{method:"POST"})};async function Cc(e,t){const i=await fetch(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Mc(s)??i.statusText)}return Ct(await i.json())}}function Ic(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 Mc(e){if(!Tc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Tc(e){return typeof e=="object"&&e!==null}const Ac={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),S(`${M(i.machineId)}/files?${s.toString()}`,N(nn))}},Ec={gitStatus:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Bl),gitDiff:(e,t,i,s="local")=>S(wc(s,e,t,i),Hl)},O={...un,...$c,...ai,...hs,...fn,...Pc,...us,...Rc,...nt,...Ac,...Ec};function Dc(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(`${Ns()}${js(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function Mb(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ns()}${js(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Wc(e="local"){return new WebSocket(`${Ns()}${js(e)}/events`)}function js(e){return`/api/machines/${encodeURIComponent(e)}`}function Ns(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Xt(){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 _c(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,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 Ci(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function gn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const mn="local";function Bi(e,t){return`${e}:${t}`}function vn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??mn}class Oc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??fn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Lc(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 Lc(e){const t={};for(const i of e.workspaces)gn(i)&&(t[i.cwd]=i);return t}function jc(e,t){const i={...e};return gn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Nc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??O,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=zc(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 zc(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 Dt(e){return e.replaceAll(":",".")}function Fc(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 Ui(e,t){const i=Fc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function Se(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));Bc(o,s)}function Bc(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 jo=Dt("core:workspace.files");class Uc{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 O.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await O.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:qc(this.getState().expandedDirs,t)});return}try{const o=await O.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"}),Se(jo,"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 O.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(Hc(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Se(jo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function Hc(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function qc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const No=Dt("core:workspace.git");class Kc{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await O.gitStatus(t.id,i.id,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}),Se(No,"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"}),Se(No,"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([O.gitDiff(i.id,s.id,{path:t},g(this.getState())),O.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 Vc{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 O.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:zo(this.getState().machineActivities,o),machineRuntimes:zo(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:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Xt()}),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 O.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 O.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:Hi(this.getState().machineStatuses,t.id),machineRuntimes:Hi(this.getState().machineRuntimes,t.id),machineActivities:Hi(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 O.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 O.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 O.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=>O.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=>O.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 Hi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function zo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Gc{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 O.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 O.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 O.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 fs="pi-web:cached-new-sessions:v1",Qc="browserCachedNew",dt="local";function Wt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=dt,i=Wt()){if(e.messageCount!==0||e.archived===!0)return;const s=zs(i).filter(o=>o.id!==e.id||o.machineId!==t);Fs([gs(e,t),...s],i)}function gs(e,t=dt){return{...e,browserCachedNew:!0,machineId:t}}function Bo(e,t=dt,i=Wt()){const s=zs(i).filter(o=>o.id!==e||o.machineId!==t);Fs(s,i)}function Zc(e,t,i=dt,s=Wt()){const o=new Set(t.map(c=>c.id)),r=zs(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Fs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ae(e){return e===void 0?!1:Yc(e)&&e.browserCachedNew===!0}function Jc(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:dt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function zs(e=Wt()){try{const t=e?.getItem(fs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Xc(s)):[]}catch{return[]}}function Fs(e,t=Wt()){try{e.length===0?t?.removeItem(fs):t?.setItem(fs,JSON.stringify(e))}catch{}}function Xc(e){if(!ed(e))return[];const t=it(e,"id"),i=it(e,"path"),s=it(e,"cwd"),o=it(e,"created"),r=it(e,"modified"),n=it(e,"firstMessage"),a=td(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=qi(e,"name"),p=qi(e,"parentSessionPath"),u=qi(e,"machineId")??dt;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 Yc(e){return Qc in e}function ed(e){return typeof e=="object"&&e!==null}function it(e,t){const i=e[t];return typeof i=="string"?i:void 0}function qi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function td(e,t){const i=e[t];return typeof i=="number"?i:void 0}function id(e){return bd(e.flatMap(Bs)).filter(t=>t.parts.length>0)}function $e(e,t){return{role:e,parts:[{type:"text",text:t}]}}function mt(e,t){const i=dd(t);return i===void 0?e:{...e,meta:i}}function sd(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,$e(t,i)]}function od(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 Bs(e){if(nd(e))return[e];if(_(e,"role")==="bashExecution")return[mt(ud(e),e)];const t=fd(_(e,"role")),i=gd(ue(e,"content"),e),s=t==="user"?ad(i):void 0;if(s!==void 0)return s.map(p=>mt(p,e));const o=cd(e);if(t==="tool")return[mt({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?[mt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=rd(e);return c===void 0?a:[...a,mt(c,e)]}function rd(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return $e("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function nd(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ue(e,"parts"))}function ad(e){if(e.length!==1||e[0]?.type!=="text")return;const t=ld(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 ld(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 cd(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function dd(e){const t=pd(ue(e,"timestamp")),i=hd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function pd(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 hd(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(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 ud(e){const t=_(e,"command")??"",i=Yt(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ue(e,"output");s!=null&&i.push("",ci(s));const o=ue(e,"exitCode");o!=null&&i.push("",`exit ${ci(o)}`),Yt(e,"cancelled")===!0&&i.push("","cancelled"),Yt(e,"truncated")===!0&&i.push("","output truncated");const r=_(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function fd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function gd(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),o=_(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=_(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=_(i,"name")??"tool",n=ue(i,"arguments"),a=r==="read"?vd(_(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=_(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:r,summary:_t(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:Uo(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?md(i.text,t):i):Uo(e)}function md(e,t){const i=_(t,"toolCallId"),s=ue(t,"content"),o=ue(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:Yt(t,"isError")===!0}}function vd(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 bd(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=wd(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&&yd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function wd(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 yd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=li(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 li(e){const t=ue(e,"preview");if(!Us(t))return;const i=_(t,"diff"),s=_(t,"error"),o=xd(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 Uo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:_t(e)}]:[{type:"text",text:ci(e)}]}function _t(e){if(!Us(e))return ci(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(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}: ${Sd(n)}`).join(" · ")}function Sd(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 Us(e){return typeof e=="object"&&e!==null}function ue(e,t){return Us(e)?e[t]:void 0}function _(e,t){const i=ue(e,t);return typeof i=="string"?i:void 0}function Yt(e,t){const i=ue(e,t);return typeof i=="boolean"?i:void 0}function xd(e,t){const i=ue(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function ci(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const kd="pi-web:prompt-draft:";function di(e){return`${kd}${e}`}function Ii(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function bn(e,t=Ii()){try{return t?.getItem(di(e))??""}catch{return""}}function pi(e,t,i=Ii()){try{t?i?.setItem(di(e),t):i?.removeItem(di(e))}catch{}}function Hs(e,t=Ii()){try{t?.removeItem(di(e))}catch{}}function $d(e,t,i=Ii()){const s=bn(e,i);s!==""&&(pi(t,s,i),Hs(e,i))}function Pd(e,t){return $e("bash",`${t===!0?`excluded from context
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
6
6
 
7
- `:""}$ ${e}`)}function Rd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,$e("bash",t)];const o=Id(s.text)?"":`
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)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Cd(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 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(`
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 Id(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function Fd(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function Md(e,t){if(t.type==="message.append")return zd(e,t.message);if(t.type==="assistant.delta")return sd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return od(e,t.text);if(t.type==="tool.start")return Wd(e,t);if(t.type==="tool.update")return yn(e,t.toolCallId,i=>_d(i,t));if(t.type==="tool.end")return wn(e,t.toolCallId,t.toolName,_t(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Pd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Rd(e,t.chunk);if(t.type==="shell.end")return Cd(e,t);if(t.type==="command.output")return[...e,$e(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,$e("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Td(e,t.message)}function Td(e,t){const i=Od(t);if(i!==void 0)return wn(e,i.toolCallId,i.toolName,_t(i.content),i.text,i.isError,i.content,i.details);const s=Bs(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Ed(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Ad(r,n),e)}function Ad(e,t){const i=Ld(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"||Nd(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Ed(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Dd(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 Wd(e,t){const i=t.toolName==="read"?Dd(Ve(t.args,"path")):void 0;if(i!==void 0)return Fd(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||_t(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function _d(e,t){const i=li(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 wn(e,t,i,s,o,r,n,a){const c=yn(e,t,h=>{const f=li(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=li(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 yn(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 Od(e){if(Ve(e,"role")!=="toolResult")return;const t=Ve(e,"toolCallId"),i=ui(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Ve(e,"toolName")??"tool",text:Sn(i),isError:Ud(e,"isError")===!0,content:i,details:ui(e,"details")}}function Sn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Sn).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=Ve(e,"text")??Ve(e,"content")??Ve(e,"output");if(t!==void 0)return t}return""}function Ld(e,t){const i=hi(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=hi(o);if(xn(r,i))return s}return-1}function hi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function xn(e,t){return e.length===t.length&&e.every((i,s)=>jd(i,t[s]))}function jd(e,t){return t===void 0?!1:Ho(e.path)===Ho(t.path)||e.name===t.name}function Ho(e){return e.replace(/\\/g,"/")}function Nd(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 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(`
18
18
 
19
- `)}function zd(e,t){const i=Bs(t);return i.length===0?e:[...e,...i]}function Fd(e,t){const i=e.at(-1);return t.role==="skill"&&xn(hi(i),hi(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Bd(e){return typeof e=="object"&&e!==null}function ui(e,t){return Bd(e)?e[t]:void 0}function Ve(e,t){const i=ui(e,t);return typeof i=="string"?i:void 0}function Ud(e,t){const i=ui(e,t);return typeof i=="boolean"?i:void 0}const Hd="pi-web:chat-history:v2:",qd=1800*1e3;function Kd(e){try{const t=sessionStorage.getItem(ms(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Jd(i))return;if(Date.now()-i.savedAt>qd){sessionStorage.removeItem(ms(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Vd(e,t){try{sessionStorage.setItem(ms(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Gd(e,t){if(e===void 0||!vs(e))return t;if(!vs(t))return e;if(Qd(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 Ko(o,i,e),Ko(o,i,t),Zd(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Qd(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Zd(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Ko(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function ms(e){return`${Hd}${e}`}function Jd(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"&&vs({messages:t,start:i,total:s})}function vs(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(Xd)}function Xd(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 Yd={read:Kd,write:Vd};class ep{constructor(t=Yd){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Vo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Gd(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Vo(s)}applyLiveEvent(t,i){return Md(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Vo(e){const t=e?.start??0;return{messages:id(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function kn(e,t=e.length){const i=e.slice(0,t),s=ip(i,t);if(s!==void 0)return s;const o=sp(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 tp(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 sp(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),o=Go(s,"@ "),r=Go(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 Go(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||op(e[i-1]))return i;return-1}function op(e){return e===" "||e===" "}function qs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:np(e).startsWith("/")?{kind:"command"}:kn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function rp(e){return qs(e).kind==="shell"}function np(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class ap{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),Pn(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=Dc(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 $n(t);lp(i)&&this.onEvent?.(i)}}class Qo{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),Pn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Wc(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 $n(t);dp(i)&&this.onEvent?.(i)}}function lp(e){const t=Ks(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(t)}function cp(e){const t=Ks(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function dp(e){const t=Ks(e);return cp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Ks(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function $n(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 Pn(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 Ot(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Mi{constructor(t,i,s=Ot()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of pp(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 Vs(e){return typeof e=="string"&&e!==""?e:void 0}function pp(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!hp(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 hp(e){return!up(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 up(e){return typeof e=="object"&&e!==null}class fp{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 gp="pi-web:session-selection:v1";class mp{constructor(t=Ot()){this.sessionIdsByCwd=new Mi(gp,Vs,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function vp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return wp(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 bp(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function wp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function yp(e,t,i){return bs(e,[t],i)}function bs(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Sp(e,t,i){return ws(e,t,[i])}function ws(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 vt=100;class xp{constructor(t,i,s,o=new fp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new ap,this.api=r.api??O,this.transcripts=r.transcripts??new ep}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.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})}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();bp(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);Fo(s,i);const o=gs(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return vp(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 h=await this.api.messages(t,{limit:vt},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:vt},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),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ae(t)&&Ap(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:vt},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){if(t.trim().startsWith("/"))return this.runCommand(t);if(rp(t))return this.runShell(t);const o=this.getState().selectedSession;if(!(!o||o.archived===!0))try{await this.api.prompt(o,t,i,g(this.getState())),this.markCachedNewSessionPersisted(o)}catch(r){this.setState({error:String(r)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,$e("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,$e("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,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(ae(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=yp(i.sessions,t.id,new Date().toISOString()),o=Sp(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||ae(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=bs(o.sessions,s,new Date().toISOString()),n=ws(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=Zo(t).filter(n=>n.archived!==!0&&!ae(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=Jo(o);if(r.length>0){const n=this.getState(),a=bs(n.sessions,r,new Date().toISOString()),c=ws(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=Zo(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||!tn(o,Os.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=Jo(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(!ae(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Bo(t.id,g(this.getState())),Hs(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 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())))}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())))}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 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:vt},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],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=$p(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return vn(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);Fo(o,s),$d(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Bo(t.id,s);const r=gs(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(!ae(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Jc(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,$e(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&pi(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)}}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"&&!Ci(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Ip(i,t.sessionId,t.messageCount),...s?{sessionActivities:kp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!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(Mp(t))return}if(Tp(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:vt},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 kp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zo(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 Jo(e){return e.filter(Pp).map(t=>t.value)}function $p(e){return e.filter(Rp).map(t=>Cp(t.reason))}function Pp(e){return e.status==="fulfilled"}function Rp(e){return e.status==="rejected"}function Cp(e){return e instanceof Error?e.message:String(e)}function Ip(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 Mp(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 Tp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Ap(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ep{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 Dp="pi-web:workspace-selection:v1";class Wp{constructor(t=Ot()){this.workspaceIdsByProject=new Mi(Dp,Vs,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function _p(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 Op{constructor(t,i,s,o,r=new Ep,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??O}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Xt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Bi(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,...Xt()});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=_p(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bi(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:Bi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Xt()});try{const o=Zc(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 Lp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function jp(e){return e.find(t=>t.isMain)??e[0]}const Np="pi-web:machine-navigation:v1";class zp{constructor(t=Ot()){this.snapshotsByMachine=new Mi(Np,Bp,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?er(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,er(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Fp(e){return{machineId:e,surface:{}}}function Xo(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??mn,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 Yo(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 er(e){return{...e,surface:{...e.surface}}}function Bp(e){if(!Cn(e))return;const t=We(e,"machineId");if(t===void 0)return;const i=Rn(We(e,"tool")),s=Hp(We(e,"view"));return{machineId:t,projectId:We(e,"projectId"),workspaceId:We(e,"workspaceId"),sessionId:We(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Up(e.surface)}}function Up(e){return Cn(e)?{selectedFilePath:We(e,"selectedFilePath"),selectedDiffPath:We(e,"selectedDiffPath"),selectedTerminalId:We(e,"selectedTerminalId")}:{}}function Hp(e){return e==="navigation"||e==="chat"?e:Rn(e)}function Rn(e){return qp(e)?e:void 0}function qp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function We(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Cn(e){return typeof e=="object"&&e!==null}const Kp="pi-web:terminal-selection:v1";class Vp{constructor(t=Ot()){this.terminalIdsByCwd=new Mi(Kp,Vs,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 Tb(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 Ab(e){return e.find(t=>!t.exited)??e[0]}const In=1200,Gp=["mod","alt","shift"];class Qp{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Tn(t);if(o===void 0)return!1;const r=Gs(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(),!At(o))return!1}else if(!At(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>rh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Qs(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},In)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Gs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Zp(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(ys)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Yp),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=eh(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:tr(u),v=h?[...a.get(p)??[]].sort(ys).map(tr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Ki(e){return An(e,{requireFirstChordActivator:!0})}function Mn(e){const t=An(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ei(e){return Mn(e).map(t=>t.split("+").map(Dn).join("+")).join(" ")}function Tn(e){if(e.isComposing)return;const t=sh(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 At(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Zp(e,t,i){const s=Jp(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Mn(o),n=r[0];if(!(n===void 0||!At(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Xp(r),order:i}}function Jp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Xp(e){return e.join("\0")}function tr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ys(e,t){return ir(e.source)-ir(t.source)||sr(e.action.id,t.action.id)||sr(e.action.title,t.action.title)||e.order-t.order}function Yp(e,t){return e.tokens.length-t.tokens.length||ys(e,t)}function eh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Qs(e.tokens,i.tokens))}function ir(e){switch(e){case"custom":return 0;case"default":return 1}}function sr(e,t){return e<t?-1:e>t?1:0}function An(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=th(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!At(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 th(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 ${Dn(n)} modifiers.`};i.add(n);continue}const a=En(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:[...Gp.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 En(e){const t=oh(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 sh(e){if(e===" ")return"space";const t=e.toLowerCase();return En(t)}function oh(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 Dn(e){return e==="mod"?or()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?or()?"⌥":"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 rh(e,t){return e.length===t.length&&Qs(e,t)}function Qs(e,t){return t.every((i,s)=>e[s]===i)}function or(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Zs="themes:classic",nh="themes:pi-web-dark",ah={themeId:nh,auto:!0},Wn="pi-web-app-theme",lh=["--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"],ch=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function dh(){try{const e=window.localStorage.getItem(Wn);return e===null?void 0:gh(e)}catch{return}}function ph(e){try{window.localStorage.setItem(Wn,JSON.stringify(e))}catch{}}function hh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of lh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function uh(e){const t=fh(e.themes,e.fallbackThemeId??Zs),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=_n(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 fh(e,t=Zs){return e.find(i=>i.id===t)??e[0]}function _n(e,t){return e.find(i=>i.light===t||i.dark===t)}function gh(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(!vh(e))return!1;const t=e.themeId,i=e.auto;return bh(t)&&typeof i=="boolean"}function vh(e){return typeof e=="object"&&e!==null}function bh(e){return typeof e=="string"&&ch.test(e)}const wh="workspace.delete",yh="pi.operation",Sh="target.workspaceId";function xh(e){return{...e===void 0?{}:{projectId:e},metadata:{[yh]:wh}}}function kh(e){const t={};for(const i of e){const s=Ss(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 $h(e){return Object.entries(e).filter(([,t])=>fi(t)).map(([t])=>t)}function On(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&fi(i)}function Ss(e){return e.metadata[Sh]}function fi(e){return e.status==="queued"||e.status==="running"}function Ph(){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:bt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:rr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:bt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:bt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:rr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:bt,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:Rh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:bt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Ch,run:e=>e.archiveSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Ih,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ci(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function bt(e){return e.state.selectedWorkspace!==void 0}function rr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Rh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!On(e.state,t)}function Ch(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ae(t)}function Ih(e){return ae(e.state.selectedSession)}const Mh="modulepreload",Th=function(e){return"/"+e},nr={},Ln=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=Th(p),p in nr)return;nr[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":Mh,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)})},Ah=10*1024*1024,Eh="10 MB";function Dh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ti(e)}function ti(e){switch(e){case"navigation":return rt`
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}
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`
23
25
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
24
26
  <circle cx="6" cy="7" r="1.5"></circle>
25
27
  <path d="M10 7h8"></path>
@@ -28,17 +30,17 @@ ${o.join(`
28
30
  <circle cx="6" cy="17" r="1.5"></circle>
29
31
  <path d="M10 17h8"></path>
30
32
  </svg>
31
- `;case"chat":return rt`
33
+ `;case"chat":return he`
32
34
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
33
35
  <path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
34
36
  <path d="M8 9h8"></path>
35
37
  <path d="M8 13h5"></path>
36
38
  </svg>
37
- `;case"files":return rt`
39
+ `;case"files":return he`
38
40
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
39
41
  <path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
40
42
  </svg>
41
- `;case"git":return rt`
43
+ `;case"git":return he`
42
44
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
43
45
  <circle cx="6" cy="6" r="2"></circle>
44
46
  <circle cx="18" cy="6" r="2"></circle>
@@ -47,13 +49,13 @@ ${o.join(`
47
49
  <path d="M6 8v2a6 6 0 0 0 6 6"></path>
48
50
  <path d="M18 8v2a6 6 0 0 1-6 6"></path>
49
51
  </svg>
50
- `;case"terminal":return rt`
52
+ `;case"terminal":return he`
51
53
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
52
54
  <rect x="3" y="5" width="18" height="14" rx="2"></rect>
53
55
  <path d="m7 10 3 3-3 3"></path>
54
56
  <path d="M12 16h5"></path>
55
57
  </svg>
56
- `}}function Wh(){return[{id:"workspace.files",title:"Files",icon:ti("files"),order:10,render:_h},{id:"workspace.git",title:"Git",icon:ti("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:zh},{id:"workspace.terminal",title:"Terminal",icon:ti("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Nh}]}function _h(e){return l`
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`
57
59
  <section class="toolbar">
58
60
  <strong>Files</strong>
59
61
  ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
@@ -61,30 +63,30 @@ ${o.join(`
61
63
  </section>
62
64
  <section class="split">
63
65
  <div class="list tree">
64
- ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>jn(e,t,0))}
66
+ ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Hn(e,t,0))}
65
67
  </div>
66
68
  <div class="viewer">
67
- ${Lh(e)}
69
+ ${Jh(e)}
68
70
  </div>
69
71
  </section>
70
- `}function jn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
71
- <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Oh(e,t)}}>
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
74
  <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
73
75
  <span>${t.name}</span>
74
76
  </button>
75
- ${o?s.map(n=>jn(e,n,i+1)):null}
76
- `}function Oh(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function Lh(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"?jh(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${xs(t.size)}</p>`:(Nn(),l`
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
79
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
78
80
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
79
- `)}function jh(e,t){const i=`${t.mimeType??"image"} · ${xs(t.size)}`;if(t.size>Ah)return l`
81
+ `)}function Xh(e,t){const i=`${t.mimeType??"image"} · ${Rs(t.size)}`;if(t.size>qh)return l`
80
82
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
81
- <p class="muted">Image too large to preview: ${xs(t.size)} · limit ${Eh}</p>
82
- `;const s=Sc(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: ${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
85
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
84
86
  <div class="image-preview">
85
87
  <img src=${s} alt=${t.path} decoding="async" />
86
88
  </div>
87
- `}function Nh(e){return Uh(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function zh(e){const t=e.gitStatus;return l`
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`
88
90
  <section class="toolbar">
89
91
  <strong>Git</strong>
90
92
  ${e.gitStale?l`<span class="stale">stale</span>`:null}
@@ -93,29 +95,29 @@ ${o.join(`
93
95
  <section class="split">
94
96
  <div class="list">
95
97
  ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
96
- <p class="summary">${Hh(t)}</p>
98
+ <p class="summary">${ou(t)}</p>
97
99
  ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
98
100
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
99
- <span>${qh(i.index,i.workingTree)}</span>
101
+ <span>${ru(i.index,i.workingTree)}</span>
100
102
  <span>${i.path}</span>
101
103
  </button>
102
104
  `)}
103
105
  `:l`<p class="muted">Not a git repository.</p>`}
104
106
  </div>
105
107
  <div class="viewer">
106
- ${Fh(e)}
108
+ ${tu(e)}
107
109
  </div>
108
110
  </section>
109
- `}function Fh(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 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`
110
112
  <div class=${s.length===1?"diffs single":"diffs"}>
111
- ${s.map(o=>Bh(o))}
113
+ ${s.map(o=>iu(o))}
112
114
  </div>
113
- `}function Bh(e){return Nn(),l`
115
+ `}function iu(e){return qn(),l`
114
116
  <section class="diff-section">
115
117
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
116
118
  <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
117
119
  </section>
118
- `}function Nn(){Ln(()=>import("./CodeViewer-iYSv2-dg.js"),__vite__mapDeps([0,1,2,3]))}function Uh(){Ln(()=>import("./TerminalPanel-BpFW6j27.js"),__vite__mapDeps([4,5,6,1,2]))}function Hh(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 qh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function xs(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`${Vi(t)} KB`;const i=t/1024;return i<1024?`${Vi(i)} MB`:`${Vi(i/1024)} GB`}function Vi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Kh={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Ph(),workspacePanels:Wh()}})},Vh={"--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"},Gh={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#3d4a78","--pi-selection-bg":"#151b31","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Qh={"--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"},Zh={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:Gh},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Qh},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:Vh}],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"}]}})},Jh=/^[a-z][a-z0-9.-]*$/u;function Xh(e){return Jh.test(e)}const Yh="machine.";function eu(e,t){if(e==="")throw new Error("Machine id is required");if(!Xh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${tu(e)}.${t}`}function tu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function ar(e="/pi-web-plugins/manifest.json",t={}){const i=await iu(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=ru(n,r);s.push({id:t.machineId===void 0?o.id:eu(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 iu(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 su(await t.json())}}function su(e){if(!gi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!gi(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:ou(t.machineSpecific)}})}}function ou(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function ru(e,t){if(!gi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nu(e){return gi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function gi(e){return typeof e=="object"&&e!==null}const au=/^[a-z][a-z0-9.-]*$/u,lu=/^[a-z][a-z0-9.-]*$/u,zn=new WeakMap,Fn=new WeakMap;class cu{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:rt}).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&&uu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=gu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=du(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?.(Gi(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(Gi(c,t)):void 0},render:c=>i.render(Gi(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(!au.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lu.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}: ${fu(i)}`);return i}}function du(e,t){return zn.get(e)?.(t)??e}function Gi(e,t){return Fn.get(e)?.(t)??e}function pu(e,t){return zn.set(e,t),e}function hu(e,t){return Fn.set(e,t),e}function uu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function fu(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 gu(e){return e.state.selectedMachine?.id??"local"}const mu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vu(){return typeof window>"u"||!("matchMedia"in window)?[]:mu.map(e=>window.matchMedia(e))}function lr(e,t=bu()){return e.some(i=>i.matches)||wu(t)}function bu(){return typeof navigator>"u"?void 0:navigator}function wu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yu=250;class Su{constructor(t=xu()){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()},yu)}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 xu(){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 ku="(max-width: 760px)";class $u{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=lr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Pu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Su,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=lr(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 Pu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(ku)}const mi=["machines","projects","workspaces","sessions"];function Ru(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Js(e,t){if(e!=="none")return e??Ru(t)}function Cu(e,t){return t.isMobileLayout?Js(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Iu(e,t,i){return Js(e,i.state)===t?"none":t}function Mu(e,t,i){return i?t:e}function Tu(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Du(i)}function Au(e){return mi[mi.indexOf(e)+1]}class Eu{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Js(this.expanded,this.getState())}isCollapsed(t){return Cu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Iu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Tu(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Mu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Au(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){Wu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Du(e){const t=new Set(e);return mi.filter(i=>t.has(i))}function Wu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _u{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",Bn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Bn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const ks="pi-web:panel-sizes:v1",Ou={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Lu{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Xs(),this.panelSizes=Fu(this.storage)}hostConnected(){}constraints(t){return Lt(t)}panelWidth(t,i){return he(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=he(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Hu(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=qu(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(){Bu(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${dr(he("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${dr(he("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Lt(e){return Ou[e]}function ju(e,t,i){return e==="navigation"?i-t:t-i}function Nu(e,t,i,s,o=Lt(e)){return he(e,t+ju(e,i,s),o)}function zu(e,t,i,s={}){const o=s.constraints??Lt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Ku(e,i,r);if(n!==void 0)return he(e,t+n,o)}function he(e,t,i=Lt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Fu(e=Xs()){try{const t=e?.getItem(ks);if(t==null||t==="")return{};const i=JSON.parse(t);return Uu(i)}catch{return{}}}function Bu(e,t=Xs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ks);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=he("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=he("workspace",e.workspacePanelWidth)),t.setItem(ks,JSON.stringify(i))}catch{}}function Uu(e){if(!Vu(e)||e.version!==1)return{};const t={},i=cr(e.navigationPanelWidth),s=cr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=he("navigation",i)),s!==void 0&&(t.workspacePanelWidth=he("workspace",s)),t}function cr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hu(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function qu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ku(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 dr(e){return`${String(Math.round(e))}px`}function Xs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vu(e){return typeof e=="object"&&e!==null}function pr(){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:Gu(e.get("tool")),view:Qu(e.get("view"))}}function Qi(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 Gu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Qu(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Un(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function hr(){return Zu(new URLSearchParams(window.location.search).get("settings"))}function Zi(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 Zu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Ju(e,t){return t===void 0?e:e.map(i=>Yu(i,t))}function Xu(e,t){const i=new Set(Gs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Ju(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Hn(s):s)}function Yu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Hn(e):{...e,shortcut:i}}function Hn(e){const t={...e};return delete t.shortcut,t}function ef(e,t){const i=t.api??nt,s=t.pollIntervalMs??1e3,o=t.setTimeout??sf(),r=t.clearTimeout??of();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:tf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function tf(e,t,i,s,o){return ur(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&&ur(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function ur(e){return e.status==="succeeded"||e.status==="failed"}function sf(){return(e,t)=>globalThis.setTimeout(e,t)}function of(){return e=>{globalThis.clearTimeout(e)}}function rf(e,t){return t[e.path]}function nf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function af(e,t,i){return Kn(lf(e,t,i))}function qn(e){return Kn(Object.values(e??{}))}function Kn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function lf(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 Ht=0,cf=120;function jt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Vn():df(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-Ht,f=i.top-c-Ht;return[...h<cf&&f>h?[`bottom: ${st(r-i.top+Ht)};`,`max-height: ${st(Math.max(0,f))};`]:[`top: ${st(i.bottom+Ht)};`,`max-height: ${st(Math.max(0,h))};`],`right: ${st(Math.max(0,o-u))};`,`max-width: ${st(Math.max(0,u-n))};`].join(" ")}function df(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vn()}function Vn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function st(e){return`${String(Math.round(e))}px`}function Gn(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Ti(e,t="Active"){const i=Gn(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 Qn(e){return e.composedPath().some(t=>hf(t,pf))}function hf(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 Ai(e,t){Qn(e)||t()}function Ei(e,t){return Qn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ue(e,()=>{fr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ue(e,()=>{fr(e.currentTarget,1)}):e.key==="Home"?Ue(e,()=>{gr(e.currentTarget,0)}):e.key==="End"?Ue(e,()=>{gr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ue(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ue(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ue(e,t.cancel):!1}function Di(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 Ue(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function fr(e,t){const i=Jn(e),s=Xn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Zn(i,o+t)}function gr(e,t){const i=Jn(e);i.length!==0&&Zn(i,t<0?i.length-1:t)}function Zn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Jn(e){const t=Xn(e)?.getRootNode();return t===void 0||!uf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function uf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Xn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ff=W`
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=_`
119
121
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
120
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; }
121
123
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -209,11 +211,11 @@ ${o.join(`
209
211
  }
210
212
  status-bar { flex: 0 0 auto; }
211
213
  chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
212
- prompt-editor, chat-composer { flex: 0 0 auto; }
214
+ prompt-editor { flex: 0 0 auto; }
213
215
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
214
216
  .empty { margin: auto; color: var(--pi-muted); }
215
217
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
216
- `,gf=W`
218
+ `,Mf=_`
217
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; }
218
220
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
219
221
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -268,7 +270,7 @@ ${o.join(`
268
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); }
269
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; }
270
272
  p { margin: 10px; }
271
- `,Wi=W`
273
+ `,Ni=_`
272
274
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
273
275
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
274
276
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -310,6 +312,8 @@ ${o.join(`
310
312
  .activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
311
313
  .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
312
314
  .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
315
+ /* Client-side sending (upload in flight); distinct from server activity, which propagates to workspace/machine rows. */
316
+ .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
313
317
  .action-menu { position: relative; align-self: stretch; }
314
318
  .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
315
319
  .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
@@ -327,7 +331,7 @@ ${o.join(`
327
331
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
328
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; }
329
333
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
330
- `,mf=W`
334
+ `,Tf=_`
331
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; }
332
336
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
333
337
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -338,6 +342,7 @@ ${o.join(`
338
342
  .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
339
343
  .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
340
344
  .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
345
+ .msg.assistant { background: var(--pi-surface); }
341
346
  .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
342
347
  .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
343
348
  .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
@@ -350,6 +355,7 @@ ${o.join(`
350
355
  .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
351
356
  .msg.event-group > summary .label { margin: 0; }
352
357
  .group-body { padding: 0 12px 12px; }
358
+ .chat-image { display: block; max-width: 100%; max-height: 320px; margin: 8px 0 0; border: 1px solid var(--pi-border-muted); border-radius: 8px; object-fit: contain; }
353
359
  .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
354
360
  .group-msg.tool { color: var(--pi-warning); }
355
361
  .group-msg.tool-execution-shell { color: var(--pi-text); }
@@ -376,6 +382,8 @@ ${o.join(`
376
382
  .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
377
383
  .msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
378
384
  .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
385
+ .msg.assistant > .msg-header .label { color: var(--pi-text-secondary); }
386
+ .msg.user > .msg-header .label { color: var(--pi-accent); }
379
387
  .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
380
388
  .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
381
389
  .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
@@ -411,7 +419,7 @@ ${o.join(`
411
419
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
412
420
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
413
421
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
414
- `,vf=W`
422
+ `,Af=_`
415
423
  :host { display: block; }
416
424
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
417
425
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -436,7 +444,7 @@ ${o.join(`
436
444
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
437
445
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
438
446
  th { background: var(--pi-surface); }
439
- `,bf=W`
447
+ `,Ef=_`
440
448
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
441
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; }
442
450
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -446,7 +454,7 @@ ${o.join(`
446
454
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
447
455
  .muted { color: var(--pi-dim); }
448
456
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
449
- `,wf=W`
457
+ `,Df=_`
450
458
  :host { display: block; }
451
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); }
452
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; }
@@ -454,7 +462,7 @@ ${o.join(`
454
462
  button.selected, button:hover { background: var(--pi-selection-bg); }
455
463
  span { color: var(--pi-muted); font-size: 12px; }
456
464
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
457
- `,Yn=W`
465
+ `,ra=_`
458
466
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
459
467
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
460
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; }
@@ -468,7 +476,7 @@ ${o.join(`
468
476
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
469
477
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
470
478
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
471
- `,yf=W`
479
+ `,Wf=_`
472
480
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
473
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; }
474
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; }
@@ -486,7 +494,7 @@ ${o.join(`
486
494
  .group { grid-column: 1 / -1; font-size: 12px; }
487
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; }
488
496
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
489
- `,Sf=W`
497
+ `,_f=_`
490
498
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
491
499
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
492
500
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -495,16 +503,30 @@ ${o.join(`
495
503
  .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
496
504
  .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
497
505
  .select-model { max-width: min(42vw, 320px); }
498
- .select-thinking { max-width: 110px; }
506
+ .icon-button { flex: 0 0 auto; display: inline-grid; place-items: center; width: 36px; height: 36px; padding: 0; }
507
+ .icon-button .prompt-action-icon, .icon-button .prompt-thinking-gauge { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
508
+ .icon-button .prompt-action-icon-filled { fill: currentColor; stroke: none; }
509
+ .send-button:not(:disabled) { color: var(--pi-accent, var(--pi-text)); }
510
+ .stop-button:not(:disabled) { color: var(--pi-danger); }
511
+ .select-thinking .prompt-thinking-gauge .gauge-bar { fill: currentColor; stroke: none; opacity: .28; }
512
+ .select-thinking .prompt-thinking-gauge .gauge-bar-active { opacity: 1; }
513
+ .editor-attach { position: absolute; right: 8px; bottom: 8px; z-index: 2; width: 30px; height: 30px; }
514
+ .editor-attach .prompt-action-icon { width: 16px; height: 16px; }
499
515
  textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
500
516
  textarea { overflow-y: auto; padding: 8px; }
501
517
  .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
502
- .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
518
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px 44px 8px 8px; caret-color: var(--pi-text); }
503
519
  .markdown-editor .cm-line { padding: 0; }
504
520
  .markdown-editor .cm-placeholder { color: var(--pi-dim); }
505
521
  .markdown-editor .cm-focused { outline: none; }
506
522
  .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
507
- .mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
523
+ .mode-hint { position: absolute; right: 46px; bottom: 8px; max-width: calc(100% - 54px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
524
+ .attachments { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 8px; }
525
+ .attachment-chip { position: relative; width: 56px; height: 56px; border: 1px solid var(--pi-border); border-radius: 8px; overflow: hidden; background: var(--pi-bg); }
526
+ .attachment-chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
527
+ .attachment-remove { position: absolute; top: 1px; right: 1px; width: 18px; height: 18px; padding: 0; line-height: 16px; border-radius: 50%; border: 1px solid var(--pi-border); background: var(--pi-surface); color: var(--pi-text); font-size: 13px; cursor: pointer; }
528
+ .attachment-delivery select { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; font: 12px system-ui, sans-serif; }
529
+ .attachment-error { flex-basis: 100%; color: var(--pi-danger); font-size: 12px; }
508
530
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
509
531
  button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
510
532
  @media (max-width: 640px) {
@@ -517,10 +539,10 @@ ${o.join(`
517
539
  @media (max-width: 430px) {
518
540
  .compact-status { flex-basis: 170px; font-size: 11px; }
519
541
  .select-model { max-width: 48vw; }
520
- .select-thinking { max-width: 70px; }
521
542
  button { padding: 5px 7px; }
543
+ .icon-button { width: 34px; height: 34px; }
522
544
  }
523
- `;var xf=Object.defineProperty,kf=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?kf(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&&xf(t,i,o),o};let Q=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,Di(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
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`
524
546
  <section>
525
547
  <h2>${this.renderHeading()}</h2>
526
548
  ${this.collapsed?null:l`
@@ -529,12 +551,12 @@ ${o.join(`
529
551
  </div>
530
552
  `}
531
553
  </section>
532
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=ea(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=na(e)&&this.onRemove!==void 0;return l`
533
555
  <div
534
556
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
535
557
  tabindex="0"
536
558
  title=${e.baseUrl??e.name}
537
- @click=${o=>{Ai(o,()=>this.onSelect?.(e))}}
559
+ @click=${o=>{Oi(o,()=>this.onSelect?.(e))}}
538
560
  @keydown=${o=>{this.handleMachineKeydown(o,e)}}
539
561
  >
540
562
  <div class="action-main">
@@ -543,7 +565,7 @@ ${o.join(`
543
565
  </div>
544
566
  ${s?this.renderMachineMenu(e):null}
545
567
  </div>
546
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=qn(this.activities[e.id]);return Ti(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=$f(e.id);return l`
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`
547
569
  <div class="action-menu">
548
570
  <button
549
571
  class="action-menu-toggle"
@@ -559,13 +581,13 @@ ${o.join(`
559
581
  </div>
560
582
  `:null}
561
583
  </div>
562
- `}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=jt(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}Ei(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};Q.styles=[Wi,W`
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,_`
563
585
  .machine-row.no-actions .action-main { border-radius: 8px; }
564
586
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
565
587
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
566
588
  .machine-menu-panel button.danger { color: var(--pi-danger); }
567
589
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
568
- `];ne([d({attribute:!1})],Q.prototype,"machines",2);ne([d({attribute:!1})],Q.prototype,"selected",2);ne([d({attribute:!1})],Q.prototype,"statuses",2);ne([d({attribute:!1})],Q.prototype,"activities",2);ne([d({type:Boolean,reflect:!0})],Q.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],Q.prototype,"collapsed",2);ne([d({attribute:!1})],Q.prototype,"onSelect",2);ne([d({attribute:!1})],Q.prototype,"onRemove",2);ne([d({attribute:!1})],Q.prototype,"onToggleCollapsed",2);ne([d({attribute:!1})],Q.prototype,"onFocusNextSection",2);ne([d({attribute:!1})],Q.prototype,"onCancelKeyboardNavigation",2);ne([b()],Q.prototype,"openMenuMachineId",2);ne([b()],Q.prototype,"menuStyle",2);Q=ne([E("machine-list")],Q);function ea(e){return e.kind==="remote"}function $f(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Pf=Object.defineProperty,Rf=Object.getOwnPropertyDescriptor,ee=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rf(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&&Pf(t,i,o),o};let K=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,Di(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([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`
569
591
  <section>
570
592
  <h2>${this.renderHeading()}</h2>
571
593
  ${this.collapsed?null:l`
@@ -575,7 +597,7 @@ ${o.join(`
575
597
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
576
598
  tabindex="0"
577
599
  title=${e.path}
578
- @click=${t=>{Ai(t,()=>this.onSelect?.(e))}}
600
+ @click=${t=>{Oi(t,()=>this.onSelect?.(e))}}
579
601
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
580
602
  >
581
603
  <div class="action-main">
@@ -595,19 +617,19 @@ ${o.join(`
595
617
  </div>
596
618
  `}
597
619
  </section>
598
- `}handleProjectKeydown(e,t){Ei(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=af(e,this.workspacesByProjectId[e.id]??[],this.activities);return Ti(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=jt(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
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}?
599
621
 
600
- This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};K.styles=Wi;ee([d({attribute:!1})],K.prototype,"projects",2);ee([d({attribute:!1})],K.prototype,"selected",2);ee([d({attribute:!1})],K.prototype,"activities",2);ee([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ee([d({attribute:!1})],K.prototype,"onSelect",2);ee([d({attribute:!1})],K.prototype,"onClose",2);ee([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);ee([d({attribute:!1})],K.prototype,"onFocusPreviousSection",2);ee([d({attribute:!1})],K.prototype,"onFocusNextSection",2);ee([d({attribute:!1})],K.prototype,"onCancelKeyboardNavigation",2);ee([b()],K.prototype,"openMenuProjectId",2);ee([b()],K.prototype,"menuStyle",2);K=ee([E("project-list")],K);function mr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Cf(t)}`)}function Cf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&If(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 If(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Mf=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tf(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&&Mf(t,i,o),o};let H=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,Di(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=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`
601
623
  <section>
602
624
  <h2>${this.renderHeading()}</h2>
603
625
  ${this.collapsed?null:l`
604
626
  <div class="list-body">
605
- ${this.workspaces.map(e=>{const t=Af(e),i=this.workspaceLabelItems(e);return l`
627
+ ${this.workspaces.map(e=>{const t=qf(e),i=this.workspaceLabelItems(e);return l`
606
628
  <div
607
629
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
608
630
  tabindex="0"
609
631
  title=${t}
610
- @click=${s=>{Ai(s,()=>this.onSelect?.(e))}}
632
+ @click=${s=>{Oi(s,()=>this.onSelect?.(e))}}
611
633
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
612
634
  >
613
635
  <div class="action-main">
@@ -619,18 +641,18 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
619
641
  </div>
620
642
  `}
621
643
  </section>
622
- `}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=nf(rf(e,this.activities));return Ti(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=yf(wf(e,this.activities));return _i(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
623
645
  <span class="workspace-primary">
624
646
  <span class="workspace-primary-label">${e}</span>
625
647
  ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
626
648
  </span>
627
649
  ${t.length===0?null:l`
628
650
  <small class="workspace-secondary">
629
- <span class="workspace-label">${mr(t)}</span>
651
+ <span class="workspace-label">${yr(t)}</span>
630
652
  </small>
631
653
  `}
632
654
  ${this.renderActivity(i)}
633
- `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Df(i.id);return l`
655
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Vf(i.id);return l`
634
656
  <div class="action-menu">
635
657
  <button
636
658
  class="action-menu-toggle"
@@ -647,7 +669,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
647
669
  </div>
648
670
  `:null}
649
671
  </div>
650
- `}renderWorkspaceActions(e){if(!Ef(e))return;const t=this.isDeleting(e);return l`
672
+ `}renderWorkspaceActions(e){if(!Kf(e))return;const t=this.isDeleting(e);return l`
651
673
  <div class="workspace-menu-actions">
652
674
  <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
653
675
  </div>
@@ -664,11 +686,11 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
664
686
  ${t.length===0?null:l`
665
687
  <div class="workspace-detail-row">
666
688
  <dt>Details</dt>
667
- <dd><span class="workspace-label">${mr(t)}</span></dd>
689
+ <dd><span class="workspace-label">${yr(t)}</span></dd>
668
690
  </div>
669
691
  `}
670
692
  </dl>
671
- `}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=jt(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}Ei(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"})}};H.styles=Wi;Z([d({attribute:!1})],H.prototype,"workspaces",2);Z([d({attribute:!1})],H.prototype,"selected",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsible",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsed",2);Z([d({attribute:!1})],H.prototype,"workspaceLabelItems",2);Z([d({attribute:!1})],H.prototype,"activities",2);Z([d({attribute:!1})],H.prototype,"deletingWorkspaceIds",2);Z([d({attribute:!1})],H.prototype,"onSelect",2);Z([d({attribute:!1})],H.prototype,"onDelete",2);Z([d({attribute:!1})],H.prototype,"onToggleCollapsed",2);Z([d({attribute:!1})],H.prototype,"onFocusPreviousSection",2);Z([d({attribute:!1})],H.prototype,"onFocusNextSection",2);Z([d({attribute:!1})],H.prototype,"onCancelKeyboardNavigation",2);Z([b()],H.prototype,"openMenuWorkspaceId",2);Z([b()],H.prototype,"menuStyle",2);H=Z([E("workspace-list")],H);function Af(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function Ef(e){return e.isGitWorktree&&!e.isMain}function Df(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Wf=Object.defineProperty,_f=Object.getOwnPropertyDescriptor,A=(e,t,i,s)=>{for(var o=s>1?void 0:s?_f(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&&Wf(t,i,o),o};function wt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let I=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.canDeleteArchived=!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,Di(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Lf(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>yt(r)==="current"),s=ta(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Of(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=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`
672
694
  <section>
673
695
  ${this.renderHeading(e.length+s.length,i)}
674
696
  ${this.collapsed?null:l`
@@ -691,7 +713,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
691
713
  ${this.renderCurrentSelectionButton(t)}
692
714
  <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
693
715
  </h2>
694
- `;const i=this.selected===void 0?"No session selected":wt(this.selected),s=this.selected?.path??i;return l`
716
+ `;const i=this.selected===void 0?"No session selected":kt(this.selected),s=this.selected?.path??i;return l`
695
717
  <h2>
696
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>
697
719
  ${this.renderCurrentSelectionButton(t)}
@@ -704,7 +726,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
704
726
  ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close archived session selection":"Select archived sessions"} aria-label=${t?"Close archived session selection":"Select archived sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
705
727
  <small class="section-count">${e.length}</small>
706
728
  </h2>
707
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ae(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
729
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ee(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
708
730
  <div class="bulk-row selecting">
709
731
  <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"Clear visible":"Select visible"}</button>
710
732
  <small>${t.length} selected${o!==t.length?l` · ${o} visible`:null}</small>
@@ -721,37 +743,38 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
721
743
  <button @click=${()=>{this.closeSelection("archived")}}>Done</button>
722
744
  ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
723
745
  </div>
724
- `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=yt(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=$t(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
725
747
  <div
726
748
  class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
727
749
  style=${`--depth:${String(o)}`}
728
750
  tabindex="0"
729
751
  title=${s.path}
730
- @click=${p=>{Ai(p,()=>{this.activateSessionRow(s,i)})}}
752
+ @click=${p=>{Oi(p,()=>{this.activateSessionRow(s,i)})}}
731
753
  @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
732
754
  >
733
755
  <div class="action-main ${n?"selecting":""}">
734
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${wt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
735
- <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${wt(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 ${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>
736
758
  ${this.renderActivity(s)}
737
759
  </div>
738
760
  <div class="action-menu">
739
761
  <button class="action-menu-toggle" title="Session actions" @click=${p=>{p.stopPropagation(),this.toggleMenu(s.id,p.currentTarget)}}>⋯</button>
740
762
  ${this.openMenuSessionId===s.id?l`
741
763
  <div class="action-menu-panel" style=${this.menuStyle}>
742
- ${ae(s)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:s.archived===!0?l`
764
+ ${ee(s)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:s.archived===!0?l`
743
765
  <button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(s)}}>Restore</button>
744
766
  <button class="danger" title=${this.canDeleteArchived?"Permanently delete archived session":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(s)}}>Delete archived session</button>
745
767
  `:l`
746
- ${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
747
768
  <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
748
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
+ ${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}
749
772
  `}
750
773
  </div>
751
774
  `:null}
752
775
  </div>
753
776
  </div>
754
- `}handleSessionKeydown(e,t,i){Ei(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)&&yt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${wt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${wt(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=Ji(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ae(t));this.selectedSessionIds=Ji(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=>yt(i)===e).map(i=>i.id);this.selectedSessionIds=Ji(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)&&yt(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=jt(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 ae(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){if(!(ae(e)||e.archived===!0))return Ti(Ci(this.statuses[e.id],this.activities[e.id])?"session":void 0,"Session active")}};I.styles=[Wi,W`
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,_`
755
778
  h2 { min-height: 30px; }
756
779
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
757
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; }
@@ -765,7 +788,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
765
788
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
766
789
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
767
790
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
768
- `];A([d({attribute:!1})],I.prototype,"sessions",2);A([d({attribute:!1})],I.prototype,"statuses",2);A([d({attribute:!1})],I.prototype,"activities",2);A([d({attribute:!1})],I.prototype,"selected",2);A([d({type:Boolean})],I.prototype,"canStart",2);A([d({type:Boolean})],I.prototype,"canDeleteArchived",2);A([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);A([d({attribute:!1})],I.prototype,"onSelect",2);A([d({attribute:!1})],I.prototype,"onStart",2);A([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);A([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);A([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);A([d({attribute:!1})],I.prototype,"onFocusNextSection",2);A([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);A([d({attribute:!1})],I.prototype,"onArchive",2);A([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);A([d({attribute:!1})],I.prototype,"onArchiveMany",2);A([d({attribute:!1})],I.prototype,"onRestore",2);A([d({attribute:!1})],I.prototype,"onDelete",2);A([d({attribute:!1})],I.prototype,"onDeleteArchived",2);A([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);A([d({attribute:!1})],I.prototype,"onDetachParent",2);A([b()],I.prototype,"openMenuSessionId",2);A([b()],I.prototype,"menuStyle",2);A([b()],I.prototype,"archivedExpanded",2);A([b()],I.prototype,"selectionScopes",2);A([b()],I.prototype,"selectedSessionIds",2);I=A([E("session-list")],I);function yt(e){return e.archived===!0?"archived":"current"}function Ji(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Of(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 Lf(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 ta(e.filter(s=>i.has(s.id)))}function ta(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 Ys={CHILD:2,ELEMENT:6},eo=e=>(...t)=>({_$litDirective$:e,values:t});let to=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:jf}=tl,vr=e=>e,br=()=>document.createComment(""),St=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(br(),o),n=s.insertBefore(br(),o);i=new jf(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=vr(c).nextSibling;vr(s).insertBefore(c,o),c=p}}}return i},He=(e,t,i=e)=>(e._$AI(t,i),e),Nf={},zf=(e,t=Nf)=>e._$AH=t,Ff=e=>e._$AH,Xi=e=>{e._$AR(),e._$AA.remove()};const wr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Bf=eo(class extends to{constructor(e){if(super(e),e.type!==Ys.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=Ff(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]=He(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=He(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=He(o[h],r[P]),St(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=He(o[f],r[v]),St(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=wr(n,v,P),u=wr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const B=u.get(n[v]),et=B!==void 0?o[B]:null;if(et===null){const ht=St(e,o[h]);He(ht,r[v]),c[v]=ht}else c[v]=He(et,r[v]),St(e,o[h],et),o[B]=null;v++}else Xi(o[f]),f--;else Xi(o[h]),h++;for(;v<=P;){const B=St(e,c[P+1]);He(B,r[v]),c[v++]=B}for(;h<=f;){const B=o[h++];B!==null&&Xi(B)}return this.ut=n,zf(e,c),Fe}}),Uf="pi-web:chat-groups:",Hf={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(yr(e));return t===null||t===""?void 0:Kf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(yr(e),JSON.stringify(t))}catch{}}};class qf{constructor(t=Hf){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&&Sr(r,this.openGroupKeys)&&Sr(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 yr(e){return`${Uf}${e}`}function Kf(e){if(Array.isArray(e))return{open:Yi(e),closedDefaultOpen:[]};if(Vf(e))return{open:Array.isArray(e.open)?Yi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Yi(e.closedDefaultOpen):[]}}function Yi(e){return e.filter(t=>typeof t=="string")}function Sr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Vf(e){return typeof e=="object"&&e!==null}function Gf(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=>xr(a,v)),u=a.parts.filter(v=>!xr(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 Qf(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 xr(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 Zf=30;function Jf(e,t){const i=Yf(ig(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Xf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=eg(s,t.markerOffset);return}e.scrollTop=tg(e.scrollHeight,t.distanceFromBottom)}function Yf(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 eg(e,t){return e-t}function tg(e,t){return Math.max(0,e-t)}function ig(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 sg=600,og=1;function rg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ng(e)||ag(e)}function ng(e){return e.scrollTop<(e.topThreshold??Math.max(sg,e.clientHeight))}function ag(e){return e.scrollHeight<=e.clientHeight+og}const lg="pi-web:chat-scroll:",cg=180,dg=48,pg=2,hg={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)}},ug={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class fg{constructor(t=hg,i=ug){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=cg){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=pg){if(t===""||i===void 0||!ts(i))return"skipped";try{if(sa(i,o)){const a={mode:"bottom"};return this.storage.setItem(es(t),JSON.stringify(a)),"saved"}const r=vg(i,s);if(r===void 0)return"skipped";const n=mg(i,r);return this.storage.setItem(es(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||!ts(i))return{status:"skipped"};const r=bg(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(es(t));if(i===null||i==="")return;const s=JSON.parse(i);return gg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function es(e){return`${lg}${e}`}function gg(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 ts(e){return e.clientHeight>0&&e.scrollHeight>0}function ia(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function sa(e,t=dg){return ia(e)<t}function mg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:io(t)??"",offset:t.getBoundingClientRect().top-i}}function vg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(io(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 kr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function bg(e,t){return e.find(i=>io(i)===t)}function io(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var wg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,so=(e,t,i,s)=>{for(var o=s>1?void 0:s?yg(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 Et=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=$r(this.positionPercent),t=$r(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([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`
769
792
  <div
770
793
  class="meter"
771
794
  style=${`--position:${e.toFixed(2)}%;`}
@@ -781,21 +804,21 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
781
804
  <div class="marker"></div>
782
805
  </div>
783
806
  </div>
784
- `}};Et.styles=W`
807
+ `}};Lt.styles=_`
785
808
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
786
809
  :host(:hover), :host(:focus-within) { opacity: .92; }
787
810
  .meter { height: 100%; }
788
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); }
789
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)); }
790
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%); }
791
- `;so([d({type:Number})],Et.prototype,"positionPercent",2);so([d({type:Number})],Et.prototype,"loadedPercent",2);Et=so([E("conversation-meter")],Et);function $r(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class $s extends to{constructor(t){if(super(t),this.it=L,t.type!==Ys.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===L||t==null)return this._t=void 0,this.it=t;if(t===Fe)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:[]}}}$s.directiveName="unsafeHTML",$s.resultType=1;const Sg=eo($s);function oo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Je=oo();function oa(e){Je=e}var qe={exec:()=>null};function R(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(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var xg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={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)}}>`)},kg=/^(?:[ \t]*(?:\n|$))+/,$g=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Nt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Rg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ro=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ra=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,na=R(ra).replace(/bull/g,ro).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(),Cg=R(ra).replace(/bull/g,ro).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(),no=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ig=/^[^\n]+/,ao=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mg=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ao).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Tg=R(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ro).getRegex(),_i="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",lo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ag=R("^ {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",lo).replace("tag",_i).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),aa=R(no).replace("hr",Nt).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",_i).getRegex(),Eg=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aa).getRegex(),co={blockquote:Eg,code:$g,def:Mg,fences:Pg,heading:Rg,hr:Nt,html:Ag,lheading:na,list:Tg,newline:kg,paragraph:aa,table:qe,text:Ig},Pr=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Nt).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",_i).getRegex(),Dg={...co,lheading:Cg,table:Pr,paragraph:R(no).replace("hr",Nt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pr).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",_i).getRegex()},Wg={...co,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",lo).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:qe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(no).replace("hr",Nt).replace("heading",` *#{1,6} *[^
792
- ]`).replace("lheading",na).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_g=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Og=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,la=/^( {2,}|\\)\n(?!\s*$)/,Lg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,pt=/[\p{P}\p{S}]/u,Oi=/[\s\p{P}\p{S}]/u,po=/[^\s\p{P}\p{S}]/u,jg=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Oi).getRegex(),ca=/(?!~)[\p{P}\p{S}]/u,Ng=/(?!~)[\s\p{P}\p{S}]/u,zg=/(?:[^\s\p{P}\p{S}]|~)/u,Fg=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",xg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),da=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Bg=R(da,"u").replace(/punct/g,pt).getRegex(),Ug=R(da,"u").replace(/punct/g,ca).getRegex(),pa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Hg=R(pa,"gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),qg=R(pa,"gu").replace(/notPunctSpace/g,zg).replace(/punctSpace/g,Ng).replace(/punct/g,ca).getRegex(),Kg=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),Vg=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,pt).getRegex(),Gg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Qg=R(Gg,"gu").replace(/notPunctSpace/g,po).replace(/punctSpace/g,Oi).replace(/punct/g,pt).getRegex(),Zg=R(/\\(punct)/,"gu").replace(/punct/g,pt).getRegex(),Jg=R(/^<(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(),Xg=R(lo).replace("(?:-->|$)","-->").getRegex(),Yg=R("^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",Xg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),vi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,em=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",vi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ha=R(/^!?\[(label)\]\[(ref)\]/).replace("label",vi).replace("ref",ao).getRegex(),ua=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",ao).getRegex(),tm=R("reflink|nolink(?!\\()","g").replace("reflink",ha).replace("nolink",ua).getRegex(),Rr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ho={_backpedal:qe,anyPunctuation:Zg,autolink:Jg,blockSkip:Fg,br:la,code:Og,del:qe,delLDelim:qe,delRDelim:qe,emStrongLDelim:Bg,emStrongRDelimAst:Hg,emStrongRDelimUnd:Kg,escape:_g,link:em,nolink:ua,punctuation:jg,reflink:ha,reflinkSearch:tm,tag:Yg,text:Lg,url:qe},im={...ho,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",vi).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",vi).getRegex()},Ps={...ho,emStrongRDelimAst:qg,emStrongLDelim:Ug,delLDelim:Vg,delRDelim:Qg,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Rr).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:R(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Rr).getRegex()},sm={...Ps,br:R(la).replace("{2,}","*").getRegex(),text:R(Ps.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},qt={normal:co,gfm:Dg,pedantic:Wg},xt={normal:ho,gfm:Ps,breaks:sm,pedantic:im},om={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Cr=e=>om[e];function Me(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,Cr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,Cr);return e}function Ir(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Mr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.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(G.slashPipe,"|");return s}function Ne(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 Tr(e){let t=e.split(`
793
- `),i=t.length-1;for(;i>=0&&G.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
794
- `)}function rm(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 nm(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 Ar(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 am(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
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(`
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(`
795
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(`
796
- `)}var bi=class{options;rules;lexer;constructor(e){this.options=e||Je}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]:Tr(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=am(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=Ne(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ne(t[0],`
797
- `),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:Ne(t[0],`
798
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Ne(t[0],`
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],`
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
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Fe(t[0],`
799
822
  `).split(`
800
823
  `),s="",o="",r=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
801
824
  `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
@@ -803,23 +826,23 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
803
826
  ${p}`:p,o=o?`${o}
804
827
  ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let v=f,P=v.raw+`
805
828
  `+i.join(`
806
- `),B=this.blockquote(P);r[r.length-1]=B,s=s.substring(0,s.length-v.raw.length)+B.raw,o=o.substring(0,o.length-v.text.length)+B.text;break}else if(f?.type==="list"){let v=f,P=v.raw+`
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+`
807
830
  `+i.join(`
808
- `),B=this.list(P);r[r.length-1]=B,s=s.substring(0,s.length-f.raw.length)+B.raw,o=o.substring(0,o.length-v.raw.length)+B.raw,i=P.substring(r.at(-1).raw.length).split(`
809
- `);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=nm(t[2].split(`
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(`
810
833
  `,1)[0],t[1].length),f=e.split(`
811
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+`
812
- `,e=e.substring(f.length+1),c=!0),!c){let B=this.rules.other.nextBulletRegex(P),et=this.rules.other.hrRegex(P),ht=this.rules.other.fencesBeginRegex(P),go=this.rules.other.headingBeginRegex(P),xa=this.rules.other.htmlBeginRegex(P),ka=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ji=e.split(`
813
- `,1)[0],ut;if(f=ji,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),ut=f):ut=f.replace(this.rules.other.tabCharGlobal," "),ht.test(f)||go.test(f)||xa.test(f)||ka.test(f)||B.test(f)||et.test(f))break;if(ut.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
814
- `+ut.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ht.test(h)||go.test(h)||et.test(h))break;u+=`
815
- `+f}v=!f.trim(),p+=ji+`
816
- `,e=e.substring(ji.length+1),h=ut.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=Tr(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:Ne(t[0],`
817
- `),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=Mr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
818
- `):[],r={type:"table",raw:Ne(t[0],`
819
- `),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(Mr(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:Ne(t[0],`
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(`
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],`
820
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)===`
821
- `?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=Ne(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=rm(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)),Ar(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 Ar(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}}}},xe=class Rs{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Je,this.options.tokenizer=this.options.tokenizer||new bi,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:G,block:qt.normal,inline:xt.normal};this.options.pedantic?(i.block=qt.pedantic,i.inline=xt.pedantic):this.options.gfm&&(i.block=qt.gfm,this.options.breaks?i.inline=xt.breaks:i.inline=xt.gfm),this.tokenizer.rules=i}static get rules(){return{block:qt,inline:xt}}static lex(t,i){return new Rs(i).lex(t)}static lexInline(t,i){return new Rs(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
822
- `),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(G.tabCharGlobal," ").replace(G.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+=`
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,`
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+=`
823
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(`
824
847
  `)?"":`
825
848
  `)+r.raw,a.text+=`
@@ -832,7 +855,7 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
832
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(`
833
856
  `)?"":`
834
857
  `)+r.raw,a.text+=`
835
- `+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)}},wi=class{options;parser;constructor(e){this.options=e||Je}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
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,"")+`
836
859
  `;return s?'<pre><code class="language-'+Me(s)+'">'+(i?o:Me(o,!0))+`</code></pre>
837
860
  `:"<pre><code>"+(i?o:Me(o,!0))+`</code></pre>
838
861
  `}blockquote({tokens:e}){return`<blockquote>
@@ -850,19 +873,19 @@ ${this.parser.parse(e)}</blockquote>
850
873
  `}tablerow({text:e}){return`<tr>
851
874
  ${e}</tr>
852
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}>
853
- `}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=Ir(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=Ir(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)}},uo=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}},ke=class Cs{options;renderer;textRenderer;constructor(t){this.options=t||Je,this.options.renderer=this.options.renderer||new wi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new uo}static parse(t,i){return new Cs(i).parse(t)}static parseInline(t,i){return new Cs(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}},$t=class{options;block;constructor(e){this.options=e||Je}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?xe.lex:xe.lexInline}provideParser(e=this.block){return e?ke.parse:ke.parseInline}},lm=class{defaults=oo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ke;Renderer=wi;TextRenderer=uo;Lexer=xe;Tokenizer=bi;Hooks=$t;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 wi(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 bi(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 $t;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];$t.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&$t.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 xe.lex(e,t??this.defaults)}parser(e,t){return ke.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?xe.lex:xe.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?ke.parse:ke.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?xe.lex:xe.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?ke.parse:ke.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+=`
854
- 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}}},Qe=new lm;function T(e,t){return Qe.parse(e,t)}T.options=T.setOptions=function(e){return Qe.setOptions(e),T.defaults=Qe.defaults,oa(T.defaults),T};T.getDefaults=oo;T.defaults=Je;T.use=function(...e){return Qe.use(...e),T.defaults=Qe.defaults,oa(T.defaults),T};T.walkTokens=function(e,t){return Qe.walkTokens(e,t)};T.parseInline=Qe.parseInline;T.Parser=ke;T.parser=ke.parse;T.Renderer=wi;T.TextRenderer=uo;T.Lexer=xe;T.lexer=xe.lex;T.Tokenizer=bi;T.Hooks=$t;T.parse=T;T.options;T.setOptions;T.use;T.walkTokens;T.parseInline;ke.parse;xe.lex;const fa=new T.Renderer;fa.html=({text:e})=>pm(e);const cm=300,kt=new Map;function dm(e){const t=kt.get(e);if(t!==void 0)return t;const i=T.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:fa}),s=hm(i);if(kt.set(e,s),kt.size>cm){const o=kt.keys().next().value;o!==void 0&&kt.delete(o)}return s}function pm(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function hm(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")&&!um(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function um(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,gm=Object.getOwnPropertyDescriptor,ga=(e,t,i,s)=>{for(var o=s>1?void 0:s?gm(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 yi=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}>${Sg(dm(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 mm(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)}};yi.styles=vf;ga([d()],yi.prototype,"text",2);yi=ga([E("formatted-text")],yi);async function mm(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var vm=Object.defineProperty,bm=Object.getOwnPropertyDescriptor,zt=(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&&vm(t,i,o),o};const Er=180;let Ze=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=wm(e.args),s=ym(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Sm(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>${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`
855
878
  <section class=${`tool-card ${e.status}`}>
856
879
  <div class="tool-header">
857
880
  <div class="tool-title">
858
- <span class="status-icon" aria-hidden="true">${km(e.status)}</span>
881
+ <span class="status-icon" aria-hidden="true">${jm(e.status)}</span>
859
882
  <strong>${e.toolName}</strong>
860
883
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
861
884
  </div>
862
885
  <div class="tool-meta">
863
- ${Dr(e)===void 0?null:l`<span>${Dr(e)}</span>`}
886
+ ${Lr(e)===void 0?null:l`<span>${Lr(e)}</span>`}
864
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>`}
865
- <span class="status-label">${$m(e.status)}</span>
888
+ <span class="status-label">${Nm(e.status)}</span>
866
889
  </div>
867
890
  </div>
868
891
 
@@ -877,7 +900,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
877
900
  <pre>${e}</pre>
878
901
  </details>
879
902
  `}renderDiffBody(e,t){const i=e.split(`
880
- `),s=!this.showFullDiff&&i.length>Er,o=s?i.slice(0,Er):i;return l`
903
+ `),s=!this.showFullDiff&&i.length>Or,o=s?i.slice(0,Or):i;return l`
881
904
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
882
905
  <summary>
883
906
  <span>${t}</span>
@@ -887,14 +910,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
887
910
  <span>${s?`Showing ${String(o.length)} of ${String(i.length)} lines`:"Full diff"}</span>
888
911
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
889
912
  </div>
890
- <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${xm(r)}>${r}</span>`)}</code></pre>
913
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Lm(r)}>${r}</span>`)}</code></pre>
891
914
  ${s?l`
892
915
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
893
916
  Show all ${String(i.length)} diff lines
894
917
  </button>
895
918
  `:null}
896
919
  </details>
897
- `}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}}};Ze.styles=W`
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=_`
898
921
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
899
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); }
900
923
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -934,19 +957,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
934
957
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
935
958
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
936
959
  .show-more { justify-self: start; }
937
- `;zt([d({attribute:!1})],Ze.prototype,"execution",2);zt([b()],Ze.prototype,"showFullDiff",2);zt([b()],Ze.prototype,"copied",2);zt([b()],Ze.prototype,"diffOpen",2);Ze=zt([E("tool-execution-view")],Ze);function wm(e){return Is(e,"path")??Is(e,"file_path")}function Dr(e){if(e.toolName!=="edit")return;const t=ii(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof ii(e.args,"oldText")=="string"&&typeof ii(e.args,"newText")=="string")return"1 edit"}function ym(e){return Is(e,"diff")}function Sm(e){let t=0,i=0;for(const s of e.split(`
938
- `))ma(s)?t++:va(s)&&i++;return{added:t,removed:i}}function xm(e){return ma(e)?"added":va(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function ma(e){return e.startsWith("+")&&!e.startsWith("+++")}function va(e){return e.startsWith("-")&&!e.startsWith("---")}function km(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function $m(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Pm(e){return typeof e=="object"&&e!==null}function ii(e,t){return Pm(e)?e[t]:void 0}function Is(e,t){const i=ii(e,t);return typeof i=="string"?i:void 0}var Rm=Object.defineProperty,Cm=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var o=s>1?void 0:s?Cm(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&&Rm(t,i,o),o};const Im=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Mm=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),is=["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 Wr(){return is[Math.floor(Math.random()*is.length)]??is[0]}function _r(e){return si(e,0,100)}function si(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let j=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.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new qf,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`
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`
939
962
  <div class="chat-wrap">
940
963
  ${this.renderConversationRail()}
941
964
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
942
965
  ${this.renderHistoryBoundary()}
943
- ${Bf(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
+ ${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)))}
944
967
  ${this.renderQueuedMessages()}
945
968
  ${this.renderSessionActivity()}
946
969
  </div>
947
970
  ${this.renderActivityDock()}
948
971
  </div>
949
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Gf(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
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`
973
+ <div class="activity-dock active" aria-live="polite">
974
+ <span class="dot"></span>
975
+ <span class="activity-text">Sending your message…</span>
976
+ </div>
977
+ `;const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
950
978
  <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
951
979
  <span class="dot"></span>
952
980
  <span class="activity-text">${this.activityText(e)}</span>
@@ -975,7 +1003,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
975
1003
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
976
1004
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
977
1005
  </aside>
978
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Wr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Wr(),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?_r(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=si(this.currentConversationIndex??t,0,e-1);return _r(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?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`
979
1007
  <div class="history-boundary">
980
1008
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
981
1009
  <span>Scroll up to load earlier messages</span>
@@ -992,7 +1020,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
992
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)}}>
993
1021
  <summary>
994
1022
  <b class="label">${s?"live events":"events"}</b>
995
- <span>${Qf(e)}</span>
1023
+ <span>${dg(e)}</span>
996
1024
  </summary>
997
1025
  <div class="group-body">
998
1026
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -1019,7 +1047,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1019
1047
  </div>
1020
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(`
1021
1049
 
1022
- `);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:Im.format(t),full:Mm.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: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`
1023
1051
  <details class="part skill-invocation">
1024
1052
  <summary><b>[skill]</b> ${e.name}</summary>
1025
1053
  <small>${e.location}</small>
@@ -1030,50 +1058,95 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1030
1058
  <strong>Loaded ${e.name}</strong>
1031
1059
  <small>read ${e.path}</small>
1032
1060
  </div>
1033
- `:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
1061
+ `:e.type==="image"?l`<img class="part chat-image" src=${`data:${e.mimeType};base64,${e.data}`} alt="attached image" loading="lazy" />`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
1034
1062
  <details class="part" ?open=${e.isError}>
1035
1063
  <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1036
1064
  <formatted-text .text=${e.text}></formatted-text>
1037
1065
  </details>
1038
- `: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&&rg({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?sa(e):!0}isAtBottom(){const e=this.chat;return e?ia(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 Jf(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(Xf(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Zf){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=si(i,0,Math.max(0,e-1));return}this.currentConversationIndex=si(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 kr(e,t)??kr(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=mf;F([d({attribute:!1})],j.prototype,"messages",2);F([d()],j.prototype,"sessionId",2);F([d({type:Number})],j.prototype,"messageStart",2);F([d({type:Number})],j.prototype,"messageEnd",2);F([d({type:Number})],j.prototype,"messageTotal",2);F([d({type:Boolean})],j.prototype,"hasMore",2);F([d({type:Boolean})],j.prototype,"loadingMore",2);F([d({type:Boolean})],j.prototype,"isReceivingPartialStream",2);F([d({type:Boolean})],j.prototype,"isCompacting",2);F([d({type:Number})],j.prototype,"pendingMessageCount",2);F([d({attribute:!1})],j.prototype,"status",2);F([d({attribute:!1})],j.prototype,"activity",2);F([d({attribute:!1})],j.prototype,"onLoadMore",2);F([z(".chat")],j.prototype,"chat",2);F([b()],j.prototype,"pinnedToBottom",2);F([b()],j.prototype,"expandedMetaKey",2);F([b()],j.prototype,"copiedMessageKey",2);F([b()],j.prototype,"currentConversationIndex",2);F([b()],j.prototype,"loadMoreRequested",2);j=F([E("chat-view")],j);class Tm extends to{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Ys.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 fo=eo(Tm);var Am=Object.defineProperty,Em=Object.getOwnPropertyDescriptor,Li=(e,t,i,s)=>{for(var o=s>1?void 0:s?Em(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&&Am(t,i,o),o};let lt=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
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`
1067
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
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
+ </svg>
1070
+ `}function Ra(){return he`
1071
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1072
+ <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1073
+ <path d="M21 3 11.5 12.5"></path>
1074
+ </svg>
1075
+ `}function iv(){return he`
1076
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1077
+ <path d="M4 7h11"></path>
1078
+ <path d="M4 12h7"></path>
1079
+ <path d="M4 17h7"></path>
1080
+ <path d="m15 14 5 3-5 3z"></path>
1081
+ </svg>
1082
+ `}function sv(){return Ra()}function ov(){return he`
1083
+ <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1084
+ <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
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`
1087
+ <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1088
+ ${a}
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`
1039
1091
  <div class="menu">
1040
1092
  ${this.items.map((e,t)=>l`
1041
- <button class=${t===this.selectedIndex?"selected":""} ${fo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1093
+ <button class=${t===this.selectedIndex?"selected":""} ${bo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1042
1094
  <strong>${e.insertText}</strong>
1043
1095
  <span>${e.detail}</span>
1044
1096
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1045
1097
  </button>
1046
1098
  `)}
1047
1099
  </div>
1048
- `:null}};lt.styles=wf;Li([d({attribute:!1})],lt.prototype,"items",2);Li([d({type:Number})],lt.prototype,"selectedIndex",2);Li([d({attribute:!1})],lt.prototype,"onPick",2);lt=Li([E("autocomplete-menu")],lt);var Dm=Object.defineProperty,Wm=Object.getOwnPropertyDescriptor,V=(e,t,i,s)=>{for(var o=s>1?void 0:s?Wm(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&&Dm(t,i,o),o};let U=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new mo,this.readOnlyCompartment=new mo}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=Kt(i,t);s!==void 0&&pi(s,this.draft);const o=Kt(this.machineId,this.sessionId);this.draft=o!==void 0?bn(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;return l`
1049
- <footer class=${t?"shell-mode":""}>
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`
1101
+ <footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
1050
1102
  <div class="editor-wrap">
1051
1103
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
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>
1052
1106
  ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1053
1107
  ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1054
- <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
1108
+ ${this.renderAttachments()}
1109
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${o=>{this.pick(o)}}></autocomplete-menu>
1055
1110
  </div>
1056
1111
  <div class="actions">
1057
1112
  ${this.renderCompactStatus()}
1058
- <button ?disabled=${this.disabled} title=${i?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${i?"Queue":"Send"}</button>
1059
- ${this.canSteer&&!this.isCompacting?l`<button ?disabled=${this.disabled} title="Steer the current response before the next model call" @click=${()=>{this.send("steer")}}>Steer</button>`:null}
1060
- <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</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?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>
1061
1116
  </div>
1062
1117
  </footer>
1063
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`
1064
1119
  <div class="compact-status" aria-label="Session status">
1065
1120
  <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1066
- <button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${e.thinkingLevel??"off"}</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>
1067
1122
  </div>
1068
- `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new tt({parent:this.editorHost,state:Ni.create({doc:this.draft,extensions:[$a(),Wa(),Pa(),Ra.of(" "),Ca(Da,{fallback:!0}),tt.lineWrapping,tt.contentAttributes.of(e=>Nm(e.state.sliceDoc(0,e.state.selection.main.head))),Ia("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(tt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ni.readOnly.of(this.disabled)),tt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ma.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=>_a(e)||Ea(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>vo.shift?.(e)??!1},{key:"Backspace",run:e=>Oa(e)},...Ta,...Aa])]})}))}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:bo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(tt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ni.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Kt(this.machineId,this.sessionId);t!==void 0&&pi(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 O.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(_m);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await O.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Om);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=tp(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 kn(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):vo.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:bo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Kt(this.machineId,this.sessionId);i!==void 0&&Hs(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};U.styles=Sf;V([d({type:Boolean})],U.prototype,"disabled",2);V([d()],U.prototype,"sessionId",2);V([d()],U.prototype,"cwd",2);V([d()],U.prototype,"machineId",2);V([d({type:Boolean})],U.prototype,"canSteer",2);V([d({type:Boolean})],U.prototype,"isCompacting",2);V([d({type:Boolean})],U.prototype,"canStop",2);V([d({attribute:!1})],U.prototype,"status",2);V([d({attribute:!1})],U.prototype,"onSend",2);V([d({attribute:!1})],U.prototype,"onStop",2);V([d({attribute:!1})],U.prototype,"onSelectModel",2);V([d({attribute:!1})],U.prototype,"onSelectThinking",2);V([z(".markdown-editor")],U.prototype,"editorHost",2);V([b()],U.prototype,"draft",2);V([b()],U.prototype,"completions",2);V([b()],U.prototype,"selectedIndex",2);U=V([E("prompt-editor")],U);function Kt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return vn(e,t)}function _m(){return[]}function Om(){return[]}const Lm={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},jm={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Nm(e){return qs(e).kind==="normal"?Lm:jm}function Vt(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 zm(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,ba=(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 Si=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 ${Vt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Vt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1123
+ `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:l`
1124
+ <div class="attachments" aria-label="Pending attachments">
1125
+ ${this.attachments.map(e=>l`
1126
+ <div class="attachment-chip" title=${e.name}>
1127
+ <img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />
1128
+ <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
1129
+ </div>
1130
+ `)}
1131
+ ${this.attachments.length>0?l`
1132
+ <label class="attachment-delivery" title="How attachments are delivered to the agent">
1133
+ <select .value=${this.attachmentDelivery} @change=${e=>{this.changeDelivery(e)}}>
1134
+ <option value="inline">Attach to message</option>
1135
+ <option value="folder">Save to .pi-web/attachments</option>
1136
+ </select>
1137
+ </label>
1138
+ `:null}
1139
+ ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
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`
1069
1142
  <div class="bar">
1070
- <span>↑${Vt(s.input)}</span>
1071
- <span>↓${Vt(s.output)}</span>
1143
+ <span>↑${Xt(s.input)}</span>
1144
+ <span>↓${Xt(s.output)}</span>
1072
1145
  <span class="context">${i}</span>
1073
- <span>${zm(e.cost)}</span>
1146
+ <span>${wv(e.cost)}</span>
1074
1147
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1075
1148
  </div>
1076
- `}};Si.styles=bf;ba([d({attribute:!1})],Si.prototype,"status",2);Si=ba([E("status-bar")],Si);var Um=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,Le=(e,t,i,s)=>{for(var o=s>1?void 0:s?Hm(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&&Um(t,i,o),o};let Pe=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`
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`
1077
1150
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1078
1151
  <section @mousedown=${t=>{t.stopPropagation()}}>
1079
1152
  <header>
@@ -1083,7 +1156,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1083
1156
  ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1084
1157
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1085
1158
  ${e.map((t,i)=>l`
1086
- <button class=${i===this.selectedIndex?"selected":""} ${fo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1159
+ <button class=${i===this.selectedIndex?"selected":""} ${bo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1087
1160
  <span>${t.label}</span>
1088
1161
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1089
1162
  </button>
@@ -1092,7 +1165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1092
1165
  </div>
1093
1166
  </section>
1094
1167
  </div>
1095
- `}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=Yn;Le([d()],Pe.prototype,"title",2);Le([d({type:Boolean})],Pe.prototype,"searchable",2);Le([d({attribute:!1})],Pe.prototype,"options",2);Le([d({attribute:!1})],Pe.prototype,"selectedValue",2);Le([d({attribute:!1})],Pe.prototype,"onPick",2);Le([d({attribute:!1})],Pe.prototype,"onCancel",2);Le([b()],Pe.prototype,"selectedIndex",2);Le([b()],Pe.prototype,"query",2);Pe=Le([E("command-picker")],Pe);var qm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,Xe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Km(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&&qm(t,i,o),o};let _e=class extends C{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)}}};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`
1096
1169
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1097
1170
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1098
1171
  <header>
@@ -1105,19 +1178,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1105
1178
  </header>
1106
1179
  <div class="options">
1107
1180
  ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1108
- <button class=${i===this.selectedIndex?"selected":""} ${fo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1181
+ <button class=${i===this.selectedIndex?"selected":""} ${bo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1109
1182
  <span class="main">
1110
1183
  <strong>${t.title}</strong>
1111
1184
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1112
1185
  </span>
1113
- ${t.shortcut!==void 0?l`<kbd>${ei(t.shortcut)}</kbd>`:null}
1186
+ ${t.shortcut!==void 0?l`<kbd>${ri(t.shortcut)}</kbd>`:null}
1114
1187
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1115
1188
  </button>
1116
1189
  `)}
1117
1190
  </div>
1118
1191
  </section>
1119
1192
  </div>
1120
- `}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)}};_e.styles=yf;Xe([d({attribute:!1})],_e.prototype,"actions",2);Xe([d({attribute:!1})],_e.prototype,"onRun",2);Xe([d({attribute:!1})],_e.prototype,"onCancel",2);Xe([z("input")],_e.prototype,"input",2);Xe([b()],_e.prototype,"queryText",2);Xe([b()],_e.prototype,"selectedIndex",2);_e=Xe([E("action-palette")],_e);var Vm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var o=s>1?void 0:s?Gm(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&&Vm(t,i,o),o};let ie=class extends C{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=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`
1121
1194
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1122
1195
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1123
1196
  <header>
@@ -1140,11 +1213,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1140
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>
1141
1214
  </div>
1142
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`
1143
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Or(t.authType)}</small></button>
1216
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Fr(t.authType)}</small></button>
1144
1217
  `)}</div>`}}renderProviderButton(e){return l`
1145
1218
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1146
- <span>${e.name}${e.status.source!==void 0?l` <em>${Zm(e)}</em>`:null}</span>
1147
- <small>${e.id} · ${Or(e.authType)}</small>
1219
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Mv(e)}</em>`:null}</span>
1220
+ <small>${e.id} · ${Fr(e.authType)}</small>
1148
1221
  </button>
1149
1222
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1150
1223
  <div class="form">
@@ -1167,7 +1240,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1167
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}
1168
1241
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1169
1242
  </div>
1170
- `}focusInputIfNeeded(){const e=Qm(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?.()}};ie.styles=[Yn,W`
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,_`
1171
1244
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1172
1245
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1173
1246
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1182,7 +1255,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1182
1255
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1183
1256
  .inline-options { display: grid; gap: 8px; }
1184
1257
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1185
- `];ve([d({attribute:!1})],ie.prototype,"state",2);ve([d({attribute:!1})],ie.prototype,"onChooseMethod",2);ve([d({attribute:!1})],ie.prototype,"onSelectProvider",2);ve([d({attribute:!1})],ie.prototype,"onApiKeyInput",2);ve([d({attribute:!1})],ie.prototype,"onSaveApiKey",2);ve([d({attribute:!1})],ie.prototype,"onLogoutProvider",2);ve([d({attribute:!1})],ie.prototype,"onOAuthInput",2);ve([d({attribute:!1})],ie.prototype,"onOAuthRespond",2);ve([d({attribute:!1})],ie.prototype,"onOAuthCancel",2);ve([d({attribute:!1})],ie.prototype,"onCancel",2);ve([z("input")],ie.prototype,"input",2);ie=ve([E("auth-dialog")],ie);function Or(e){return e==="oauth"?"subscription":"API key"}function Qm(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 Zm(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 Jm=Object.defineProperty,Xm=Object.getOwnPropertyDescriptor,Ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xm(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&&Jm(t,i,o),o};let fe=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 O.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([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`
1186
1259
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1187
1260
  <section @click=${e=>{e.stopPropagation()}}>
1188
1261
  <header>
@@ -1214,7 +1287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1214
1287
  </footer>
1215
1288
  </section>
1216
1289
  </div>
1217
- `}};fe.styles=W`
1290
+ `}};ge.styles=_`
1218
1291
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1219
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); }
1220
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; }
@@ -1232,7 +1305,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1232
1305
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1233
1306
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1234
1307
  button:disabled { opacity: .5; cursor: not-allowed; }
1235
- `;Ae([d({attribute:!1})],fe.prototype,"onSubmit",2);Ae([d({attribute:!1})],fe.prototype,"onCancel",2);Ae([d()],fe.prototype,"machineId",2);Ae([b()],fe.prototype,"path",2);Ae([b()],fe.prototype,"createMissing",2);Ae([b()],fe.prototype,"suggestions",2);Ae([b()],fe.prototype,"selected",2);Ae([b()],fe.prototype,"loading",2);Ae([z("input")],fe.prototype,"pathInput",2);fe=Ae([E("project-dialog")],fe);var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,Ee=(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};let ge=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=tv(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"&&ss(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===""||ss(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?ss(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([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`
1236
1309
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1237
1310
  <section @click=${s=>{s.stopPropagation()}}>
1238
1311
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1267,7 +1340,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1267
1340
  </form>
1268
1341
  </section>
1269
1342
  </div>
1270
- `}};ge.styles=W`
1343
+ `}};me.styles=_`
1271
1344
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1272
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); }
1273
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; }
@@ -1287,8 +1360,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1287
1360
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1288
1361
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1289
1362
  button:disabled { opacity: .5; cursor: not-allowed; }
1290
- `;Ee([d({attribute:!1})],ge.prototype,"onSubmit",2);Ee([d({attribute:!1})],ge.prototype,"onCancel",2);Ee([d()],ge.prototype,"error",2);Ee([b()],ge.prototype,"url",2);Ee([b()],ge.prototype,"name",2);Ee([b()],ge.prototype,"token",2);Ee([b()],ge.prototype,"submitting",2);Ee([z("input[name='baseUrl']")],ge.prototype,"urlInput",2);Ee([z("input[name='name']")],ge.prototype,"nameInput",2);ge=Ee([E("machine-dialog")],ge);function tv(e){const t=e.trim();if(t==="")return"";const i=Lr(t)??Lr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):iv(t)}function ss(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 Lr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function iv(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 sv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function ov(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(`
1291
- `):""}}function rv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},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 av=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,De=(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&&av(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=sv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=ov(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([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`
1292
1365
  <div class="section-heading">
1293
1366
  <div>
1294
1367
  <h2>General configuration</h2>
@@ -1309,7 +1382,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1309
1382
  <span>Host</span>
1310
1383
  ${this.renderOverrideBadge("host")}
1311
1384
  </span>
1312
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:jr(t)})}}>
1385
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Ur(t)})}}>
1313
1386
  <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1314
1387
  </label>
1315
1388
 
@@ -1318,7 +1391,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1318
1391
  <span>Port</span>
1319
1392
  ${this.renderOverrideBadge("port")}
1320
1393
  </span>
1321
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:jr(t)})}}>
1394
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Ur(t)})}}>
1322
1395
  <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1323
1396
  </label>
1324
1397
 
@@ -1327,11 +1400,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1327
1400
  <span>Allowed hosts</span>
1328
1401
  ${this.renderOverrideBadge("allowedHosts")}
1329
1402
  </span>
1330
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:dv(t)==="all"?"all":"list"})}}>
1403
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Uv(t)==="all"?"all":"list"})}}>
1331
1404
  <option value="list">Only listed hosts</option>
1332
1405
  <option value="all">Allow every host</option>
1333
1406
  </select>
1334
- <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:pv(t)})}}></textarea>
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>
1335
1408
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1336
1409
  </div>
1337
1410
 
@@ -1348,10 +1421,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1348
1421
  <dl>
1349
1422
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1350
1423
  <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1351
- <div><dt>Allowed hosts</dt><dd>${cv(e.allowedHosts)}</dd></div>
1424
+ <div><dt>Allowed hosts</dt><dd>${Bv(e.allowedHosts)}</dd></div>
1352
1425
  </dl>
1353
1426
  </section>
1354
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(rv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=hv(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};me.styles=W`
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=_`
1355
1428
  :host { display: block; }
1356
1429
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1357
1430
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1393,7 +1466,84 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1393
1466
  .section-heading .secondary { justify-self: start; }
1394
1467
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1395
1468
  }
1396
- `;De([d({attribute:!1})],me.prototype,"configResponse",2);De([d({type:Boolean})],me.prototype,"loading",2);De([d({type:Boolean})],me.prototype,"saving",2);De([d()],me.prototype,"error",2);De([d()],me.prototype,"savedMessage",2);De([d({attribute:!1})],me.prototype,"onReload",2);De([d({attribute:!1})],me.prototype,"onSave",2);De([b()],me.prototype,"draft",2);De([b()],me.prototype,"localError",2);me=De([E("settings-general-panel")],me);function cv(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 jr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function dv(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function pv(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function hv(e){return e instanceof Error?e.message:String(e)}var uv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,je=(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&&uv(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
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`
1470
+ <div class="section-heading">
1471
+ <div>
1472
+ <h2>Session daemon</h2>
1473
+ <p>These settings affect the long-lived session runtime. Changes are saved to the config file immediately but only take effect after the session daemon restarts.</p>
1474
+ </div>
1475
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1476
+ </div>
1477
+ ${this.renderMessages()}
1478
+ <div class="restart-note" role="note">Restart required: run <code>pi-web restart</code> (or restart the session daemon service) after changing these settings.</div>
1479
+ ${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
1480
+ <div class="config-path-card">
1481
+ <span>Config file</span>
1482
+ <code>${e?.path??"Unknown"}</code>
1483
+ </div>
1484
+ <div class="field">
1485
+ <span class="field-heading">
1486
+ <span>Allow agents to start sessions</span>
1487
+ ${t?l`<span class="override-badge">environment override</span>`:null}
1488
+ </span>
1489
+ <label class="toggle">
1490
+ <input
1491
+ type="checkbox"
1492
+ .checked=${i}
1493
+ ?disabled=${this.loading||this.saving||t}
1494
+ @change=${s=>{this.toggleSpawnSessions(s)}}
1495
+ >
1496
+ <span>Enable the <code>spawn_session</code> tool</span>
1497
+ </label>
1498
+ <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
+ </div>
1500
+ <section class="effective-card" aria-label="Effective configuration summary">
1501
+ <h3>Effective after environment overrides</h3>
1502
+ <dl>
1503
+ <div><dt>Spawn sessions</dt><dd>${i?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
1504
+ </dl>
1505
+ </section>
1506
+ `}
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=_`
1508
+ :host { display: block; }
1509
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1510
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1511
+ h2, h3, p { margin: 0; }
1512
+ h2 { font-size: 17px; line-height: 1.25; }
1513
+ h3 { font-size: 13px; line-height: 1.3; }
1514
+ p { color: var(--pi-muted); line-height: 1.45; }
1515
+ button, input { font: inherit; }
1516
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1517
+ button:disabled { opacity: .55; cursor: not-allowed; }
1518
+ .secondary { flex: 0 0 auto; }
1519
+ .message, .loading-card, .config-path-card, .effective-card, .restart-note { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1520
+ .message { margin-bottom: 12px; }
1521
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1522
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1523
+ .loading-card { color: var(--pi-muted); }
1524
+ .restart-note { margin-bottom: 14px; border-color: var(--pi-warning-border); color: var(--pi-warning); background: var(--pi-warning-surface); line-height: 1.45; }
1525
+ .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1526
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1527
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1528
+ .field { display: grid; gap: 7px; margin-bottom: 14px; }
1529
+ .field small { color: var(--pi-muted); line-height: 1.45; }
1530
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1531
+ .toggle { display: flex; align-items: center; gap: 9px; cursor: pointer; }
1532
+ .toggle input { width: 16px; height: 16px; }
1533
+ .toggle input:disabled { cursor: not-allowed; }
1534
+ .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; }
1535
+ .effective-card { display: grid; gap: 10px; }
1536
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
1537
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1538
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1539
+ .muted { color: var(--pi-muted); }
1540
+
1541
+ @media (max-width: 760px) {
1542
+ .section-heading { display: grid; gap: 12px; }
1543
+ .section-heading .secondary { justify-self: start; }
1544
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1545
+ }
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`
1397
1547
  <div class="section-heading">
1398
1548
  <div>
1399
1549
  <h2>Plugins</h2>
@@ -1420,7 +1570,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1420
1570
  <span>${e.enabled?"Enabled":"Disabled"}</span>
1421
1571
  </label>
1422
1572
  </article>
1423
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Re.styles=W`
1573
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Re.styles=_`
1424
1574
  :host { display: block; }
1425
1575
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1426
1576
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1453,7 +1603,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1453
1603
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1454
1604
  .toggle { justify-self: start; }
1455
1605
  }
1456
- `;je([d({attribute:!1})],Re.prototype,"pluginsResponse",2);je([d({attribute:!1})],Re.prototype,"configResponse",2);je([d({type:Boolean})],Re.prototype,"loading",2);je([d({type:Boolean})],Re.prototype,"saving",2);je([d()],Re.prototype,"error",2);je([d()],Re.prototype,"savedMessage",2);je([d({attribute:!1})],Re.prototype,"onReload",2);je([d({attribute:!1})],Re.prototype,"onTogglePlugin",2);Re=je([E("settings-plugins-panel")],Re);var gv=Object.defineProperty,mv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?mv(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};const Nr={capture:!0};let se=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=Tn(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&&!At(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=yv(this.actions),t=this.shortcutResolutions();return l`
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`
1457
1607
  <div class="section-heading">
1458
1608
  <div>
1459
1609
  <h2>Keyboard shortcuts</h2>
@@ -1477,19 +1627,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1477
1627
  </section>
1478
1628
  `)}
1479
1629
  `}
1480
- `}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=xi(e.id,i),o=$v(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Ki(r),a=n?.ok===!0?n.shortcut:kv(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=wv(t);return l`
1481
- <article class=${vv(t)}>
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)}>
1482
1632
  <div class="shortcut-main">
1483
1633
  <strong>${e.title}</strong>
1484
1634
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1485
1635
  <small class="shortcut-id">${e.id}</small>
1486
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ei(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1636
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ri(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1487
1637
  </div>
1488
1638
  <div class="shortcut-editor">
1489
1639
  <div class="shortcut-status">
1490
- ${a!==void 0&&a!==""?l`<kbd>${ei(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
1491
- <small class=${u}>${Pv(u)}${p?" · Unsaved":""}</small>
1492
- ${f===void 0?null:l`<small class=${bv(t)}>${f}</small>`}
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>`}
1493
1643
  </div>
1494
1644
  <label class="shortcut-input-label">
1495
1645
  <span>Shortcut</span>
@@ -1502,7 +1652,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1502
1652
  autocapitalize="off"
1503
1653
  spellcheck="false"
1504
1654
  ?disabled=${this.saving}
1505
- @input=${v=>{this.updateDraft(e.id,Rv(v))}}
1655
+ @input=${v=>{this.updateDraft(e.id,ab(v))}}
1506
1656
  >
1507
1657
  </label>
1508
1658
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1514,7 +1664,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1514
1664
  </div>
1515
1665
  </div>
1516
1666
  </article>
1517
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=xi(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: ${ei(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=Ki(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?xv(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(Gs(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=Ki(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()},In)}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,Nr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Nr),this.recordingListenerActive=!1)}};se.styles=W`
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=_`
1518
1668
  :host { display: block; }
1519
1669
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1520
1670
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1569,7 +1719,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1569
1719
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1570
1720
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1571
1721
  }
1572
- `;be([d({attribute:!1})],se.prototype,"actions",2);be([d({attribute:!1})],se.prototype,"configResponse",2);be([d({type:Boolean})],se.prototype,"loading",2);be([d({type:Boolean})],se.prototype,"saving",2);be([d()],se.prototype,"error",2);be([d()],se.prototype,"savedMessage",2);be([d({attribute:!1})],se.prototype,"onReload",2);be([d({attribute:!1})],se.prototype,"onSave",2);be([b()],se.prototype,"drafts",2);be([b()],se.prototype,"localError",2);be([b()],se.prototype,"recording",2);se=be([E("settings-shortcuts-panel")],se);function vv(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function bv(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function wv(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 yv(e){const t=new Map;for(const i of[...e].sort(Sv)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Sv(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function xi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function xv(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function kv(e,t){const i=xi(e.id,t);if(i!==null)return i??e.shortcut}function $v(e,t){const i=xi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Pv(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function Rv(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Cv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?Iv(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 oe=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`
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`
1573
1723
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1574
1724
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1575
1725
  <header class="settings-header">
@@ -1582,6 +1732,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1582
1732
  <div class="settings-body">
1583
1733
  <nav class="settings-nav" aria-label="Settings sections">
1584
1734
  ${this.renderNavButton("general","General","Server config")}
1735
+ ${this.renderNavButton("sessiond","Session daemon","Runtime settings")}
1585
1736
  ${this.renderNavButton("plugins","Plugins","Enable and disable")}
1586
1737
  ${this.renderNavButton("shortcuts","Keyboard","Shortcuts")}
1587
1738
  </nav>
@@ -1591,7 +1742,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1591
1742
  </div>
1592
1743
  </section>
1593
1744
  </div>
1594
- `}renderActiveSection(){return this.section==="shortcuts"?l`
1745
+ `}renderActiveSection(){return this.section==="sessiond"?l`
1746
+ <settings-sessiond-panel
1747
+ .configResponse=${this.configResponse}
1748
+ .loading=${this.loading}
1749
+ .saving=${this.saving}
1750
+ .error=${this.error}
1751
+ .savedMessage=${this.savedMessage}
1752
+ .onReload=${()=>this.loadConfig()}
1753
+ .onSave=${e=>this.saveConfig(e)}
1754
+ ></settings-sessiond-panel>
1755
+ `:this.section==="shortcuts"?l`
1595
1756
  <settings-shortcuts-panel
1596
1757
  .actions=${this.actions}
1597
1758
  .configResponse=${this.configResponse}
@@ -1628,7 +1789,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1628
1789
  <strong>${t}</strong>
1629
1790
  <small>${i}</small>
1630
1791
  </button>
1631
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ai.config(),hs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${os(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 ai.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${os(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await hs.plugins()}catch(e){this.error=`Failed to refresh plugins: ${os(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?.())}};oe.styles=W`
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=_`
1632
1793
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1633
1794
  .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; }
1634
1795
  .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; }
@@ -1655,7 +1816,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1655
1816
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1656
1817
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1657
1818
  }
1658
- `;we([d({attribute:!1})],oe.prototype,"section",2);we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"onNavigate",2);we([d({attribute:!1})],oe.prototype,"onClose",2);we([d({attribute:!1})],oe.prototype,"onConfigSaved",2);we([b()],oe.prototype,"configResponse",2);we([b()],oe.prototype,"pluginsResponse",2);we([b()],oe.prototype,"loading",2);we([b()],oe.prototype,"saving",2);we([b()],oe.prototype,"error",2);we([b()],oe.prototype,"savedMessage",2);oe=we([E("settings-dialog")],oe);function os(e){return e instanceof Error?e.message:String(e)}var Mv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tv(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&&Mv(t,i,o),o};let le=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`
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`
1659
1820
  ${this.hideToolTabs?null:l`
1660
1821
  <header>
1661
1822
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -1685,32 +1846,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1685
1846
  <h2>${e.title}</h2>
1686
1847
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
1687
1848
  </section>
1688
- `}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}};le.styles=gf;Ce([d({attribute:!1})],le.prototype,"workspace",2);Ce([d({attribute:!1})],le.prototype,"panelContext",2);Ce([d({attribute:!1})],le.prototype,"emptyState",2);Ce([d()],le.prototype,"tool",2);Ce([d({attribute:!1})],le.prototype,"panels",2);Ce([d({type:Boolean})],le.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],le.prototype,"onSelectTool",2);Ce([z(".workspace-header-strip")],le.prototype,"workspaceHeaderStrip",2);Ce([b()],le.prototype,"workspaceHeaderCanScrollLeft",2);Ce([b()],le.prototype,"workspaceHeaderCanScrollRight",2);le=Ce([E("workspace-panel")],le);var Av=Object.defineProperty,Ev=Object.getOwnPropertyDescriptor,ye=(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&&Av(t,i,o),o};let re=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=Dv(this.machines),t=Wv(this.machine),i=Ov(this.project),s=jv(this.workspace),o=zv(this.session);return l`
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`
1689
1850
  <nav class=${this.contextBarClass()} aria-label="Current location">
1690
1851
  <span class="context-bar-label">Location</span>
1691
1852
  <ol class="context-items" @scroll=${this.onContextScroll}>
1692
1853
  ${e?l`
1693
1854
  <li class="context-item">
1694
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${_v(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
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")}}>
1695
1856
  <span class="context-kind">Machine</span>
1696
1857
  <span class="context-value">${t}</span>
1697
1858
  </button>
1698
1859
  </li>
1699
1860
  `:null}
1700
1861
  <li class="context-item">
1701
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Lv(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
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")}}>
1702
1863
  <span class="context-kind">Project</span>
1703
1864
  <span class="context-value">${i}</span>
1704
1865
  </button>
1705
1866
  </li>
1706
1867
  <li class="context-item">
1707
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Nv(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
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")}}>
1708
1869
  <span class="context-kind">Workspace</span>
1709
1870
  <span class="context-value">${s}</span>
1710
1871
  </button>
1711
1872
  </li>
1712
1873
  <li class="context-item">
1713
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Fv(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
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")}}>
1714
1875
  <span class="context-kind">Session</span>
1715
1876
  <span class="context-value">${o}</span>
1716
1877
  </button>
@@ -1724,7 +1885,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1724
1885
  <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1725
1886
  </svg>
1726
1887
  </button>
1727
- `}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}};re.styles=W`
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=_`
1728
1889
  /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1729
1890
  :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1730
1891
  .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); }
@@ -1750,7 +1911,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1750
1911
  .context-kind { display: none; }
1751
1912
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1752
1913
  button { cursor: pointer; }
1753
- `;ye([d({attribute:!1})],re.prototype,"machines",2);ye([d({attribute:!1})],re.prototype,"machine",2);ye([d({attribute:!1})],re.prototype,"project",2);ye([d({attribute:!1})],re.prototype,"workspace",2);ye([d({attribute:!1})],re.prototype,"session",2);ye([d({attribute:!1})],re.prototype,"refreshControl",2);ye([d({attribute:!1})],re.prototype,"onOpenSection",2);ye([d({attribute:!1})],re.prototype,"onShowActions",2);ye([z(".context-items")],re.prototype,"contextItems",2);ye([b()],re.prototype,"canScrollLeft",2);ye([b()],re.prototype,"canScrollRight",2);re=ye([E("app-context-bar")],re);function Dv(e){return e.length>1}function Wv(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function _v(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Ov(e){return e?.name??"No project"}function Lv(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function jv(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Nv(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function zv(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 Fv(e){return e===void 0?"No session selected":e.path}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Ye=(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 Oe=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`
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`
1754
1915
  <div class=${this.frameClass()}>
1755
1916
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1756
1917
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -1762,7 +1923,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1762
1923
  `})}
1763
1924
  </div>
1764
1925
  </div>
1765
- `}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>`:Dh(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}};Oe.styles=W`
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=_`
1766
1927
  :host { flex: 0 0 auto; min-width: 0; }
1767
1928
  .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); }
1768
1929
  .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; }
@@ -1788,12 +1949,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1788
1949
  .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; }
1789
1950
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1790
1951
  }
1791
- `;Ye([d({attribute:!1})],Oe.prototype,"tabs",2);Ye([d({attribute:!1})],Oe.prototype,"selectedView",2);Ye([d({attribute:!1})],Oe.prototype,"onSelect",2);Ye([z(".mobile-tabs")],Oe.prototype,"mobileTabs",2);Ye([b()],Oe.prototype,"canScrollLeft",2);Ye([b()],Oe.prototype,"canScrollRight",2);Oe=Ye([E("app-mobile-main-tabs")],Oe);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,de=(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 Y=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=rs(e,this.statuses),i=e.name;return l`
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`
1792
1953
  <div class="machine-switcher">
1793
1954
  <button
1794
1955
  type="button"
1795
1956
  class="machine-switcher-button"
1796
- title=${Fr(e)}
1957
+ title=${Kr(e)}
1797
1958
  aria-label=${`Machine: ${i}. Switch machine.`}
1798
1959
  aria-expanded=${String(this.open)}
1799
1960
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -1804,7 +1965,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1804
1965
  <span class="machine-switcher-kicker">Machine</span>
1805
1966
  <span class="machine-switcher-label">${i}</span>
1806
1967
  </span>
1807
- <span class=${`machine-status ${t}`}>${zr(t)}</span>
1968
+ <span class=${`machine-status ${t}`}>${qr(t)}</span>
1808
1969
  <span class="machine-chevron" aria-hidden="true">▾</span>
1809
1970
  </button>
1810
1971
  ${this.open?l`
@@ -1813,18 +1974,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1813
1974
  </div>
1814
1975
  `:null}
1815
1976
  </div>
1816
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=rs(e,this.statuses),s=ea(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
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`
1817
1978
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
1818
1979
  <button
1819
1980
  type="button"
1820
1981
  class="machine-option-main"
1821
- title=${Fr(e)}
1982
+ title=${Kr(e)}
1822
1983
  data-machine-id=${e.id}
1823
1984
  @click=${()=>{this.select(e)}}
1824
1985
  @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
1825
1986
  >
1826
1987
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
1827
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${zr(i)}</small>
1988
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${qr(i)}</small>
1828
1989
  </button>
1829
1990
  ${s?l`
1830
1991
  <div class="machine-option-actions">
@@ -1844,7 +2005,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1844
2005
  </div>
1845
2006
  `:null}
1846
2007
  </div>
1847
- `}renderActivity(e){const t=rs(e,this.statuses);if(t==="offline"||t==="error")return;const i=qn(this.activities[e.id]);return Gn(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=Br(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=Br(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=jt(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)}};Y.styles=W`
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=_`
1848
2009
  :host { min-width: 0; display: block; }
1849
2010
  .machine-switcher { min-width: 0; }
1850
2011
  .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; }
@@ -1859,6 +2020,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1859
2020
  .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
1860
2021
  .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
1861
2022
  .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
2023
+ .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
1862
2024
  .machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
1863
2025
  .machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
1864
2026
  .machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
@@ -1876,10 +2038,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1876
2038
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
1877
2039
  .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); }
1878
2040
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
1879
- `;de([d({attribute:!1})],Y.prototype,"machines",2);de([d({attribute:!1})],Y.prototype,"selected",2);de([d({attribute:!1})],Y.prototype,"statuses",2);de([d({attribute:!1})],Y.prototype,"activities",2);de([d({attribute:!1})],Y.prototype,"onSelect",2);de([d({attribute:!1})],Y.prototype,"onRemove",2);de([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);de([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);de([b()],Y.prototype,"open",2);de([b()],Y.prototype,"menuStyle",2);de([b()],Y.prototype,"openActionsMachineId",2);de([b()],Y.prototype,"actionMenuStyle",2);Y=de([E("machine-switcher")],Y);function rs(e,t){return t[e.id]?.status??e.status??"unknown"}function zr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Fr(e){return e.baseUrl??e.name}function Br(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: ${Gt(t.bottom)};`,`left: ${Gt(o)};`,`width: ${Gt(s)};`,`max-height: ${Gt(r)};`].join(" ")}function Gt(e){return`${String(Math.round(e))}px`}var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,k=(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 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.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.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`
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`
1880
2042
  <header>
1881
2043
  <strong>PI WEB</strong>
1882
- ${ki(this.machines)?l`
2044
+ ${Mi(this.machines)?l`
1883
2045
  <machine-switcher
1884
2046
  .machines=${this.machines}
1885
2047
  .selected=${this.selectedMachine}
@@ -1896,7 +2058,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1896
2058
  <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
1897
2059
  </div>
1898
2060
  </header>
1899
- ${this.compact&&ki(this.machines)?l`
2061
+ ${this.compact&&Mi(this.machines)?l`
1900
2062
  <machine-list
1901
2063
  .machines=${this.machines}
1902
2064
  .selected=${this.selectedMachine}
@@ -1944,9 +2106,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1944
2106
  .sessions=${this.sessions}
1945
2107
  .statuses=${this.sessionStatuses}
1946
2108
  .activities=${this.sessionActivities}
2109
+ .sending=${this.sendingPrompts}
1947
2110
  .selected=${this.selectedSession}
1948
2111
  .canStart=${this.canStartSession}
1949
2112
  .canDeleteArchived=${this.canDeleteArchivedSessions}
2113
+ .canReload=${this.canReloadSessions}
1950
2114
  .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
1951
2115
  .collapsible=${this.collapsible}
1952
2116
  .collapsed=${this.sessionsCollapsed}
@@ -1962,11 +2126,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1962
2126
  .onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
1963
2127
  .onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
1964
2128
  .onDetachParent=${e=>this.onDetachParentSession?.(e)}
2129
+ .onReload=${e=>this.onReloadSession?.(e)}
1965
2130
  .onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
1966
2131
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
1967
2132
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
1968
2133
  ></session-list>
1969
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Gv(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Qv(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=W`
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=_`
1970
2135
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
1971
2136
  :host([compact]) { flex: 1 1 auto; }
1972
2137
  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); }
@@ -1989,7 +2154,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1989
2154
  :host([compact]) workspace-list[collapsed],
1990
2155
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1991
2156
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1992
- `;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,"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: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,"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([z("machine-list")],x.prototype,"machineList",2);k([z("machine-switcher")],x.prototype,"machineSwitcher",2);k([z("project-list")],x.prototype,"projectList",2);k([z("workspace-list")],x.prototype,"workspaceList",2);k([z("session-list")],x.prototype,"sessionList",2);x=k([E("app-navigation-panel")],x);function ki(e){return e.length>1}function Gv(e,t){const i=wa(t);return i[i.indexOf(e)-1]}function Qv(e,t){const i=wa(t);return i[i.indexOf(e)+1]??"chat"}function wa(e){return mi.filter(t=>t!=="machines"||ki(e))}var Zv=Object.defineProperty,Jv=Object.getOwnPropertyDescriptor,J=(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 Xv=new Set(["ArrowLeft","ArrowRight","Home","End"]),Yv=420,eb=4;let q=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`
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`
1993
2158
  ${this.renderResizeHandle()}
1994
2159
  <button
1995
2160
  type="button"
@@ -2000,7 +2165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2000
2165
  aria-expanded=${String(!this.collapsed)}
2001
2166
  @click=${()=>{this.onToggle?.()}}
2002
2167
  >${this.renderIcon()}</button>
2003
- `}renderResizeHandle(){if(!this.resizable)return L;const e=this.resizeConstraints();return l`
2168
+ `}renderResizeHandle(){if(!this.resizable)return z;const e=this.resizeConstraints();return l`
2004
2169
  <div
2005
2170
  class="resize-handle"
2006
2171
  role="separator"
@@ -2019,7 +2184,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2019
2184
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2020
2185
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2021
2186
  ></div>
2022
- `}resizeAriaValueNow(){return this.panelWidth===void 0?L: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)<=eb)&&(t.moved=!0,this.commitPanelWidth(Nu(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||!Xv.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=zu(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<=Yv){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 he(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(he(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=Lt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};q.styles=W`
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=_`
2023
2188
  :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; }
2024
2189
  :host([side="navigation"]) { grid-column: 2; }
2025
2190
  :host([side="workspace"]) { grid-column: 4; }
@@ -2038,7 +2203,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2038
2203
  @media (max-width: 760px) {
2039
2204
  :host([side="navigation"]) { display: none; }
2040
2205
  }
2041
- `;J([d({reflect:!0})],q.prototype,"side",2);J([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);J([d({type:Boolean})],q.prototype,"resizable",2);J([d({type:Number})],q.prototype,"panelWidth",2);J([d({type:Number})],q.prototype,"minWidth",2);J([d({type:Number})],q.prototype,"maxWidth",2);J([d()],q.prototype,"controls",2);J([d()],q.prototype,"resizeLabel",2);J([d()],q.prototype,"expandLabel",2);J([d()],q.prototype,"collapseLabel",2);J([d({attribute:!1})],q.prototype,"onToggle",2);J([d({attribute:!1})],q.prototype,"onResizeStart",2);J([d({attribute:!1})],q.prototype,"onResize",2);J([d({attribute:!1})],q.prototype,"onResizeEnd",2);J([d({attribute:!1})],q.prototype,"onReset",2);q=J([E("app-panel-edge-control")],q);var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,ya=(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&&tb(t,i,o),o};let $i=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
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`
2042
2207
  <button
2043
2208
  class="app-refresh-button"
2044
2209
  title=${e}
@@ -2052,12 +2217,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2052
2217
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2053
2218
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2054
2219
  </svg>
2055
- `}};$i.styles=W`
2220
+ `}};Ti.styles=_`
2056
2221
  :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; }
2057
2222
  :host, :host * { -webkit-user-select: none; user-select: none; }
2058
2223
  .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; }
2059
2224
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2060
- `;ya([d({attribute:!1})],$i.prototype,"onReload",2);$i=ya([E("app-refresh-control")],$i);var sb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?ob(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&&sb(t,i,o),o};const rb=900*1e3,nb=750,Ms=[1e3,3e3,8e3,15e3,3e4],Ur={capture:!0},ns="auto:on",Hr="auto:off",Qt="theme:",as=Dt("core:workspace.files"),ls=Dt("core:workspace.git"),Zt=Dt("core:workspace.terminal"),ab=320,lb=2,cb="(min-width: 1181px)";let ce=class extends C{constructor(){super(...arguments),this.state=_c(),this.sessions=new xp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new mp),this.activity=new Oc(()=>this.state,e=>{this.setState(e)}),this.auth=new Nc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Op(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Wp),this.projects=new Gc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Vc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Kc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Qp,this.realtime=new Qo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new zp,this.terminalSelection=new Vp,this.appShell=new $u(this),this.panelCollapse=new _u(this),this.panelResize=new Lu(this),this.navigationSections=new Eu(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=db(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=dh()??ah,this.activeThemeId=Zs,this.isRefreshingApp=!1,this.settingsSection=hr(),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,Ur),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},rb),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,Ur),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(!ub(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),pb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=pr();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=nb){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 un.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=>Sa(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 ai.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(pr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?Vr():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===""?Vr():{selectedFilePath:Ui(as,"file"),selectedDiffPath:Ui(ls,"diff"),selectedTerminalId:Ui(Zt,"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){Qi(e,{replace:!0}),Se(as,"file",void 0,{replace:!0}),Se(ls,"diff",void 0,{replace:!0}),Se(Zt,"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=gb(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>=Ms.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 cs(),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(),Qi({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(Xo(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Xo(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Qi(Yo(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Se(as,"file",e.selectedFilePath,{replace:!0}),Se(ls,"diff",e.selectedDiffPath,{replace:!0}),Se(Zt,"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)??Fp(e.id);if(await this.restoreRouteFor(Yo(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=Gr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=ef(e,{api:{runTerminalCommand:(r,n)=>nt.runTerminalCommand(r,n,t),listCommandRuns:r=>nt.listCommandRuns(r,t),getCommandRun:r=>nt.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){Se(Zt,"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,Zi(e)}closeSettings(){this.settingsSection=void 0,Zi(void 0)}navigateSettings(e){this.settingsSection=e,Zi(e)}restoreSettingsRoute(){this.settingsSection=hr()}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 Qo;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=>hb(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):fb(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 nt.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=Kr(e),s=Kr(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`
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`
2061
2226
  <workspace-panel
2062
2227
  id="workspace-panel"
2063
2228
  .workspace=${e}
@@ -2103,7 +2268,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2103
2268
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2104
2269
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2105
2270
  ></app-panel-edge-control>
2106
- `}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-lb-ab);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(cb).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&&tn(e,Os.sessionsDeleteArchived)}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`
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`
2107
2272
  <app-navigation-panel
2108
2273
  .machines=${this.state.machines}
2109
2274
  .selectedMachine=${this.state.selectedMachine}
@@ -2119,13 +2284,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2119
2284
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2120
2285
  .workspaces=${this.state.workspaces}
2121
2286
  .selectedWorkspace=${this.state.selectedWorkspace}
2122
- .deletingWorkspaceIds=${$h(this.state.workspaceDeletionRuns)}
2287
+ .deletingWorkspaceIds=${Lh(this.state.workspaceDeletionRuns)}
2123
2288
  .sessions=${this.state.sessions}
2124
2289
  .sessionStatuses=${this.state.sessionStatuses}
2125
2290
  .sessionActivities=${this.state.sessionActivities}
2291
+ .sendingPrompts=${this.state.sendingPrompts}
2126
2292
  .selectedSession=${this.state.selectedSession}
2127
2293
  .canStartSession=${!!this.state.selectedWorkspace}
2128
2294
  .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
2295
+ .canReloadSessions=${this.canReloadSessions()}
2129
2296
  .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
2130
2297
  .collapsible=${!0}
2131
2298
  .compact=${this.appShell.isMobileNavigationLayout}
@@ -2153,17 +2320,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2153
2320
  .onDeleteArchivedSession=${e=>this.sessions.deleteArchivedSessions([e])}
2154
2321
  .onDeleteArchivedSessions=${e=>this.sessions.deleteArchivedSessions(e)}
2155
2322
  .onDetachParentSession=${e=>this.sessions.detachParent(e)}
2323
+ .onReloadSession=${e=>this.sessions.reloadSession(e)}
2156
2324
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2157
2325
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2158
2326
  ></app-navigation-panel>
2159
- `}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"&&!ki(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 cs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await cs(),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=qr(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=>us.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=qr(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return hu({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 Xu(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",()=>ar())}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}`,()=>ar(`/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(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Lp(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(On(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
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}?
2160
2328
 
2161
2329
  This will run git worktree remove and delete:
2162
2330
  ${e.path}
2163
2331
 
2164
- The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await us.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: ${mb(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=Ss(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(xh(t.id));if(g(this.state)!==e)return;const s=kh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))fi(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(fi);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=Gr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ss(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:vb(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}?
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}?
2165
2333
 
2166
- 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?Hr:ns;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${Qt}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${Qt}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ns||e===Hr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ns},this.applyPreferredTheme(!0);return}if(!e.startsWith(Qt))return;const t=e.slice(Qt.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,hh(t),e&&ph(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return uh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return _n(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=>({value:i,label:`${i}${i===t?" ✓ current":""}`,description:wb(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),bb(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
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`
2167
2335
  <app-context-bar
2168
2336
  .machines=${this.state.machines}
2169
2337
  .machine=${this.state.selectedMachine}
@@ -2184,14 +2352,14 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
2184
2352
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2185
2353
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2186
2354
  ${this.renderNavigationPanelEdgeControl()}
2187
- <main class=${Bn(e.mainView)}>
2355
+ <main class=${Gn(e.mainView)}>
2188
2356
  ${this.renderContextBar()}
2189
2357
  ${this.renderMobileMainTabs()}
2190
2358
  ${e.error?l`<div class="error">${e.error}</div>`:null}
2191
2359
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2192
2360
  ${e.selectedSession?l`
2193
- <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} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
2194
- <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} .onSend=${(t,i)=>{this.sendPrompt(t,i)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2361
+ <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>
2195
2363
  <status-bar .status=${e.status}></status-bar>
2196
2364
  ${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}
2197
2365
  ${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}
@@ -2207,4 +2375,4 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
2207
2375
  ${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}
2208
2376
  ${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}
2209
2377
  </div>
2210
- `}};ce.styles=ff;Ie([b()],ce.prototype,"state",2);Ie([z("chat-view")],ce.prototype,"chatView",2);Ie([z("prompt-editor")],ce.prototype,"promptEditor",2);Ie([z("app-navigation-panel")],ce.prototype,"navigationPanel",2);Ie([z("#navigation-panel")],ce.prototype,"navigationPanelFrame",2);Ie([z("#workspace-panel")],ce.prototype,"workspacePanelFrame",2);Ie([b()],ce.prototype,"activeThemeId",2);Ie([b()],ce.prototype,"isRefreshingApp",2);Ie([b()],ce.prototype,"settingsSection",2);Ie([b()],ce.prototype,"shortcutConfig",2);ce=Ie([E("pi-web-app")],ce);function db(){const e=new cu;return e.register({id:"core",plugin:Kh}),e.register({id:"themes",plugin:Zh}),e}function qr(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 pb(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function hb(e,t){return Sa(e,t)}function Sa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function ub(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Kr(e){return Ci(e.status,e.activity)}function fb(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Vr(){return{}}function Gr(e,t){return JSON.stringify([e,t])}function gb(e){const t=Math.min(e,Ms.length-1);return Ms[t]??3e4}function mb(e){return e instanceof Error?e.message:String(e)}function vb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function cs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function bb(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function wb(e){switch(e){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)"}}export{W as a,l as b,nt as c,Ab as d,z as e,Mb as f,C as i,d as n,b as r,Tb as s,E as t};
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};