@jmfederico/pi-web 1.202606.0 → 1.202606.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +21 -7
  2. package/dist/client/assets/{CodeViewer-N88Bx8F6.js → CodeViewer-BcQUZop_.js} +1 -1
  3. package/dist/client/assets/{TerminalPanel-DKiL51Xi.js → TerminalPanel-1o4j3QP_.js} +4 -4
  4. package/dist/client/assets/index-CM8WX5nf.js +1994 -0
  5. package/dist/client/index.html +1 -1
  6. package/dist/config.js +63 -1
  7. package/dist/config.js.map +1 -1
  8. package/dist/pi-web-plugins/info/pi-web-plugin.js +8 -1
  9. package/dist/pi-web-plugins/updates/package.json +9 -0
  10. package/dist/pi-web-plugins/{pi-web → updates}/pi-web-plugin.js +38 -30
  11. package/dist/pi-web-plugins/workspace-tasks/config.js +91 -0
  12. package/dist/pi-web-plugins/workspace-tasks/package.json +9 -0
  13. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +48 -0
  14. package/dist/pi-web-plugins/workspace-tasks/taskRunner.js +12 -0
  15. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +292 -0
  16. package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +47 -0
  17. package/dist/plugin-api/unstable.d.ts +22 -0
  18. package/dist/plugin-api.d.ts +169 -0
  19. package/dist/server/app.js +55 -25
  20. package/dist/server/app.js.map +1 -1
  21. package/dist/server/configRoutes.js +123 -0
  22. package/dist/server/configRoutes.js.map +1 -0
  23. package/dist/server/git/gitEnv.js +15 -0
  24. package/dist/server/git/gitEnv.js.map +1 -0
  25. package/dist/server/git/gitService.js +2 -1
  26. package/dist/server/git/gitService.js.map +1 -1
  27. package/dist/server/gitRoutes.js +3 -3
  28. package/dist/server/gitRoutes.js.map +1 -1
  29. package/dist/server/machines/machineClient.js +134 -0
  30. package/dist/server/machines/machineClient.js.map +1 -0
  31. package/dist/server/machines/machinePluginProxyRoutes.js +179 -0
  32. package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -0
  33. package/dist/server/machines/machineProxyRoutes.js +92 -0
  34. package/dist/server/machines/machineProxyRoutes.js.map +1 -0
  35. package/dist/server/machines/machineRoutes.js +50 -0
  36. package/dist/server/machines/machineRoutes.js.map +1 -0
  37. package/dist/server/machines/machineService.js +168 -0
  38. package/dist/server/machines/machineService.js.map +1 -0
  39. package/dist/server/machines/machineStore.js +128 -0
  40. package/dist/server/machines/machineStore.js.map +1 -0
  41. package/dist/server/piWebPluginService.js +22 -12
  42. package/dist/server/piWebPluginService.js.map +1 -1
  43. package/dist/server/sessiond/sessionProxyRoutes.js +15 -13
  44. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  45. package/dist/server/sessions/piSessionService.js +19 -5
  46. package/dist/server/sessions/piSessionService.js.map +1 -1
  47. package/dist/server/sessions/sessionNameGenerator.js +2 -0
  48. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  49. package/dist/server/sessions/sessionRoutes.js +1 -1
  50. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  51. package/dist/server/terminalProxyRoutes.js +20 -10
  52. package/dist/server/terminalProxyRoutes.js.map +1 -1
  53. package/dist/server/terminals/terminalRoutes.js +11 -0
  54. package/dist/server/terminals/terminalRoutes.js.map +1 -1
  55. package/dist/server/terminals/terminalService.js +6 -0
  56. package/dist/server/terminals/terminalService.js.map +1 -1
  57. package/dist/server/workspaceExplorerRoutes.js +4 -4
  58. package/dist/server/workspaceExplorerRoutes.js.map +1 -1
  59. package/dist/server/workspaces/fileSuggestions.js +2 -1
  60. package/dist/server/workspaces/fileSuggestions.js.map +1 -1
  61. package/dist/server/workspaces/gitWorktreeDiscovery.js +3 -2
  62. package/dist/server/workspaces/gitWorktreeDiscovery.js.map +1 -1
  63. package/dist/server/workspaces/workspaceDeletionRoutes.js +113 -0
  64. package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -0
  65. package/dist/shared/apiTypes.d.ts +464 -0
  66. package/dist/shared/federatedRoutes.js +59 -0
  67. package/dist/shared/federatedRoutes.js.map +1 -0
  68. package/dist/shared/machinePluginIds.js +41 -0
  69. package/dist/shared/machinePluginIds.js.map +1 -0
  70. package/dist/shared/pluginIds.js +5 -0
  71. package/dist/shared/pluginIds.js.map +1 -0
  72. package/dist/shared/workspaceDeletion.js +12 -0
  73. package/dist/shared/workspaceDeletion.js.map +1 -0
  74. package/docs/plugins.md +276 -65
  75. package/package.json +8 -12
  76. package/plugin-api/unstable.d.ts +1 -0
  77. package/plugin-api.d.ts +1 -148
  78. package/dist/client/assets/index-DeSR1RUE.js +0 -1446
  79. package/dist/pi-web-plugins/pi-web/package.json +0 -9
@@ -0,0 +1,1994 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-BcQUZop_.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-1o4j3QP_.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Bs,w as Je,J as $i,R as $n,S as Pn,G as Cn,U as In,V as Tn,A as Mn,W as An,X as Rn,Y as En,Z as zs,x as Us,_ as Dn}from"./vendor-editor-core-B4Sq6exx.js";import{m as _n,i as Ln,d as On}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Ht=globalThis,ns=Ht.ShadowRoot&&(Ht.ShadyCSS===void 0||Ht.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,as=Symbol(),Hs=new WeakMap;let ao=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(ns&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Hs.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Hs.set(i,t))}return t}toString(){return this.cssText}};const Wn=e=>new ao(typeof e=="string"?e:e+"",void 0,as),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new ao(i,e,as)},jn=(e,t)=>{if(ns)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Ht.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},qs=ns?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Wn(i)})(e):e;const{is:Nn,defineProperty:Fn,getOwnPropertyDescriptor:Bn,getOwnPropertyNames:zn,getOwnPropertySymbols:Un,getPrototypeOf:Hn}=Object,hi=globalThis,Vs=hi.trustedTypes,qn=Vs?Vs.emptyScript:"",Vn=hi.reactiveElementPolyfillSupport,vt=(e,t)=>e,Qt={toAttribute(e,t){switch(t){case Boolean:e=e?qn: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)=>!Nn(e,t),Ks={attribute:!0,type:String,converter:Qt,reflect:!1,useDefault:!1,hasChanged:ls};Symbol.metadata??=Symbol("metadata"),hi.litPropertyMetadata??=new WeakMap;let Xe=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=Ks){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Fn(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Bn(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ks}static _$Ei(){if(this.hasOwnProperty(vt("elementProperties")))return;const t=Hn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(vt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(vt("properties"))){const i=this.properties,s=[...zn(i),...Un(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const r of s)i.unshift(qs(r))}else t!==void 0&&i.push(qs(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 jn(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:Qt).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Qt;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??ls)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};Xe.elementStyles=[],Xe.shadowRootOptions={mode:"open"},Xe[vt("elementProperties")]=new Map,Xe[vt("finalized")]=new Map,Vn?.({ReactiveElement:Xe}),(hi.reactiveElementVersions??=[]).push("2.1.2");const cs=globalThis,Gs=e=>e,Zt=cs.trustedTypes,Js=Zt?Zt.createPolicy("lit-html",{createHTML:e=>e}):void 0,lo="$lit$",Re=`lit$${Math.random().toFixed(9).slice(2)}$`,co="?"+Re,Kn=`<${co}>`,Ne=document,yt=()=>Ne.createComment(""),xt=e=>e===null||typeof e!="object"&&typeof e!="function",ds=Array.isArray,Gn=e=>ds(e)||typeof e?.[Symbol.iterator]=="function",Pi=`[
3
+ \f\r]`,lt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Qs=/-->/g,Zs=/>/g,_e=RegExp(`>|${Pi}(?:([^\\s"'>=/]+)(${Pi}*=${Pi}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Xs=/'/g,Ys=/"/g,po=/^(?:script|style|textarea|title)$/i,ho=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=ho(1),Ye=ho(2),Ee=Symbol.for("lit-noChange"),j=Symbol.for("lit-nothing"),er=new WeakMap,We=Ne.createTreeWalker(Ne,129);function uo(e,t){if(!ds(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Js!==void 0?Js.createHTML(t):t}const Jn=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=lt;for(let a=0;a<i;a++){const c=e[a];let p,f,h=-1,u=0;for(;u<c.length&&(n.lastIndex=u,f=n.exec(c),f!==null);)u=n.lastIndex,n===lt?f[1]==="!--"?n=Qs:f[1]!==void 0?n=Zs:f[2]!==void 0?(po.test(f[2])&&(r=RegExp("</"+f[2],"g")),n=_e):f[3]!==void 0&&(n=_e):n===_e?f[0]===">"?(n=r??lt,h=-1):f[1]===void 0?h=-2:(h=n.lastIndex-f[2].length,p=f[1],n=f[3]===void 0?_e:f[3]==='"'?Ys:Xs):n===Ys||n===Xs?n=_e:n===Qs||n===Zs?n=lt:(n=_e,r=void 0);const v=n===_e&&e[a+1].startsWith("/>")?" ":"";o+=n===lt?c+Kn:h>=0?(s.push(p),c.slice(0,h)+lo+c.slice(h)+Re+v):c+Re+(h===-2?a:v)}return[uo(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class St{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,f]=Jn(t,i);if(this.el=St.createElement(p,s),We.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=We.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(lo)){const u=f[n++],v=r.getAttribute(h).split(Re),S=/([.?@])?(.*)/.exec(u);c.push({type:1,index:o,name:S[2],strings:v,ctor:S[1]==="."?Zn:S[1]==="?"?Xn:S[1]==="@"?Yn:ui}),r.removeAttribute(h)}else h.startsWith(Re)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(po.test(r.tagName)){const h=r.textContent.split(Re),u=h.length-1;if(u>0){r.textContent=Zt?Zt.emptyScript:"";for(let v=0;v<u;v++)r.append(h[v],yt()),We.nextNode(),c.push({type:2,index:++o});r.append(h[u],yt())}}}else if(r.nodeType===8)if(r.data===co)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Re,h+1))!==-1;)c.push({type:7,index:o}),h+=Re.length-1}o++}}static createElement(t,i){const s=Ne.createElement("template");return s.innerHTML=t,s}}function tt(e,t,i=e,s){if(t===Ee)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=xt(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=tt(e,r._$AS(e,t.values),r,s)),t}class Qn{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??Ne).importNode(i,!0);We.currentNode=r;let o=We.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new st(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new ea(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=We.nextNode(),n++)}return We.currentNode=Ne,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class st{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=j,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=tt(this,t,i),xt(t)?t===j||t==null||t===""?(this._$AH!==j&&this._$AR(),this._$AH=j):t!==this._$AH&&t!==Ee&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Gn(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!==j&&xt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ne.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=St.createElement(uo(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Qn(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=er.get(t.strings);return i===void 0&&er.set(t.strings,i=new St(t)),i}k(t){ds(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new st(this.O(yt()),this.O(yt()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Gs(t).nextSibling;Gs(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let ui=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=j,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=j}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=tt(this,t,i,0),n=!xt(t)||t!==this._$AH&&t!==Ee,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=tt(this,a[s+c],i,c),p===Ee&&(p=this._$AH[c]),n||=!xt(p)||p!==this._$AH[c],p===j?t=j:t!==j&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===j?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Zn=class extends ui{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===j?void 0:t}},Xn=class extends ui{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==j)}},Yn=class extends ui{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=tt(this,t,i,0)??j)===Ee)return;const s=this._$AH,r=t===j&&s!==j||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==j&&(s===j||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class ea{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){tt(this,t)}}const ta={I:st},ia=cs.litHtmlPolyfillSupport;ia?.(St,st),(cs.litHtmlVersions??=[]).push("3.3.2");const sa=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new st(t.insertBefore(yt(),o),o,void 0,i??{})}return r._$AI(e),r};const ps=globalThis;let T=class extends Xe{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=sa(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ee}};T._$litElement$=!0,T.finalized=!0,ps.litElementHydrateSupport?.({LitElement:T});const ra=ps.litElementPolyfillSupport;ra?.({LitElement:T});(ps.litElementVersions??=[]).push("4.2.2");const A=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const oa={attribute:!0,type:String,converter:Qt,reflect:!1,hasChanged:ls},na=(e=oa,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const 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"?na(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function x(e){return d({...e,state:!0,attribute:!1})}const aa=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function re(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return aa(i,s,{get(){return o(this)}})}}async function b(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const r=await fetch(e,{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(la(n)??r.statusText)}const o=await r.json();return t(o)}function la(e){if(ca(e))return typeof e.error=="string"?e.error:void 0}function ca(e){return typeof e=="object"&&e!==null}function bt(e){return typeof e=="object"&&e!==null}function y(e){if(!bt(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 Y(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function R(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function W(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function da(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function pa(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function ha(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:da(t.messages),start:Y(t,"start"),total:Y(t,"total")}}function ua(e){const t=y(e);return W(fo)(t.machines)}function fo(e){const t=y(e),i=ga(t,"kind"),s=$(t,"baseUrl"),r=go(t,"status"),o=$(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"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function fa(e){const t=y(e),i=go(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:R(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Xt(t.web)},...t.sessiond===void 0?{}:{sessiond:Xt(t.sessiond)},...s===void 0?{}:{error:s}}}function ga(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function go(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 tr(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function ma(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:R(t,"isMain"),isGitRepo:R(t,"isGitRepo"),isGitWorktree:R(t,"isGitWorktree")}}function qi(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(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:Y(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function ct(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:R(t,"isStreaming"),isCompacting:R(t,"isCompacting"),isBashRunning:R(t,"isBashRunning"),pendingMessageCount:Y(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:W(va)(t.queuedMessages),...w("messageCount",be(t,"messageCount")),tokens:ba(t.tokens),cost:Y(t,"cost"),...wa(t.model),...Ea(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function va(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 ba(e){const t=y(e);return{input:Y(t,"input"),output:Y(t,"output"),cacheRead:Y(t,"cacheRead"),cacheWrite:Y(t,"cacheWrite"),total:Y(t,"total")}}function mo(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",be(t,"contextWindow")),...w("reasoning",t.reasoning)}}function wa(e){return e===void 0?{}:{model:mo(e)}}function ya(e){const t=y(e);return{models:W(mo)(t.models)}}function xa(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Sa(e){const t=y(e);return{levels:W(xa)(t.levels)}}function ka(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function $a(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 Pa(e){const t=y(e),i=t.source===void 0?void 0:$a(t.source);return{configured:R(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Ca(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:ka(t.authType),status:Pa(t.status)}}function Ia(e){const t=y(e);return{providers:W(Ca)(t.providers)}}function Lt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Ta(t.status),progress:W(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Ma(t.auth)),...w("prompt",Aa(t.prompt)),...w("select",Ra(t.select))}}function Ta(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ma(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Aa(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 Ra(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:W(bo)(t.options)}}function Ea(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:ar(t,"tokens"),contextWindow:Y(t,"contextWindow"),percent:ar(t,"percent")}}}function Da(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 vo(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 _a(e){const t=y(e);return{path:m(t,"path"),entries:W(La)(t.entries),scannedAt:m(t,"scannedAt"),truncated:R(t,"truncated")}}function La(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",be(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function Oa(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",Wa(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:Y(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:R(t,"truncated"),binary:R(t,"binary")}}function Wa(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function ja(e){const t=y(e);return{isGitRepo:R(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",be(t,"ahead")),...w("behind",be(t,"behind")),files:W(Na)(t.files)}}function Na(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:ir(t.index),workingTree:ir(t.workingTree)}}function ir(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 Fa(e){const t=y(e);return{...w("path",$(t,"path")),staged:R(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:R(t,"truncated")}}function Ci(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:R(t,"exited"),...w("exitCode",be(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function wt(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:Ba(t.status),...w("exitCode",be(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:za(t.metadata,"metadata")}}function Ba(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function za(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function Ua(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:R(t,"hasSessionActivity"),hasTerminalActivity:R(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Ha(e){const t=y(e);return{workspaces:W(Ua)(t.workspaces),generatedAt:m(t,"generatedAt")}}function sr(e){const t=y(e);return{path:m(t,"path"),exists:R(t,"exists"),config:rr(t.config),effectiveConfig:rr(t.effectiveConfig),envOverrides:Ga(t.envOverrides)}}function rr(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",be(t,"port")),...w("allowedHosts",qa(t.allowedHosts)),...w("shortcuts",Va(t.shortcuts)),...w("plugins",Ka(t.plugins))}}function qa(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 Va(e){if(e!==void 0){if(!bt(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 Ka(e){if(e!==void 0){if(!bt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!bt(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 r=i.settings;if(r!==void 0&&(!bt(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Ga(e){const t=y(e);return{host:R(t,"host"),port:R(t,"port"),allowedHosts:R(t,"allowedHosts")}}function Ja(e){const t=y(e);return{plugins:W(Qa)(t.plugins)}}function Qa(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Za(t.scope),enabled:R(t,"enabled")}}function Za(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Xa(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Ya(t.components),release:tl(t.release),commands:il(t.commands),messages:W(sl)(t.messages)}}function Ya(e){const t=y(e);return{web:Xt(t.web),sessiond:Xt(t.sessiond)}}function Xt(e){const t=y(e);return{component:rl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:R(t,"stale"),available:R(t,"available"),...w("installation",el(t.installation)),...w("error",$(t,"error"))}}function el(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 tl(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:R(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function il(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 sl(e){const t=y(e);return{id:m(t,"id"),severity:ol(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function rl(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function ol(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function or(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:W(bo)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...nl(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function bo(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function nl(e){return e===void 0?{}:{session:qi(e)}}function Ot(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Vi(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function al(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function ll(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function nr(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:pa(t.sessionIds,"sessionIds"),s=be(t,"archivedCount"),r=be(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function cl(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function dl(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function be(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 ar(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 pl(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function hl(e,t,i="local"){const s=new URLSearchParams;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/${e}/messages${r?`?${r}`:""}`}function ul(e,t,i,s){const r=new URLSearchParams;return r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`}const k=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,wo={piWebStatus:()=>b("/api/pi-web/status",Xa)},fl={machines:()=>b("/api/machines",ua),addMachine:e=>b("/api/machines",fo,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>b(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>b(`/api/machines/${encodeURIComponent(e)}/health`,fa)},Yt={config:()=>b("/api/config",sr),saveConfig:e=>b("/api/config",sr,{method:"PUT",body:JSON.stringify({config:e})})},Ki={plugins:()=>b("/api/plugins",Ja)},yo={workspaceActivity:(e="local")=>b(`${k(e)}/activity`,Ha)},gl={projects:(e="local")=>b(`${k(e)}/projects`,W(tr)),addProject:(e,t,i,s="local")=>b(`${k(s)}/projects`,tr,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>b(`${k(t)}/projects/${encodeURIComponent(e)}`,Vi,{method:"DELETE"}),projectDirectories:(e,t="local")=>b(`${k(t)}/project-directories?q=${encodeURIComponent(e)}`,W(vo))},Gi={workspaces:(e,t="local")=>b(`${k(t)}/projects/${e}/workspaces`,W(ma)),deleteWorkspace:(e,t,i="local")=>b(`${k(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,wt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>b(`${k(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,_a),workspaceFile:(e,t,i,s="local")=>b(`${k(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Oa)},ml={sessions:(e,t="local")=>b(`${k(t)}/sessions?cwd=${encodeURIComponent(e)}`,W(qi)),startSession:(e,t="local")=>b(`${k(t)}/sessions`,qi,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>b(hl(e,t,i),ha),status:(e,t="local")=>b(`${k(t)}/sessions/${e}/status`,ct),models:(e,t="local")=>b(`${k(t)}/sessions/${e}/models`,ya),setModel:(e,t,i,s="local")=>b(`${k(s)}/sessions/${e}/model`,ct,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>b(`${k(i)}/sessions/${e}/model/cycle`,ct,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>b(`${k(t)}/sessions/${e}/thinking-levels`,Sa),setThinkingLevel:(e,t,i="local")=>b(`${k(i)}/sessions/${e}/thinking-level`,ct,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>b(`${k(t)}/sessions/${e}/thinking-level/cycle`,ct,{method:"POST"}),commands:(e,t="local")=>b(`${k(t)}/sessions/${e}/commands`,W(Da)),prompt:(e,t,i,s="local")=>b(`${k(s)}/sessions/${e}/prompt`,Ot,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>b(`${k(i)}/sessions/${e}/shell`,Ot,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>b(`${k(i)}/sessions/${e}/commands/run`,or,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>b(`${k(s)}/sessions/${e}/commands/respond`,or,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>b(`${k(t)}/sessions/${e}/abort`,al,{method:"POST"}),stop:(e,t="local")=>b(`${k(t)}/sessions/${e}/stop`,ll,{method:"POST"}),archive:(e,t="local")=>b(`${k(t)}/sessions/${e}/archive`,nr,{method:"POST"}),archiveWithDescendants:(e,t="local")=>b(`${k(t)}/sessions/${e}/archive-tree`,nr,{method:"POST"}),restore:(e,t="local")=>b(`${k(t)}/sessions/${e}/restore`,cl,{method:"POST"}),detachParent:(e,t="local")=>b(`${k(t)}/sessions/${e}/detach-parent`,dl,{method:"POST"}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return b(`${k(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Ia)},saveApiKey:(e,t,i="local")=>b(`${k(i)}/auth/api-key`,Ot,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>b(`${k(t)}/auth/logout`,Ot,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>b(`${k(t)}/auth/oauth`,Lt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>b(`${k(t)}/auth/oauth/${encodeURIComponent(e)}`,Lt),respondOAuthFlow:(e,t,i,s="local")=>b(`${k(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Lt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>b(`${k(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Lt,{method:"POST"})},et={terminals:(e,t,i="local")=>b(`${k(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,W(Ci)),startTerminal:(e,t,i,s="local")=>b(`${k(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ci,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>b(`${k(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Vi,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>b(`${k(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Vi,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>b(`${k(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Ci,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>b(`${k(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,wt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>b(`${k(t)}/terminal-command-runs${bl(e)}`,W(wt)),getCommandRun:(e,t="local")=>vl(e,t),cancelCommandRun:(e,t="local")=>b(`${k(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,wt,{method:"POST"})};async function vl(e,t){const i=await fetch(`${k(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(wl(s)??i.statusText)}return wt(await i.json())}}function bl(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 wl(e){if(!yl(e))return;const t=e.error;return typeof t=="string"?t:void 0}function yl(e){return typeof e=="object"&&e!==null}const xl={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),b(`${k(i.machineId)}/files?${s.toString()}`,W(vo))}},Sl={gitStatus:(e,t,i="local")=>b(`${k(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,ja),gitDiff:(e,t,i,s="local")=>b(pl(s,e,t,i),Fa)},_={...wo,...fl,...Yt,...Ki,...yo,...gl,...Gi,...ml,...et,...xl,...Sl};function kl(e,t="local"){return new WebSocket(`${us()}${hs(t)}/sessions/${e}/events`)}function Am(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${us()}${hs(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function $l(e="local"){return new WebSocket(`${us()}${hs(e)}/events`)}function hs(e){return`/api/machines/${encodeURIComponent(e)}`}function us(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function qt(){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 Pl(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},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 fi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function xo(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const So="local";function Ii(e,t){return`${e}:${t}`}function ko(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??So}class Cl{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??yo}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Il(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),r=g(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=Tl(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Il(e){const t={};for(const i of e.workspaces)xo(i)&&(t[i.cwd]=i);return t}function Tl(e,t){const i={...e};return xo(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Ml{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??_,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Al(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 r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.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(r=>r.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(r){this.setState({error:String(r)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,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(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){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 r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!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??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",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.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function Al(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function Pt(e){return e.replaceAll(":",".")}function Rl(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function Ti(e,t){const i=Rl(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function pe(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));El(r,s)}function El(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 lr=Pt("core:workspace.files");class Dl{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()),r=await _.workspaceTree(t.id,i.id,"",s),o={...this.getState().expandedDirs};await Promise.all(Object.keys(o).map(async n=>{o[n]=(await _.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:r.entries,expandedDirs:o,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:Ll(this.getState().expandedDirs,t)});return}try{const r=await _.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),pe(lr,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const r=await _.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(_l(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),pe(lr,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function _l(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Ll(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const cr=Pt("core:workspace.git");class Ol{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 _.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),pe(cr,"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"}),pe(cr,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([_.gitDiff(i.id,s.id,{path:t},g(this.getState())),_.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Wl{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await _.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:jl(this.getState().machineActivities,r)}),this.refreshMachineHealthFor(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,...qt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await _.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 _.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:dr(this.getState().machineStatuses,t.id),machineActivities:dr(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await _.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const r=await this.safeRemoteHealth(s);if(r.ok)return s;const o=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${o?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r}}),o??s}async safeRemoteHealth(t){try{return await _.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(r=>_.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}}function dr(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function jl(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Nl{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 _.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}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 _.addProject(t.trim(),void 0,i,g(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await _.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 Ji="pi-web:cached-new-sessions:v1",Fl="browserCachedNew",rt="local";function Ct(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function pr(e,t=rt,i=Ct()){if(e.messageCount!==0||e.archived===!0)return;const s=fs(i).filter(r=>r.id!==e.id||r.machineId!==t);gs([Qi(e,t),...s],i)}function Qi(e,t=rt){return{...e,browserCachedNew:!0,machineId:t}}function hr(e,t=rt,i=Ct()){const s=fs(i).filter(r=>r.id!==e||r.machineId!==t);gs(s,i)}function Bl(e,t,i=rt,s=Ct()){const r=new Set(t.map(c=>c.id)),o=fs(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&gs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function $e(e){return e===void 0?!1:Hl(e)&&e.browserCachedNew===!0}function zl(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:rt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function fs(e=Ct()){try{const t=e?.getItem(Ji);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Ul(s)):[]}catch{return[]}}function gs(e,t=Ct()){try{e.length===0?t?.removeItem(Ji):t?.setItem(Ji,JSON.stringify(e))}catch{}}function Ul(e){if(!ql(e))return[];const t=Qe(e,"id"),i=Qe(e,"path"),s=Qe(e,"cwd"),r=Qe(e,"created"),o=Qe(e,"modified"),n=Qe(e,"firstMessage"),a=Vl(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=Mi(e,"name"),p=Mi(e,"parentSessionPath"),f=Mi(e,"machineId")??rt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:f,browserCachedNew:!0}]}function Hl(e){return Fl in e}function ql(e){return typeof e=="object"&&e!==null}function Qe(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Mi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Vl(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Kl(e){return lc(e.flatMap(ms)).filter(t=>t.parts.length>0)}function ve(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Wt(e,t){const i=ec(t);return i===void 0?e:{...e,meta:i}}function Gl(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,ve(t,i)]}function Jl(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 ms(e){if(Ql(e))return[e];if(D(e,"role")==="bashExecution")return[Wt(sc(e),e)];const t=rc(D(e,"role")),i=oc(ee(e,"content"),e),s=t==="user"?Zl(i):void 0;if(s!==void 0)return s.map(a=>Wt(a,e));const r=Yl(e);if(t==="tool")return[Wt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":t;return o.length>0?[Wt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[]}function Ql(e){const t=D(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ee(e,"parts"))}function Zl(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Xl(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 Xl(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 Yl(e){const t=D(e,"source");if(t==="compaction"||t==="branch_summary")return t}function ec(e){const t=tc(ee(e,"timestamp")),i=ic(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function tc(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 ic(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 sc(e){const t=D(e,"command")??"",i=Vt(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ee(e,"output");s!=null&&i.push("",ti(s));const r=ee(e,"exitCode");r!=null&&i.push("",`exit ${ti(r)}`),Vt(e,"cancelled")===!0&&i.push("","cancelled"),Vt(e,"truncated")===!0&&i.push("","output truncated");const o=D(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function rc(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function oc(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=D(i,"type"),r=D(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=D(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=D(i,"name")??"tool",n=ee(i,"arguments"),a=o==="read"?ac(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:o,summary:It(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:ur(i)}).map(i=>i.type==="text"&&D(t,"role")==="toolResult"?nc(i.text,t):i):ur(e)}function nc(e,t){const i=D(t,"toolCallId"),s=ee(t,"content"),r=ee(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:D(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:Vt(t,"isError")===!0}}function ac(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 lc(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=cc(a),p=t.length;t.push({role:"tool",parts:[c],...o}),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&&dc(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function cc(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 dc(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=ei(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function ei(e){const t=ee(e,"preview");if(!vs(t))return;const i=D(t,"diff"),s=D(t,"error"),r=hc(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function ur(e){return e==null?[]:typeof e=="object"?[{type:"text",text:It(e)}]:[{type:"text",text:ti(e)}]}function It(e){if(!vs(e))return ti(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(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${pc(n)}`).join(" · ")}function pc(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 ee(e,t){return vs(e)?e[t]:void 0}function D(e,t){const i=ee(e,t);return typeof i=="string"?i:void 0}function Vt(e,t){const i=ee(e,t);return typeof i=="boolean"?i:void 0}function hc(e,t){const i=ee(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function ti(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const uc="pi-web:prompt-draft:";function ii(e){return`${uc}${e}`}function gi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function $o(e,t=gi()){try{return t?.getItem(ii(e))??""}catch{return""}}function si(e,t,i=gi()){try{t?i?.setItem(ii(e),t):i?.removeItem(ii(e))}catch{}}function bs(e,t=gi()){try{t?.removeItem(ii(e))}catch{}}function fc(e,t,i=gi()){const s=$o(e,i);s!==""&&(si(t,s,i),bs(e,i))}function gc(e,t){return ve("bash",`${t===!0?`excluded from context
6
+
7
+ `:""}$ ${e}`)}function mc(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,ve("bash",t)];const r=bc(s.text)?"":`
8
+
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function vc(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
10
+
11
+ `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash command failed"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`full output: ${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
+
13
+ ${r.join(`
14
+ `)}`}]}]}function bc(e){const t=e.lastIndexOf(`
15
+
16
+ `),i=e.lastIndexOf("$ ");return t>i}function wc(e,t){if(t.type==="message.append")return Mc(e,t.message);if(t.type==="assistant.delta")return Gl(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Jl(e,t.text);if(t.type==="tool.start")return kc(e,t);if(t.type==="tool.update")return Co(e,t.toolCallId,i=>$c(i,t));if(t.type==="tool.end")return Po(e,t.toolCallId,t.toolName,It(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,gc(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return mc(e,t.chunk);if(t.type==="shell.end")return vc(e,t);if(t.type==="command.output")return[...e,ve(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,ve("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:yc(e,t.message)}function yc(e,t){const i=Pc(t);if(i!==void 0)return Po(e,i.toolCallId,i.toolName,It(i.content),i.text,i.isError,i.content,i.details);const s=ms(t)[0];if(s===void 0)return;const r=s.role==="assistant"?xc(s):s;if(r.parts.length===0)return e;const o=Cc(e,r);if(o>=0)return[...e.slice(0,o),r,...e.slice(o+1)];const n=e.at(-1);return n?.role!==r.role?[...e,r]:r.role==="assistant"||Tc(n,r)?[...e.slice(0,-1),r]:[...e,r]}function xc(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Sc(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 kc(e,t){const i=t.toolName==="read"?Sc(je(t.args,"path")):void 0;if(i!==void 0)return Ac(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||It(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function $c(e,t){const i=ei(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 Po(e,t,i,s,r,o,n,a){const c=Co(e,t,h=>{const u=ei(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...u===void 0?{}:{preview:u}}});if(c!==e)return c;const p=ei(a),f={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[f]}]}function Co(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Pc(e){if(je(e,"role")!=="toolResult")return;const t=je(e,"toolCallId"),i=oi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:je(e,"toolName")??"tool",text:Io(i),isError:Ec(e,"isError")===!0,content:i,details:oi(e,"details")}}function Io(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Io).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=je(e,"text")??je(e,"content")??je(e,"output");if(t!==void 0)return t}return""}function Cc(e,t){const i=ri(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r?.role!=="skill")continue;const o=ri(r);if(To(o,i))return s}return-1}function ri(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function To(e,t){return e.length===t.length&&e.every((i,s)=>Ic(i,t[s]))}function Ic(e,t){return t===void 0?!1:fr(e.path)===fr(t.path)||e.name===t.name}function fr(e){return e.replace(/\\/g,"/")}function Tc(e,t){return gr(e)===gr(t)}function gr(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
+
19
+ `)}function Mc(e,t){const i=ms(t);return i.length===0?e:[...e,...i]}function Ac(e,t){const i=e.at(-1);return t.role==="skill"&&To(ri(i),ri(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Rc(e){return typeof e=="object"&&e!==null}function oi(e,t){return Rc(e)?e[t]:void 0}function je(e,t){const i=oi(e,t);return typeof i=="string"?i:void 0}function Ec(e,t){const i=oi(e,t);return typeof i=="boolean"?i:void 0}const Dc="pi-web:chat-history:v2:",_c=1800*1e3;function Lc(e){try{const t=sessionStorage.getItem(Zi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Fc(i))return;if(Date.now()-i.savedAt>_c){sessionStorage.removeItem(Zi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Oc(e,t){try{sessionStorage.setItem(Zi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Wc(e,t){if(e===void 0||!Xi(e))return t;if(!Xi(t))return e;if(jc(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),r=new Array(s-i);return mr(r,i,e),mr(r,i,t),Nc(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function jc(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Nc(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function mr(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Zi(e){return`${Dc}${e}`}function Fc(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&Xi({messages:t,start:i,total:s})}function Xi(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(Bc)}function Bc(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 zc={read:Lc,write:Oc};class Uc{constructor(t=zc){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return vr(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Wc(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),vr(s)}applyLiveEvent(t,i){return wc(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 vr(e){const t=e?.start??0;return{messages:Kl(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function ws(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Mo(e).startsWith("/")?{kind:"command"}:qc(e)?{kind:"file"}:{kind:"normal"}}function Hc(e){return ws(e).kind==="shell"}function Mo(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
20
+ `))+1;return e.slice(t)}function qc(e){const t=Mo(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const r=e.slice(0,s);return r.endsWith("@")||r.endsWith("@ ")||r.endsWith("!@")}class Vc{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.sessionId=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Ro(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=kl(this.sessionId,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 Ao(t);Kc(i)&&this.onEvent?.(i)}}class br{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),Ro(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=$l(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 Ao(t);Jc(i)&&this.onEvent?.(i)}}function Kc(e){const t=ys(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 Gc(e){const t=ys(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function Jc(e){const t=ys(e);return Gc(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function ys(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Ao(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 Ro(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 Tt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class mi{constructor(t,i,s=Tt()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[r,o]of Qc(t,i,s))this.values.set(r,o)}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 xs(e){return typeof e=="string"&&e!==""?e:void 0}function Qc(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Zc(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Zc(e){return!Xc(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 Xc(e){return typeof e=="object"&&e!==null}class Yc{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 ed="pi-web:session-selection:v1";class td{constructor(t=Tt()){this.sessionIdsByCwd=new mi(ed,xs,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function id(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return rd(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function sd(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function rd(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function od(e,t,i){return Eo(e,[t],i)}function Eo(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function nd(e,t,i){return Do(e,t,[i])}function Do(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const dt=100;class ad{constructor(t,i,s,r=new Yc,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Vc,this.api=o.api??_,this.transcripts=o.transcripts??new Uc}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();sd(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);pr(s,i);const r=Qi(s,i);this.setState({sessions:[r,...this.getState().sessions]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return id(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 r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,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.id,{limit:dt},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const u=this.transcripts.mergeHistory(r,h);this.setState({...u,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:dt},g(this.getState())),this.api.status(t.id,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a),f=c.isStreaming;this.catchupStreamSessionId=f?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:f,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($e(t)&&hd(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.id,{before:t.messagePageStart,limit:dt},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(Hc(t))return this.runShell(t);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,t,i,g(this.getState())),this.markCachedNewSessionPersisted(r)}catch(o){this.setState({error:String(o)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ve("user",t)]});try{await this.api.shell(i.id,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("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,ve("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,g(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if($e(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,g(this.getState()));const i=this.getState(),s=od(i.sessions,t.id,new Date().toISOString()),r=nd(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||$e(t)))try{const i=await this.api.archiveWithDescendants(t.id,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Eo(r.sessions,s,new Date().toISOString()),n=Do(o,r.selectedSession?.id,s);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!$e(t))return;this.api.stop(t.id,g(this.getState())).catch(()=>{}),hr(t.id,g(this.getState())),bs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t.id,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.id,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.id,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.id,t,i,g(this.getState())))}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i.id,t,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.id,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.id,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.id,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.id,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,r]=await Promise.all([this.api.messages(t,{limit:dt},g(this.getState())),this.api.status(t,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return ko(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()),r=await this.api.startSession(t.cwd,s);pr(r,s),fc(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),hr(t.id,s);const o=Qi(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!$e(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(zl(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,ve(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&si(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!fi(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...cd(i,t.sessionId,t.messageCount),...s?{sessionActivities:ld(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=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(dd(t))return}if(pd(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:dt},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function ld(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function cd(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function dd(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 pd(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function hd(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class ud{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 fd="pi-web:workspace-selection:v1";class gd{constructor(t=Tt()){this.workspaceIdsByProject=new mi(fd,xs,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function md(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class vd{constructor(t,i,s,r,o=new ud,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??_}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...qt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Ii(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,...qt()});try{const r=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=md(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Ii(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Ii(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...qt()});try{const r=Bl(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:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.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),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=wd(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function bd(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function wd(e){return e.find(t=>t.isMain)??e[0]}const yd="pi-web:machine-navigation:v1";class xd{constructor(t=Tt()){this.snapshotsByMachine=new mi(yd,kd,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?xr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,xr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Sd(e){return{machineId:e,surface:{}}}function wr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??So,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 yr(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 xr(e){return{...e,surface:{...e.surface}}}function kd(e){if(!Lo(e))return;const t=ke(e,"machineId");if(t===void 0)return;const i=_o(ke(e,"tool")),s=Pd(ke(e,"view"));return{machineId:t,projectId:ke(e,"projectId"),workspaceId:ke(e,"workspaceId"),sessionId:ke(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:$d(e.surface)}}function $d(e){return Lo(e)?{selectedFilePath:ke(e,"selectedFilePath"),selectedDiffPath:ke(e,"selectedDiffPath"),selectedTerminalId:ke(e,"selectedTerminalId")}:{}}function Pd(e){return e==="navigation"||e==="chat"?e:_o(e)}function _o(e){return Cd(e)?e:void 0}function Cd(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function ke(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Lo(e){return typeof e=="object"&&e!==null}const Id="pi-web:terminal-selection:v1";class Td{constructor(t=Tt()){this.terminalIdsByCwd=new mi(Id,xs,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 Rm(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function Em(e){return e.find(t=>!t.exited)??e[0]}const Md=1200;class Ad{constructor(){this.pendingTokens=[]}handle(t,i){const s=Rd(t);if(s===void 0||!Sr(s))return!1;const r=i.filter(c=>c.shortcut!==void 0&&c.enabled!==!1).map(c=>({action:c,tokens:Wo(c.shortcut??"")})).filter(c=>c.tokens.length>0),o=this.pendingTokens.length>0&&!Sr(s)?[...this.pendingTokens,s]:[s],n=r.find(c=>Dd(c.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(c=>jo(c.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Md)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Oo(e){return Wo(e).map(t=>t.split("+").map(i=>i==="mod"?kr()?"⌘":"Ctrl":i==="shift"?"Shift":i==="alt"?kr()?"⌥":"Alt":i==="ctrl"?"Ctrl":i==="enter"?"Enter":i==="escape"?"Esc":i==="."?".":i.length===1?i.toUpperCase():`${i.charAt(0).toUpperCase()}${i.slice(1)}`).join("+")).join(" ")}function Rd(e){if(e.isComposing)return;const t=Ed(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 Wo(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t!=="").map(t=>t.split("+").filter(i=>i!=="").join("+"))}function Ed(e){if(e===" ")return"space";if(e.length===1)return e.toLowerCase();const t=e.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(t))return t}function Dd(e,t){return e.length===t.length&&jo(e,t)}function jo(e,t){return t.every((i,s)=>e[s]===i)}function Sr(e){return e.includes("+")}function kr(){return navigator.userAgent.toLowerCase().includes("mac")}const Ss="themes:classic",_d="themes:pi-web-dark",Ld={themeId:_d,auto:!0},No="pi-web-app-theme",Od=["--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"],Wd=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function jd(){try{const e=window.localStorage.getItem(No);return e===null?void 0:Ud(e)}catch{return}}function Nd(e){try{window.localStorage.setItem(No,JSON.stringify(e))}catch{}}function Fd(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Od){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Bd(e){const t=zd(e.themes,e.fallbackThemeId??Ss),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=Fo(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function zd(e,t=Ss){return e.find(i=>i.id===t)??e[0]}function Fo(e,t){return e.find(i=>i.light===t||i.dark===t)}function Ud(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Hd(i)?i:void 0}catch{return}}function Hd(e){if(!qd(e))return!1;const t=e.themeId,i=e.auto;return Vd(t)&&typeof i=="boolean"}function qd(e){return typeof e=="object"&&e!==null}function Vd(e){return typeof e=="string"&&Wd.test(e)}const Kd="workspace.delete",Gd="pi.operation",Jd="target.workspaceId";function Qd(e){return{...e===void 0?{}:{projectId:e},metadata:{[Gd]:Kd}}}function Zd(e){const t={};for(const i of e){const s=Yi(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function Xd(e){return Object.entries(e).filter(([,t])=>ni(t)).map(([t])=>t)}function Bo(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&ni(i)}function Yi(e){return e.metadata[Jd]}function ni(e){return e.status==="queued"||e.status==="running"}function Yd(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",group:"General",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"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.refresh-data",title:"Refresh App Data",description:"Refresh session, status, activity, and the current workspace surface without reloading the page",group:"General",run:e=>e.refreshAppData()},{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.selectMainView("chat")}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:pt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:$r,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:pt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:pt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:$r,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:pt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:ep,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:pt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:tp,run:e=>e.archiveSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:ip,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&fi(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function pt(e){return e.state.selectedWorkspace!==void 0}function $r(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ep(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Bo(e.state,t)}function tp(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!$e(t)}function ip(e){return $e(e.state.selectedSession)}const sp="modulepreload",rp=function(e){return"/"+e},Pr={},zo=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(f=>Promise.resolve(f).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");r=c(i.map(p=>{if(p=rp(p),p in Pr)return;Pr[p]=!0;const f=p.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const u=document.createElement("link");if(u.rel=f?"stylesheet":sp,f||(u.as="script"),u.crossOrigin="",u.href=p,a&&u.setAttribute("nonce",a),document.head.appendChild(u),f)return new Promise((v,S)=>{u.addEventListener("load",v),u.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})},op=10*1024*1024,np="10 MB";function ap(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Kt(e)}function Kt(e){switch(e){case"navigation":return Ye`
21
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
22
+ <circle cx="6" cy="7" r="1.5"></circle>
23
+ <path d="M10 7h8"></path>
24
+ <circle cx="6" cy="12" r="1.5"></circle>
25
+ <path d="M10 12h8"></path>
26
+ <circle cx="6" cy="17" r="1.5"></circle>
27
+ <path d="M10 17h8"></path>
28
+ </svg>
29
+ `;case"chat":return Ye`
30
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
31
+ <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>
32
+ <path d="M8 9h8"></path>
33
+ <path d="M8 13h5"></path>
34
+ </svg>
35
+ `;case"files":return Ye`
36
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
37
+ <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>
38
+ </svg>
39
+ `;case"git":return Ye`
40
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
41
+ <circle cx="6" cy="6" r="2"></circle>
42
+ <circle cx="18" cy="6" r="2"></circle>
43
+ <circle cx="12" cy="18" r="2"></circle>
44
+ <path d="M8 6h6"></path>
45
+ <path d="M6 8v2a6 6 0 0 0 6 6"></path>
46
+ <path d="M18 8v2a6 6 0 0 1-6 6"></path>
47
+ </svg>
48
+ `;case"terminal":return Ye`
49
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
50
+ <rect x="3" y="5" width="18" height="14" rx="2"></rect>
51
+ <path d="m7 10 3 3-3 3"></path>
52
+ <path d="M12 16h5"></path>
53
+ </svg>
54
+ `}}function lp(){return[{id:"workspace.files",title:"Files",icon:Kt("files"),order:10,render:cp},{id:"workspace.git",title:"Git",icon:Kt("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:fp},{id:"workspace.terminal",title:"Terminal",icon:Kt("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:up}]}function cp(e){return l`
55
+ <section class="toolbar">
56
+ <strong>Files</strong>
57
+ ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
58
+ <button @click=${e.onRefreshFiles}>Refresh</button>
59
+ </section>
60
+ <section class="split">
61
+ <div class="list tree">
62
+ ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Uo(e,t,0))}
63
+ </div>
64
+ <div class="viewer">
65
+ ${pp(e)}
66
+ </div>
67
+ </section>
68
+ `}function Uo(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
69
+ <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{dp(e,t)}}>
70
+ <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
71
+ <span>${t.name}</span>
72
+ </button>
73
+ ${r?s.map(n=>Uo(e,n,i+1)):null}
74
+ `}function dp(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function pp(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"?hp(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${es(t.size)}</p>`:(Ho(),l`
75
+ <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
76
+ <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
77
+ `)}function hp(e,t){const i=`${t.mimeType??"image"} · ${es(t.size)}`;if(t.size>op)return l`
78
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
79
+ <p class="muted">Image too large to preview: ${es(t.size)} · limit ${np}</p>
80
+ `;const s=ul(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
81
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
82
+ <div class="image-preview">
83
+ <img src=${s} alt=${t.path} decoding="async" />
84
+ </div>
85
+ `}function up(e){return vp(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function fp(e){const t=e.gitStatus;return l`
86
+ <section class="toolbar">
87
+ <strong>Git</strong>
88
+ ${e.gitStale?l`<span class="stale">stale</span>`:null}
89
+ <button @click=${e.onRefreshGit}>Refresh</button>
90
+ </section>
91
+ <section class="split">
92
+ <div class="list">
93
+ ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
94
+ <p class="summary">${bp(t)}</p>
95
+ ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
96
+ <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
97
+ <span>${wp(i.index,i.workingTree)}</span>
98
+ <span>${i.path}</span>
99
+ </button>
100
+ `)}
101
+ `:l`<p class="muted">Not a git repository.</p>`}
102
+ </div>
103
+ <div class="viewer">
104
+ ${gp(e)}
105
+ </div>
106
+ </section>
107
+ `}function gp(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(r=>r.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
108
+ <div class=${s.length===1?"diffs single":"diffs"}>
109
+ ${s.map(r=>mp(r))}
110
+ </div>
111
+ `}function mp(e){return Ho(),l`
112
+ <section class="diff-section">
113
+ <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
114
+ <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
115
+ </section>
116
+ `}function Ho(){zo(()=>import("./CodeViewer-BcQUZop_.js"),__vite__mapDeps([0,1,2,3]))}function vp(){zo(()=>import("./TerminalPanel-1o4j3QP_.js"),__vite__mapDeps([4,5,6,1,2]))}function bp(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 wp(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function es(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`${Ai(t)} KB`;const i=t/1024;return i<1024?`${Ai(i)} MB`:`${Ai(i/1024)} GB`}function Ai(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const yp={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Yd(),workspacePanels:lp()}})},xp={"--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"},Sp={"--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"},kp={"--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"},$p={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:Sp},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:kp},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:xp}],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"}]}})},Pp=/^[a-z][a-z0-9.-]*$/u;function Cp(e){return Pp.test(e)}const Ip="machine.";function Tp(e,t){if(e==="")throw new Error("Machine id is required");if(!Cp(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Ip}${Mp(e)}.${t}`}function Mp(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Cr(e="/pi-web-plugins/manifest.json",t={}){const i=await Ap(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=Ep(n,o);s.push({id:t.machineId===void 0?r.id:Tp(t.machineId,r.id),plugin:a,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function Ap(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 Rp(await t.json())}}function Rp(e){if(!ai(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ai(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module}})}}function Ep(e,t){if(!ai(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Dp(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Dp(e){return ai(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ai(e){return typeof e=="object"&&e!==null}const _p=/^[a-z][a-z0-9.-]*$/u,Lp=/^[a-z][a-z0-9.-]*$/u,qo=new WeakMap,Vo=new WeakMap;class Op{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(Fp(t,this.gatewayPluginIds))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:Ye}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a));this.gatewayPluginIds.add(i)}}getActions(t){return this.actions.filter(i=>ht(i.machineId,zp(t),i.sourcePluginId,this.gatewayPluginIds)).map(i=>{const s=Wp(t,i.pluginId),r=i.enabled?.(s),o={id:i.id,pluginId:i.pluginId,localId:i.localId,...i.machineId===void 0?{}:{machineId:i.machineId},title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(o.description=i.description),i.shortcut!==void 0&&(o.shortcut=i.shortcut),i.group!==void 0&&(o.group=i.group),r!==void 0&&(o.enabled=r),o})}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,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>ht(s,c.machine.id,r,this.gatewayPluginIds)&&(a?.(Ri(c,t))??!0),...n===void 0?{}:{badge:c=>ht(s,c.machine.id,r,this.gatewayPluginIds)?n(Ri(c,t)):void 0},render:c=>i.render(Ri(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>ht(s,c.machine.id,r,this.gatewayPluginIds)&&(n?.(c)??!0),items:c=>ht(s,c.machine.id,r,this.gatewayPluginIds)?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}`}validatePluginId(t){if(!_p.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Lp.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function Wp(e,t){return qo.get(e)?.(t)??e}function Ri(e,t){return Vo.get(e)?.(t)??e}function jp(e,t){return qo.set(e,t),e}function Np(e,t){return Vo.set(e,t),e}function Fp(e,t){return e.machineId!==void 0&&e.sourcePluginId!==void 0&&t.has(e.sourcePluginId)}function ht(e,t,i,s){return e===void 0||e===t&&!Bp(i,s)}function Bp(e,t){return e!==void 0&&t.has(e)}function zp(e){return e.state.selectedMachine?.id??"local"}const Up=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Hp(){return typeof window>"u"||!("matchMedia"in window)?[]:Up.map(e=>window.matchMedia(e))}function Ir(e,t=qp()){return e.some(i=>i.matches)||Vp(t)}function qp(){return typeof navigator>"u"?void 0:navigator}function Vp(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Kp=250;class Gp{constructor(t=Jp()){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()},Kp)}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 Jp(){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 Qp="(max-width: 760px)";class Zp{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Ir(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Xp(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Hp(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Gp,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Ir(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 Xp(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Qp)}function Yp(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function ks(e,t){if(e!=="none")return e??Yp(t)}function eh(e,t){return t.isMobileLayout&&ks(t.expanded,t.state)!==e}function th(e,t,i){return i.isMobileLayout?ks(e,i.state)===t?"none":t:e}function ih(e,t,i){return i?t:e}class sh{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,t.addController(this)}hostConnected(){}expandedSection(){return ks(this.expanded,this.getState())}isCollapsed(t){return eh(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState()})}toggle(t){this.setExpanded(th(this.expanded,t,{isMobileLayout:this.isMobileLayout(),state:this.getState()}))}expand(t){this.setExpanded(ih(this.expanded,t,this.isMobileLayout()))}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}}class rh{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()}shellClass(t){return["shell",Ko(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Ko(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}function Tr(){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:oh(e.get("tool")),view:nh(e.get("view"))}}function Ei(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function oh(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Go(e)?e:void 0}function nh(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Go(e)?e:void 0}function Go(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Mr(){return ah(new URLSearchParams(window.location.search).get("settings"))}function Di(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function ah(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function lh(e,t){return t===void 0?e:e.map(i=>ch(i,t))}function ch(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?dh(e):{...e,shortcut:i}}function dh(e){const t={...e};return delete t.shortcut,t}function ph(e,t){const i=t.api??et,s=t.pollIntervalMs??1e3,r=t.setTimeout??uh(),o=t.clearTimeout??fh();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:hh(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function hh(e,t,i,s,r){return Ar(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=u=>{c||(c=!0,a!==void 0&&r(a),o(u))},f=u=>{c||(c=!0,a!==void 0&&r(a),n(u instanceof Error?u:new Error(String(u))))},h=()=>{t.getCommandRun(e.id).then(u=>{if(u!==void 0&&Ar(u)){p(u);return}a=s(h,i)}).catch(f)};a=s(h,i)})}function Ar(e){return e.status==="succeeded"||e.status==="failed"}function uh(){return(e,t)=>globalThis.setTimeout(e,t)}function fh(){return e=>{globalThis.clearTimeout(e)}}function gh(e,t){return t[e.path]}function mh(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function vh(e,t,i){return Qo(bh(e,t,i))}function Jo(e){return Qo(Object.values(e??{}))}function Qo(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function bh(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}const jt=0,wh=120;function Mt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Zo():yh(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),f=Math.min(i.right,a),h=p-i.bottom-jt,u=i.top-c-jt;return[...h<wh&&u>h?[`bottom: ${Ze(o-i.top+jt)};`,`max-height: ${Ze(Math.max(0,u))};`]:[`top: ${Ze(i.bottom+jt)};`,`max-height: ${Ze(Math.max(0,h))};`],`right: ${Ze(Math.max(0,r-f))};`,`max-width: ${Ze(Math.max(0,f-n))};`].join(" ")}function yh(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Zo()}function Zo(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Ze(e){return`${String(Math.round(e))}px`}function At(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}const xh=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Xo(e){return e.composedPath().some(t=>Sh(t,xh))}function Sh(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 vi(e,t){Xo(e)||t()}function bi(e,t){e.key!=="Enter"&&e.key!==" "||Xo(e)||(e.preventDefault(),t())}const kh=E`
117
+ /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
118
+ :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; }
119
+ :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
120
+ @media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
121
+ :host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
122
+ }
123
+ .shell { --navigation-panel-width: 340px; --workspace-panel-width: minmax(360px, 42vw); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(420px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
124
+ aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
125
+ aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
126
+ 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); }
127
+ .header-actions { display: flex; align-items: center; gap: 8px; }
128
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
129
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
130
+ main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
131
+ .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: none; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
132
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
133
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
134
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
135
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
136
+ .context-bar-label { display: none; }
137
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
138
+ .context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
139
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
140
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; padding: 0 8px 0 0; pointer-events: none; }
141
+ .context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
142
+ .app-refresh { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
143
+ .app-refresh, .app-refresh * { -webkit-user-select: none; user-select: none; }
144
+ .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 999px; padding: 0; line-height: 1; touch-action: manipulation; -webkit-touch-callout: none; }
145
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
146
+ .app-refresh-button.refreshing .app-refresh-icon { animation: app-refresh-spin .8s linear infinite; }
147
+ .app-refresh-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(170px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
148
+ .app-refresh-menu button { display: block; width: 100%; border: 0; background: transparent; color: var(--pi-text); text-align: left; white-space: normal; overflow-wrap: anywhere; }
149
+ .app-refresh-menu button:hover, .app-refresh-menu button:focus { background: var(--pi-selection-bg); }
150
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
151
+ .context-chip:hover { background: var(--pi-surface-hover); }
152
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
153
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
154
+ .context-kind { display: none; }
155
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
156
+ app-mobile-main-tabs { display: none; }
157
+ .mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
158
+ .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; }
159
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
160
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
161
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
162
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
163
+ .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
164
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
165
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
166
+ .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
167
+ .navigation-panel-edge, .workspace-panel-edge { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
168
+ .navigation-panel-edge { grid-column: 2; }
169
+ .workspace-panel-edge { grid-column: 4; }
170
+ .navigation-panel-edge-button, .workspace-panel-edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
171
+ .navigation-panel-edge-button:hover, .navigation-panel-edge-button:focus-visible, .workspace-panel-edge-button:hover, .workspace-panel-edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
172
+ .shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
173
+ .shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
174
+ .navigation-panel-edge-icon, .workspace-panel-edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
175
+ workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
176
+ @media (min-width: 1181px) {
177
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
178
+ .shell.navigation-panel-collapsed > aside { display: none; }
179
+ .shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
180
+ .shell.workspace-panel-collapsed > workspace-panel { display: none; }
181
+ }
182
+ @media (max-width: 1180px) {
183
+ .shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
184
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
185
+ .shell.navigation-panel-collapsed > aside { display: none; }
186
+ aside { grid-row: 1 / 3; }
187
+ .navigation-panel-edge { grid-row: 1 / 3; }
188
+ main { grid-column: 3; grid-row: 1 / 3; }
189
+ app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
190
+ .mobile-tabs-frame { display: flex; }
191
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
192
+ .shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
193
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
194
+ .workspace-panel-edge { display: none; }
195
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
196
+ main.workspace-view .empty { display: none; }
197
+ main.workspace-view { overflow: hidden; }
198
+ }
199
+ @media (max-width: 760px) {
200
+ .shell { grid-template-columns: minmax(0, 1fr); }
201
+ aside, .navigation-panel-edge { display: none; }
202
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
203
+ .context-bar { display: flex; }
204
+ .mobile-navigation-tab { display: block; }
205
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
206
+ main.navigation-view .empty { display: none; }
207
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
208
+ main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
209
+ main.navigation-view .mobile-navigation-panel project-list,
210
+ main.navigation-view .mobile-navigation-panel workspace-list,
211
+ main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
212
+ main.navigation-view .mobile-navigation-panel project-list[collapsed],
213
+ main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
214
+ main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
215
+ }
216
+ status-bar { flex: 0 0 auto; }
217
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
218
+ prompt-editor, chat-composer { flex: 0 0 auto; }
219
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
220
+ .empty { margin: auto; color: var(--pi-muted); }
221
+ .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
222
+ @keyframes app-refresh-spin { to { transform: rotate(360deg); } }
223
+ `,$h=E`
224
+ :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; }
225
+ header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
226
+ .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
227
+ .workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
228
+ .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
229
+ .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
230
+ .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
231
+ .workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
232
+ .tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
233
+ .tabs button { flex: 0 0 auto; white-space: nowrap; }
234
+ .tabs button.icon-tab { min-width: 34px; }
235
+ button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
236
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
237
+ .tab-icon { flex: 0 0 auto; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
238
+ .tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
239
+ .tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
240
+ .tab-label { min-width: 0; }
241
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
242
+ @container (max-width: 430px) {
243
+ .tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
244
+ .tabs button.icon-tab .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; }
245
+ }
246
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
247
+ .empty-state { box-sizing: border-box; width: min(100%, 380px); margin: auto; padding: 24px; display: grid; gap: 8px; color: var(--pi-muted); text-align: center; }
248
+ .empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
249
+ .empty-state p { margin: 0; line-height: 1.45; }
250
+ small, .muted { color: var(--pi-muted); }
251
+ header small { flex: 0 0 auto; min-width: max-content; overflow: visible; text-overflow: clip; white-space: nowrap; }
252
+ header .workspace-label { width: max-content; max-width: none; overflow: visible; }
253
+ header .workspace-label-base, header .workspace-label-item, header .workspace-label-render { overflow: visible; text-overflow: clip; }
254
+ @media (max-width: 1180px) { .tabs { display: none; } }
255
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
256
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
257
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
258
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
259
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
260
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
261
+ .toolbar button { margin-left: auto; }
262
+ .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
263
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
264
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
265
+ .row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
266
+ .row:hover, .row.selected { background: var(--pi-selection-bg); }
267
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
268
+ .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
269
+ .viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
270
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
271
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
272
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
273
+ .diff-section:last-child { border-bottom: 0; }
274
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
275
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
276
+ code-viewer { flex: 1 1 auto; min-height: 0; }
277
+ .image-preview { flex: 1 1 auto; min-height: 0; box-sizing: border-box; display: flex; align-items: center; justify-content: center; overflow: auto; padding: 16px; }
278
+ .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); }
279
+ 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; }
280
+ p { margin: 10px; }
281
+ `,wi=E`
282
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
283
+ :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
284
+ section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
285
+ h2 { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
286
+ .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
287
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
288
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
289
+ .subheading { margin-top: 14px; }
290
+ .section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-align: left; text-transform: inherit; }
291
+ .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
292
+ .section-title { display: grid; gap: 2px; min-width: 0; }
293
+ .section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
294
+ .section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
295
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
296
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
297
+ .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
298
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
299
+ .action-row.archived .action-main { color: var(--pi-muted); }
300
+ .action-main { box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
301
+ .action-name { display: -webkit-box; max-height: 2.5em; overflow: hidden; overflow-wrap: anywhere; line-height: 1.25; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
302
+ .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
303
+ .workspace-row .action-main { border-radius: 8px 0 0 8px; }
304
+ .workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
305
+ .workspace-primary .activity-indicator { flex: 0 0 auto; margin-right: 0; }
306
+ .workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
307
+ .workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
308
+ .workspace-secondary { margin-top: 3px; }
309
+ .workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
310
+ .workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
311
+ .workspace-menu-actions button.danger { color: var(--pi-danger); }
312
+ .workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
313
+ .workspace-menu-details { display: grid; gap: 6px; margin: 0; }
314
+ .workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
315
+ .workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
316
+ .workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
317
+ .tree-marker { color: var(--pi-dim); margin-right: 5px; }
318
+ .badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
319
+ .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; }
320
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
321
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
322
+ .action-menu { position: relative; align-self: stretch; }
323
+ .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; }
324
+ .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
325
+ .action-menu-panel { position: fixed; z-index: 50; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
326
+ .action-menu-panel button { display: block; width: 100%; text-align: left; white-space: normal; overflow-wrap: anywhere; border: 0; background: transparent; color: var(--pi-text); }
327
+ .action-menu-panel button:hover { background: var(--pi-selection-bg); }
328
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
329
+ button:disabled { opacity: .5; cursor: not-allowed; }
330
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
331
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
332
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
333
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
334
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
335
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
336
+ .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
337
+ .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; }
338
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
339
+ `,Ph=E`
340
+ :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; }
341
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
342
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
343
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
344
+ .activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
345
+ .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
346
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
347
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
348
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
349
+ .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; }
350
+ .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
351
+ .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
352
+ .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
353
+ .msg.system { color: var(--pi-danger); }
354
+ .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
355
+ .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
356
+ .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
357
+ .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
358
+ .msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
359
+ .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
360
+ .msg.event-group > summary .label { margin: 0; }
361
+ .group-body { padding: 0 12px 12px; }
362
+ .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; }
363
+ .group-msg.tool { color: var(--pi-warning); }
364
+ .group-msg.tool-execution-shell { color: var(--pi-text); }
365
+ .group-msg.system { color: var(--pi-danger); }
366
+ .group-msg.bash { color: var(--pi-success); }
367
+ .history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
368
+ .history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
369
+ .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
370
+ .history-load-button:disabled { cursor: default; opacity: .55; }
371
+ .queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
372
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
373
+ .queued-header strong { color: var(--pi-warning); }
374
+ .queued-header small { color: var(--pi-muted); }
375
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
376
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
377
+ .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
378
+ .session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
379
+ .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
380
+ .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
381
+ .session-activity strong { color: var(--pi-purple); }
382
+ .session-activity.receiving strong { color: var(--pi-success); }
383
+ .session-activity span, .session-activity small { color: var(--pi-muted); }
384
+ .history-boundary small { color: var(--pi-dim); }
385
+ .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
386
+ .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); }
387
+ .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
388
+ .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
389
+ .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
390
+ .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
391
+ .group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
392
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
393
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
394
+ .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
395
+ .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
396
+ .msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
397
+ .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
398
+ .msg-header .label { margin: 0; }
399
+ .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
400
+ .msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
401
+ .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
402
+ @media (hover: none) {
403
+ .msg-actions { opacity: 1; }
404
+ .msg-meta { opacity: .75; max-width: 26px; }
405
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
406
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
407
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
408
+ }
409
+ formatted-text.part { display: block; }
410
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
411
+ .part + .part { margin-top: 10px; }
412
+ .tool-line { color: var(--pi-warning); }
413
+ .summary { color: var(--pi-muted); margin-left: 6px; }
414
+ .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
415
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
416
+ .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
417
+ .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
418
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
419
+ summary { cursor: pointer; color: var(--pi-muted); }
420
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
421
+ .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
422
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
423
+ `,Ch=E`
424
+ :host { display: block; }
425
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
426
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
427
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
428
+ ul, ol { padding-left: 22px; }
429
+ li + li { margin-top: 3px; }
430
+ code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
431
+ .code-block-wrapper { position: relative; }
432
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
433
+ pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
434
+ pre code { border: 0; padding: 0; background: transparent; }
435
+ .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
436
+ .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
437
+ blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
438
+ a { color: var(--pi-accent); }
439
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
440
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
441
+ h1 { font-size: 20px; }
442
+ h2 { font-size: 17px; }
443
+ h3 { font-size: 15px; }
444
+ h4 { font-size: 14px; }
445
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
446
+ th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
447
+ th { background: var(--pi-surface); }
448
+ `,Ih=E`
449
+ :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
450
+ .bar { display: flex; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
451
+ span { overflow: hidden; text-overflow: ellipsis; }
452
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
453
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
454
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
455
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
456
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
457
+ .bar > span:first-child { flex: 1 1 auto; min-width: 80px; }
458
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
459
+ .activity.active { color: var(--pi-success); }
460
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
461
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
462
+ .muted { color: var(--pi-dim); }
463
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
464
+ `,Th=E`
465
+ :host { display: block; }
466
+ .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); }
467
+ 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; }
468
+ button:last-child { border-bottom: 0; }
469
+ button.selected, button:hover { background: var(--pi-selection-bg); }
470
+ span { color: var(--pi-muted); font-size: 12px; }
471
+ small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
472
+ `,Yo=E`
473
+ :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
474
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
475
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
476
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
477
+ .options { min-height: 0; overflow: auto; outline: none; }
478
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
479
+ header button { font-size: 20px; color: var(--pi-muted); }
480
+ input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
481
+ input:focus { border-color: var(--pi-accent); }
482
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
483
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
484
+ small { display: block; margin-top: 4px; color: var(--pi-muted); }
485
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
486
+ `,Mh=E`
487
+ :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
488
+ .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; }
489
+ 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; }
490
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
491
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
492
+ input::placeholder { color: var(--pi-dim); }
493
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
494
+ header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
495
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; }
496
+ .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
497
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
498
+ .main { min-width: 0; }
499
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
500
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
501
+ .group { grid-column: 1 / -1; font-size: 12px; }
502
+ 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; }
503
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
504
+ `,Ah=E`
505
+ :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
506
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
507
+ footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
508
+ .editor-wrap { position: relative; min-width: 0; }
509
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
510
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
511
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
512
+ .select-model { max-width: min(42vw, 320px); }
513
+ .select-thinking { max-width: 110px; }
514
+ 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; }
515
+ textarea { overflow-y: auto; padding: 8px; }
516
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
517
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
518
+ .markdown-editor .cm-line { padding: 0; }
519
+ .markdown-editor .cm-placeholder { color: var(--pi-dim); }
520
+ .markdown-editor .cm-focused { outline: none; }
521
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
522
+ .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
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
524
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
525
+ @media (max-width: 640px) {
526
+ footer { gap: 8px; padding: 8px; }
527
+ .actions { gap: 6px; }
528
+ .compact-status { flex: 1 1 220px; gap: 4px; }
529
+ .select-model { max-width: min(58vw, 260px); }
530
+ button { padding: 6px 8px; }
531
+ }
532
+ @media (max-width: 430px) {
533
+ .compact-status { flex-basis: 170px; font-size: 11px; }
534
+ .select-model { max-width: 48vw; }
535
+ .select-thinking { max-width: 70px; }
536
+ button { padding: 5px 7px; }
537
+ }
538
+ `;var Rh=Object.defineProperty,Eh=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Eh(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Rh(t,i,r),r};let V=class extends T{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)}render(){return l`
539
+ <section>
540
+ <h2>${this.renderHeading()}</h2>
541
+ ${this.collapsed?null:l`
542
+ <div class="list-body">
543
+ ${this.machines.map(e=>this.renderMachine(e))}
544
+ </div>
545
+ `}
546
+ </section>
547
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=Dh(e)&&this.onRemove!==void 0;return l`
548
+ <div
549
+ class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
550
+ tabindex="0"
551
+ title=${e.baseUrl??e.name}
552
+ @click=${r=>{vi(r,()=>this.onSelect?.(e))}}
553
+ @keydown=${r=>{this.handleMachineKeydown(r,e)}}
554
+ >
555
+ <div class="action-main">
556
+ <span class="action-name machine-primary">${this.renderActivity(e)}<span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${i}</small>
557
+ </div>
558
+ ${s?this.renderMachineMenu(e):null}
559
+ </div>
560
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Jo(this.activities[e.id]);return At(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=_h(e.id);return l`
561
+ <div class="action-menu">
562
+ <button
563
+ class="action-menu-toggle"
564
+ title="Machine actions"
565
+ aria-label=${`Actions for ${e.name}`}
566
+ aria-expanded=${String(t)}
567
+ aria-controls=${i}
568
+ @click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
569
+ >⋯</button>
570
+ ${t?l`
571
+ <div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
572
+ <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
573
+ </div>
574
+ `:null}
575
+ </div>
576
+ `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Mt(t),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}bi(e,()=>this.onSelect?.(t))}};V.styles=[wi,E`
577
+ .machine-row.no-actions .action-main { border-radius: 8px; }
578
+ .machine-primary { display: flex; align-items: baseline; gap: 6px; }
579
+ .machine-primary .activity-indicator { flex: 0 0 auto; margin-right: 0; }
580
+ .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
581
+ .machine-menu-panel button.danger { color: var(--pi-danger); }
582
+ .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
583
+ `];oe([d({attribute:!1})],V.prototype,"machines",2);oe([d({attribute:!1})],V.prototype,"selected",2);oe([d({attribute:!1})],V.prototype,"statuses",2);oe([d({attribute:!1})],V.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);oe([d({attribute:!1})],V.prototype,"onSelect",2);oe([d({attribute:!1})],V.prototype,"onRemove",2);oe([d({attribute:!1})],V.prototype,"onToggleCollapsed",2);oe([x()],V.prototype,"openMenuMachineId",2);oe([x()],V.prototype,"menuStyle",2);V=oe([A("machine-list")],V);function Dh(e){return e.kind==="remote"}function _h(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Lh=Object.defineProperty,Oh=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?Oh(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Lh(t,i,r),r};let K=class extends T{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)}render(){return l`
584
+ <section>
585
+ <h2>${this.renderHeading()}</h2>
586
+ ${this.collapsed?null:l`
587
+ <div class="list-body">
588
+ ${this.projects.map(e=>l`
589
+ <div
590
+ class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
591
+ tabindex="0"
592
+ title=${e.path}
593
+ @click=${t=>{vi(t,()=>this.onSelect?.(e))}}
594
+ @keydown=${t=>{bi(t,()=>this.onSelect?.(e))}}
595
+ >
596
+ <div class="action-main">
597
+ <span class="action-name">${e.name}</span><small>${this.renderActivity(e)}${e.path}</small>
598
+ </div>
599
+ <div class="action-menu">
600
+ <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${e.name}`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
601
+ ${this.openMenuProjectId===e.id?l`
602
+ <div class="action-menu-panel" style=${this.menuStyle}>
603
+ <button title="Close project" @click=${()=>{this.close(e)}}>Close</button>
604
+ </div>
605
+ `:null}
606
+ </div>
607
+ </div>
608
+ `)}
609
+ </div>
610
+ `}
611
+ </section>
612
+ `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=vh(e,this.workspacesByProjectId[e.id]??[],this.activities);return At(t,t==="terminal"?"Project terminal active":"Project active")??""}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Mt(t),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
613
+
614
+ This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};K.styles=wi;ne([d({attribute:!1})],K.prototype,"projects",2);ne([d({attribute:!1})],K.prototype,"selected",2);ne([d({attribute:!1})],K.prototype,"activities",2);ne([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ne([d({attribute:!1})],K.prototype,"onSelect",2);ne([d({attribute:!1})],K.prototype,"onClose",2);ne([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);ne([x()],K.prototype,"openMenuProjectId",2);ne([x()],K.prototype,"menuStyle",2);K=ne([A("project-list")],K);function en(e,t=[],i){return l`
615
+ <span class="workspace-label">
616
+ <span class="workspace-label-base" title=${i??e}>${e}</span>
617
+ ${Wh(t)}
618
+ </span>
619
+ `}function Wh(e=[]){return e.map(t=>l`<span class="workspace-label-separator">·</span>${tn(t)}`)}function Rr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${tn(t)}`)}function tn(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&jh(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 jh(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Nh=Object.defineProperty,Fh=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var r=s>1?void 0:s?Fh(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Nh(t,i,r),r};let q=class extends T{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()}render(){return l`
620
+ <section>
621
+ <h2>${this.renderHeading()}</h2>
622
+ ${this.collapsed?null:l`
623
+ <div class="list-body">
624
+ ${this.workspaces.map(e=>{const t=Bh(e),i=this.workspaceLabelItems(e);return l`
625
+ <div
626
+ class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
627
+ tabindex="0"
628
+ title=${t}
629
+ @click=${s=>{vi(s,()=>this.onSelect?.(e))}}
630
+ @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
631
+ >
632
+ <div class="action-main">
633
+ ${this.renderWorkspaceMain(t,i,e)}
634
+ </div>
635
+ ${this.renderWorkspaceMenu(t,i,e)}
636
+ </div>
637
+ `})}
638
+ </div>
639
+ `}
640
+ </section>
641
+ `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=mh(gh(e,this.activities));return At(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
642
+ <span class="workspace-primary">
643
+ ${this.renderActivity(i)}
644
+ <span class="workspace-primary-label">${e}</span>
645
+ ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
646
+ </span>
647
+ ${t.length===0?null:l`
648
+ <small class="workspace-secondary">
649
+ <span class="workspace-label">${Rr(t)}</span>
650
+ </small>
651
+ `}
652
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=Uh(i.id);return l`
653
+ <div class="action-menu">
654
+ <button
655
+ class="action-menu-toggle"
656
+ title="Workspace actions and details"
657
+ aria-label=${`Actions and details for ${e}`}
658
+ aria-expanded=${String(s)}
659
+ aria-controls=${r}
660
+ @click=${o=>{o.stopPropagation(),this.toggleMenu(i.id,o.currentTarget)}}
661
+ >⋯</button>
662
+ ${s?l`
663
+ <div class="action-menu-panel workspace-menu-panel" id=${r} style=${this.menuStyle} @click=${o=>{o.stopPropagation()}}>
664
+ ${this.renderWorkspaceActions(i)}
665
+ ${this.renderWorkspaceDetails(e,t,i)}
666
+ </div>
667
+ `:null}
668
+ </div>
669
+ `}renderWorkspaceActions(e){if(!zh(e))return;const t=this.isDeleting(e);return l`
670
+ <div class="workspace-menu-actions">
671
+ <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
672
+ </div>
673
+ `}renderWorkspaceDetails(e,t,i){return l`
674
+ <dl class="workspace-menu-details">
675
+ <div class="workspace-detail-row">
676
+ <dt>${i.branch===void 0?"Workspace":"Branch"}</dt>
677
+ <dd>${e}</dd>
678
+ </div>
679
+ <div class="workspace-detail-row">
680
+ <dt>Path</dt>
681
+ <dd title=${i.path}>${i.path}</dd>
682
+ </div>
683
+ ${t.length===0?null:l`
684
+ <div class="workspace-detail-row">
685
+ <dt>Details</dt>
686
+ <dd><span class="workspace-label">${Rr(t)}</span></dd>
687
+ </div>
688
+ `}
689
+ </dl>
690
+ `}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=Mt(t),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}bi(e,()=>this.onSelect?.(t))}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=wi;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([x()],q.prototype,"openMenuWorkspaceId",2);X([x()],q.prototype,"menuStyle",2);q=X([A("workspace-list")],q);function Bh(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function zh(e){return e.isGitWorktree&&!e.isMain}function Uh(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Hh=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,N=(e,t,i,s)=>{for(var r=s>1?void 0:s?qh(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Hh(t,i,r),r};function _i(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let L=class extends T{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(i=>i.archived===!0)&&(this.archivedExpanded=!1);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()}render(){const e=Kh(this.sessions),t=new Set(e.map(r=>r.session.id)),i=sn(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),s=Vh(this.sessions);return l`
691
+ <section>
692
+ ${this.renderHeading(e.length+i.length)}
693
+ ${this.collapsed?null:l`
694
+ <div class="list-body">
695
+ ${e.map(r=>this.renderSession(r,s.get(r.session.id)??0))}
696
+ ${i.length>0?l`
697
+ <h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span><small>${i.length}</small></button></h2>
698
+ ${this.archivedExpanded?i.map(r=>this.renderSession(r,s.get(r.session.id)??0)):null}
699
+ `:null}
700
+ </div>
701
+ `}
702
+ </section>
703
+ `}renderHeading(e){if(!this.collapsible)return l`<h2>Sessions <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`;const t=this.selected===void 0?"No session selected":_i(this.selected),i=this.selected?.path??t;return l`
704
+ <h2>
705
+ <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span><small class="section-selected" title=${i}>${t}</small></span><small class="section-count">${e}</small></button>
706
+ <button ?disabled=${!this.canStart} @click=${s=>{s.stopPropagation(),this.onStart?.()}}>+</button>
707
+ </h2>
708
+ `}renderSession(e,t){const{session:i}=e,s=Math.min(e.depth,2);return l`
709
+ <div
710
+ class="action-row ${this.selected?.id===i.id?"selected":""} ${i.archived===!0?"archived":""}"
711
+ style=${`--depth:${String(s)}`}
712
+ tabindex="0"
713
+ title=${i.path}
714
+ @click=${r=>{vi(r,()=>this.onSelect?.(i))}}
715
+ @keydown=${r=>{bi(r,()=>this.onSelect?.(i))}}
716
+ >
717
+ <div class="action-main">
718
+ <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${_i(i)}${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.renderStatus(i)}${String(i.messageCount)} messages</small>
719
+ </div>
720
+ <div class="action-menu">
721
+ <button class="action-menu-toggle" title="Session actions" @click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}>⋯</button>
722
+ ${this.openMenuSessionId===i.id?l`
723
+ <div class="action-menu-panel" style=${this.menuStyle}>
724
+ ${i.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(i)}}>Detach from parent</button>`:null}
725
+ ${$e(i)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(i)}}>Delete</button>`:i.archived===!0?l`<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(i)}}>Restore</button>`:l`
726
+ <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(i)}}>Archive</button>
727
+ ${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(i,t)}}>Archive with descendants (${t})</button>`:null}
728
+ `}
729
+ </div>
730
+ `:null}
731
+ </div>
732
+ </div>
733
+ `}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${_i(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Mt(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(e){return $e(e)?"new · ":e.archived===!0?"read-only · ":At(fi(this.statuses[e.id],this.activities[e.id])?"session":void 0,"Session active")??""}};L.styles=wi;N([d({attribute:!1})],L.prototype,"sessions",2);N([d({attribute:!1})],L.prototype,"statuses",2);N([d({attribute:!1})],L.prototype,"activities",2);N([d({attribute:!1})],L.prototype,"selected",2);N([d({type:Boolean})],L.prototype,"canStart",2);N([d({type:Boolean,reflect:!0})],L.prototype,"collapsible",2);N([d({type:Boolean,reflect:!0})],L.prototype,"collapsed",2);N([d({attribute:!1})],L.prototype,"onSelect",2);N([d({attribute:!1})],L.prototype,"onStart",2);N([d({attribute:!1})],L.prototype,"onToggleCollapsed",2);N([d({attribute:!1})],L.prototype,"onArchivedCollapsed",2);N([x()],L.prototype,"openMenuSessionId",2);N([x()],L.prototype,"menuStyle",2);N([x()],L.prototype,"archivedExpanded",2);N([d({attribute:!1})],L.prototype,"onArchive",2);N([d({attribute:!1})],L.prototype,"onArchiveWithDescendants",2);N([d({attribute:!1})],L.prototype,"onRestore",2);N([d({attribute:!1})],L.prototype,"onDelete",2);N([d({attribute:!1})],L.prototype,"onDetachParent",2);L=N([A("session-list")],L);function Vh(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Kh(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return sn(e.filter(s=>i.has(s.id)))}function sn(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 r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const f=new Set(c);f.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,f)};for(const n of s)o(n,0,new Set);return r}const $s={CHILD:2,ELEMENT:6},Ps=e=>(...t)=>({_$litDirective$:e,values:t});let Cs=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:Gh}=ta,Er=e=>e,Dr=()=>document.createComment(""),ut=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Dr(),r),n=s.insertBefore(Dr(),r);i=new Gh(o,n,e,e.options)}else{const o=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(o!==r||a){let c=i._$AA;for(;c!==o;){const p=Er(c).nextSibling;Er(s).insertBefore(c,r),c=p}}}return i},Le=(e,t,i=e)=>(e._$AI(t,i),e),Jh={},Qh=(e,t=Jh)=>e._$AH=t,Zh=e=>e._$AH,Li=e=>{e._$AR(),e._$AA.remove()};const _r=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Xh=Ps(class extends Cs{constructor(e){if(super(e),e.type!==$s.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=Zh(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,f,h=0,u=r.length-1,v=0,S=o.length-1;for(;h<=u&&v<=S;)if(r[h]===null)h++;else if(r[u]===null)u--;else if(a[h]===n[v])c[v]=Le(r[h],o[v]),h++,v++;else if(a[u]===n[S])c[S]=Le(r[u],o[S]),u--,S--;else if(a[h]===n[S])c[S]=Le(r[h],o[S]),ut(e,c[S+1],r[h]),h++,S--;else if(a[u]===n[v])c[v]=Le(r[u],o[v]),ut(e,r[h],r[u]),u--,v++;else if(p===void 0&&(p=_r(n,v,S),f=_r(a,h,u)),p.has(a[h]))if(p.has(a[u])){const B=f.get(n[v]),Ge=B!==void 0?r[B]:null;if(Ge===null){const nt=ut(e,r[h]);Le(nt,o[v]),c[v]=nt}else c[v]=Le(Ge,o[v]),ut(e,r[h],Ge),r[B]=null;v++}else Li(r[u]),u--;else Li(r[h]),h++;for(;v<=S;){const B=ut(e,c[S+1]);Le(B,o[v]),c[v++]=B}for(;h<=u;){const B=r[h++];B!==null&&Li(B)}return this.ut=n,Qh(e,c),Ee}}),Yh="pi-web:chat-groups:",eu={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Lr(e));return t===null||t===""?void 0:iu(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Lr(e),JSON.stringify(t))}catch{}}};class tu{constructor(t=eu){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 r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&Or(o,this.openGroupKeys)&&Or(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,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 Lr(e){return`${Yh}${e}`}function iu(e){if(Array.isArray(e))return{open:Oi(e),closedDefaultOpen:[]};if(su(e))return{open:Array.isArray(e.open)?Oi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Oi(e.closedDefaultOpen):[]}}function Oi(e){return e.filter(t=>typeof t=="string")}function Or(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function su(e){return typeof e=="object"&&e!==null}function ru(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>Wr(a,v)),f=a.parts.filter(v=>!Wr(a,v)),h=t+c,u={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(f.length&&o({role:a.role,parts:f,...u},h),p.length){n();const v=p.every(S=>S.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...u},index:h})}}),n(),i}function ou(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function Wr(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 nu=30;function au(e,t){const i=cu(hu(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function lu(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=du(s,t.markerOffset);return}e.scrollTop=pu(e.scrollHeight,t.distanceFromBottom)}function cu(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function du(e,t){return e-t}function pu(e,t){return Math.max(0,e-t)}function hu(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const uu=600,fu=1;function gu(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:mu(e)||vu(e)}function mu(e){return e.scrollTop<(e.topThreshold??Math.max(uu,e.clientHeight))}function vu(e){return e.scrollHeight<=e.clientHeight+fu}const bu="pi-web:chat-scroll:",wu=180,yu=48,xu=2,Su={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)}},ku={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class $u{constructor(t=Su,i=ku){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=wu){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=xu){if(t===""||i===void 0||!ji(i))return"skipped";try{if(on(i,r)){const a={mode:"bottom"};return this.storage.setItem(Wi(t),JSON.stringify(a)),"saved"}const o=Iu(i,s);if(o===void 0)return"skipped";const n=Cu(i,o);return this.storage.setItem(Wi(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ji(i))return{status:"skipped"};const o=Tu(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Wi(t));if(i===null||i==="")return;const s=JSON.parse(i);return Pu(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ji(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Wi(e){return`${bu}${e}`}function Pu(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 ji(e){return e.clientHeight>0&&e.scrollHeight>0}function rn(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function on(e,t=yu){return rn(e)<t}function Cu(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Is(t)??"",offset:t.getBoundingClientRect().top-i}}function Iu(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Is(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>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function jr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function Tu(e,t){return e.find(i=>Is(i)===t)}function Is(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var Mu=Object.defineProperty,Au=Object.getOwnPropertyDescriptor,Ts=(e,t,i,s)=>{for(var r=s>1?void 0:s?Au(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Mu(t,i,r),r};let kt=class extends T{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Nr(this.positionPercent),t=Nr(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
734
+ <div
735
+ class="meter"
736
+ style=${`--position:${e.toFixed(2)}%;`}
737
+ role="meter"
738
+ aria-label=${i}
739
+ aria-valuemin="0"
740
+ aria-valuemax="100"
741
+ aria-valuenow=${String(Math.round(e))}
742
+ title=${i}
743
+ >
744
+ <div class="track" aria-hidden="true">
745
+ <div class="progress"></div>
746
+ <div class="marker"></div>
747
+ </div>
748
+ </div>
749
+ `}};kt.styles=E`
750
+ :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
751
+ :host(:hover), :host(:focus-within) { opacity: .92; }
752
+ .meter { height: 100%; }
753
+ .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); }
754
+ .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)); }
755
+ .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%); }
756
+ `;Ts([d({type:Number})],kt.prototype,"positionPercent",2);Ts([d({type:Number})],kt.prototype,"loadedPercent",2);kt=Ts([A("conversation-meter")],kt);function Nr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class ts extends Cs{constructor(t){if(super(t),this.it=j,t.type!==$s.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===j||t==null)return this._t=void 0,this.it=t;if(t===Ee)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:[]}}}ts.directiveName="unsafeHTML",ts.resultType=1;const Ru=Ps(ts);function Ms(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var He=Ms();function nn(e){He=e}var Oe={exec:()=>null};function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(H.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var Eu=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),H={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)}}>`)},Du=/^(?:[ \t]*(?:\n|$))+/,_u=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Lu=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Rt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ou=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,As=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,an=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ln=I(an).replace(/bull/g,As).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(),Wu=I(an).replace(/bull/g,As).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(),Rs=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ju=/^[^\n]+/,Es=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Nu=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Es).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Fu=I(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,As).getRegex(),yi="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",Ds=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Bu=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ds).replace("tag",yi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),cn=I(Rs).replace("hr",Rt).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",yi).getRegex(),zu=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",cn).getRegex(),_s={blockquote:zu,code:_u,def:Nu,fences:Lu,heading:Ou,hr:Rt,html:Bu,lheading:ln,list:Fu,newline:Du,paragraph:cn,table:Oe,text:ju},Fr=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Rt).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",yi).getRegex(),Uu={..._s,lheading:Wu,table:Fr,paragraph:I(Rs).replace("hr",Rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Fr).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",yi).getRegex()},Hu={..._s,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ds).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:Oe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(Rs).replace("hr",Rt).replace("heading",` *#{1,6} *[^
757
+ ]`).replace("lheading",ln).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qu=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Vu=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,dn=/^( {2,}|\\)\n(?!\s*$)/,Ku=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ot=/[\p{P}\p{S}]/u,xi=/[\s\p{P}\p{S}]/u,Ls=/[^\s\p{P}\p{S}]/u,Gu=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,xi).getRegex(),pn=/(?!~)[\p{P}\p{S}]/u,Ju=/(?!~)[\s\p{P}\p{S}]/u,Qu=/(?:[^\s\p{P}\p{S}]|~)/u,Zu=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Eu?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),hn=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Xu=I(hn,"u").replace(/punct/g,ot).getRegex(),Yu=I(hn,"u").replace(/punct/g,pn).getRegex(),un="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ef=I(un,"gu").replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,xi).replace(/punct/g,ot).getRegex(),tf=I(un,"gu").replace(/notPunctSpace/g,Qu).replace(/punctSpace/g,Ju).replace(/punct/g,pn).getRegex(),sf=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,xi).replace(/punct/g,ot).getRegex(),rf=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ot).getRegex(),of="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",nf=I(of,"gu").replace(/notPunctSpace/g,Ls).replace(/punctSpace/g,xi).replace(/punct/g,ot).getRegex(),af=I(/\\(punct)/,"gu").replace(/punct/g,ot).getRegex(),lf=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),cf=I(Ds).replace("(?:-->|$)","-->").getRegex(),df=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",cf).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),li=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,pf=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",li).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),fn=I(/^!?\[(label)\]\[(ref)\]/).replace("label",li).replace("ref",Es).getRegex(),gn=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",Es).getRegex(),hf=I("reflink|nolink(?!\\()","g").replace("reflink",fn).replace("nolink",gn).getRegex(),Br=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Os={_backpedal:Oe,anyPunctuation:af,autolink:lf,blockSkip:Zu,br:dn,code:Vu,del:Oe,delLDelim:Oe,delRDelim:Oe,emStrongLDelim:Xu,emStrongRDelimAst:ef,emStrongRDelimUnd:sf,escape:qu,link:pf,nolink:gn,punctuation:Gu,reflink:fn,reflinkSearch:hf,tag:df,text:Ku,url:Oe},uf={...Os,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",li).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",li).getRegex()},is={...Os,emStrongRDelimAst:tf,emStrongLDelim:Yu,delLDelim:rf,delRDelim:nf,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Br).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Br).getRegex()},ff={...is,br:I(dn).replace("{2,}","*").getRegex(),text:I(is.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Nt={normal:_s,gfm:Uu,pedantic:Hu},ft={normal:Os,gfm:is,breaks:ff,pedantic:uf},gf={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},zr=e=>gf[e];function me(e,t){if(t){if(H.escapeTest.test(e))return e.replace(H.escapeReplace,zr)}else if(H.escapeTestNoEncode.test(e))return e.replace(H.escapeReplaceNoEncode,zr);return e}function Ur(e){try{e=encodeURI(e).replace(H.percentDecode,"%")}catch{return null}return e}function Hr(e,t){let i=e.replace(H.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(H.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(H.slashPipe,"|");return s}function Ae(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function qr(e){let t=e.split(`
758
+ `),i=t.length-1;for(;i>=0&&H.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
759
+ `)}function mf(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 vf(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function Vr(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function bf(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
760
+ `).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
761
+ `)}var ci=class{options;rules;lexer;constructor(e){this.options=e||He}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]:qr(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=bf(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=Ae(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ae(t[0],`
762
+ `),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:Ae(t[0],`
763
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Ae(t[0],`
764
+ `).split(`
765
+ `),s="",r="",o=[];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(`
766
+ `),f=p.replace(this.rules.other.blockquoteSetextReplace,`
767
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
768
+ ${p}`:p,r=r?`${r}
769
+ ${f}`:f;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,o,!0),this.lexer.state.top=h,i.length===0)break;let u=o.at(-1);if(u?.type==="code")break;if(u?.type==="blockquote"){let v=u,S=v.raw+`
770
+ `+i.join(`
771
+ `),B=this.blockquote(S);o[o.length-1]=B,s=s.substring(0,s.length-v.raw.length)+B.raw,r=r.substring(0,r.length-v.text.length)+B.text;break}else if(u?.type==="list"){let v=u,S=v.raw+`
772
+ `+i.join(`
773
+ `),B=this.list(S);o[o.length-1]=B,s=s.substring(0,s.length-u.raw.length)+B.raw,r=r.substring(0,r.length-v.raw.length)+B.raw,i=S.substring(o.at(-1).raw.length).split(`
774
+ `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",f="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=vf(t[2].split(`
775
+ `,1)[0],t[1].length),u=e.split(`
776
+ `,1)[0],v=!h.trim(),S=0;if(this.options.pedantic?(S=2,f=h.trimStart()):v?S=t[1].length+1:(S=h.search(this.rules.other.nonSpaceChar),S=S>4?1:S,f=h.slice(S),S+=t[1].length),v&&this.rules.other.blankLine.test(u)&&(p+=u+`
777
+ `,e=e.substring(u.length+1),c=!0),!c){let B=this.rules.other.nextBulletRegex(S),Ge=this.rules.other.hrRegex(S),nt=this.rules.other.fencesBeginRegex(S),Fs=this.rules.other.headingBeginRegex(S),Sn=this.rules.other.htmlBeginRegex(S),kn=this.rules.other.blockquoteBeginRegex(S);for(;e;){let ki=e.split(`
778
+ `,1)[0],at;if(u=ki,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),at=u):at=u.replace(this.rules.other.tabCharGlobal," "),nt.test(u)||Fs.test(u)||Sn.test(u)||kn.test(u)||B.test(u)||Ge.test(u))break;if(at.search(this.rules.other.nonSpaceChar)>=S||!u.trim())f+=`
779
+ `+at.slice(S);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||nt.test(h)||Fs.test(h)||Ge.test(h))break;f+=`
780
+ `+u}v=!u.trim(),p+=ki+`
781
+ `,e=e.substring(ki.length+1),h=at.slice(S)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let 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 f=this.rules.other.listTaskCheckbox.exec(c.raw);if(f){let h={type:"checkbox",raw:f[0]+" ",checked:f[0]!=="[ ]"};c.checked=h.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=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(!r.loose){let f=c.tokens.filter(u=>u.type==="space"),h=f.length>0&&f.some(u=>this.rules.other.anyLine.test(u.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=qr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Ae(t[0],`
782
+ `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Hr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
783
+ `):[],o={type:"table",raw:Ae(t[0],`
784
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(Hr(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Ae(t[0],`
785
+ `),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)===`
786
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let o=Ae(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=mf(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Vr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return Vr(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let f=[...s[0]][0].length,h=e.slice(0,r+s.index+f+n);if(Math.min(r,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let u=h.slice(2,-2);return{type:"strong",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,f=e.slice(0,r+s.index+p+n),h=f.slice(r,-r);return{type:"del",raw:f,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 r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},he=class ss{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||He,this.options.tokenizer=this.options.tokenizer||new ci,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:H,block:Nt.normal,inline:ft.normal};this.options.pedantic?(i.block=Nt.pedantic,i.inline=ft.pedantic):this.options.gfm&&(i.block=Nt.gfm,this.options.breaks?i.inline=ft.breaks:i.inline=ft.gfm),this.tokenizer.rules=i}static get rules(){return{block:Nt,inline:ft}}static lex(t,i){return new ss(i).lex(t)}static lexInline(t,i){return new ss(i).inlineTokens(t)}lex(t){t=t.replace(H.carriageReturn,`
787
+ `),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(H.tabCharGlobal," ").replace(H.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
788
+ `:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
789
+ `)?"":`
790
+ `)+o.raw,a.text+=`
791
+ `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
792
+ `)?"":`
793
+ `)+o.raw,a.text+=`
794
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(f=>{p=f.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
795
+ `)?"":`
796
+ `)+o.raw,a.text+=`
797
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
798
+ `)?"":`
799
+ `)+o.raw,a.text+=`
800
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",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 f=t;if(this.options.extensions?.startInline){let h=1/0,u=t.slice(1),v;this.options.extensions.startInline.forEach(S=>{v=S.call({lexer:this},u),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(f=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(f)){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)}},di=class{options;parser;constructor(e){this.options=e||He}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(H.notSpaceStart)?.[0],r=e.replace(H.endingNewline,"")+`
801
+ `;return s?'<pre><code class="language-'+me(s)+'">'+(i?r:me(r,!0))+`</code></pre>
802
+ `:"<pre><code>"+(i?r:me(r,!0))+`</code></pre>
803
+ `}blockquote({tokens:e}){return`<blockquote>
804
+ ${this.parser.parse(e)}</blockquote>
805
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
806
+ `}hr(e){return`<hr>
807
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`>
808
+ `+s+"</"+r+`>
809
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
810
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
811
+ `}table(e){let t="",i="";for(let r=0;r<e.header.length;r++)i+=this.tablecell(e.header[r]);t+=this.tablerow({text:i});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];i="";for(let n=0;n<o.length;n++)i+=this.tablecell(o[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
812
+ <thead>
813
+ `+t+`</thead>
814
+ `+s+`</table>
815
+ `}tablerow({text:e}){return`<tr>
816
+ ${e}</tr>
817
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
818
+ `}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),r=Ur(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+me(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=Ur(e);if(r===null)return me(i);e=r;let o=`<img src="${e}" alt="${me(i)}"`;return t&&(o+=` title="${me(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:me(e.text)}},Ws=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}},ue=class rs{options;renderer;textRenderer;constructor(t){this.options=t||He,this.options.renderer=this.options.renderer||new di,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ws}static parse(t,i){return new rs(i).parse(t)}static parseInline(t,i){return new rs(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},mt=class{options;block;constructor(e){this.options=e||He}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?he.lex:he.lexInline}provideParser(e=this.block){return e?ue.parse:ue.parseInline}},wf=class{defaults=Ms();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ue;Renderer=di;TextRenderer=Ws;Lexer=he;Tokenizer=ci;Hooks=mt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new di(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new ci(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new mt;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];mt.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&mt.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let f=a.call(r,p);return c.call(r,f)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return he.lex(e,t??this.defaults)}parser(e,t){return ue.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?he.lex:he.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?ue.parse:ue.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?he.lex:he.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?ue.parse:ue.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
819
+ 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}}},Fe=new wf;function M(e,t){return Fe.parse(e,t)}M.options=M.setOptions=function(e){return Fe.setOptions(e),M.defaults=Fe.defaults,nn(M.defaults),M};M.getDefaults=Ms;M.defaults=He;M.use=function(...e){return Fe.use(...e),M.defaults=Fe.defaults,nn(M.defaults),M};M.walkTokens=function(e,t){return Fe.walkTokens(e,t)};M.parseInline=Fe.parseInline;M.Parser=ue;M.parser=ue.parse;M.Renderer=di;M.TextRenderer=Ws;M.Lexer=he;M.lexer=he.lex;M.Tokenizer=ci;M.Hooks=mt;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;ue.parse;he.lex;const mn=new M.Renderer;mn.html=({text:e})=>Sf(e);const yf=300,gt=new Map;function xf(e){const t=gt.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:mn}),s=kf(i);if(gt.set(e,s),gt.size>yf){const r=gt.keys().next().value;r!==void 0&&gt.delete(r)}return s}function Sf(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function kf(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!$f(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function $f(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Pf=Object.defineProperty,Cf=Object.getOwnPropertyDescriptor,vn=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cf(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Pf(t,i,r),r};let pi=class extends T{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)},this.onFormattedCopy=e=>{e.clipboardData===null||!Mf(If(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return l`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${Ru(xf(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="Copy code block",s.setAttribute("aria-label","Copy code block");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Af(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)}};pi.styles=Ch;vn([d()],pi.prototype,"text",2);pi=vn([A("formatted-text")],pi);function If(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&Tf(t)?t.getSelection():e.ownerDocument.getSelection()}function Tf(e){return"getSelection"in e&&typeof e.getSelection=="function"}function Mf(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function Af(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var Rf=Object.defineProperty,Ef=Object.getOwnPropertyDescriptor,Et=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ef(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Rf(t,i,r),r};const Kr=180;let Be=class extends T{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=Df(e.args),s=_f(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:Lf(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
820
+ <section class=${`tool-card ${e.status}`}>
821
+ <div class="tool-header">
822
+ <div class="tool-title">
823
+ <span class="status-icon" aria-hidden="true">${Wf(e.status)}</span>
824
+ <strong>${e.toolName}</strong>
825
+ ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
826
+ </div>
827
+ <div class="tool-meta">
828
+ ${Gr(e)===void 0?null:l`<span>${Gr(e)}</span>`}
829
+ ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
830
+ <span class="status-label">${jf(e.status)}</span>
831
+ </div>
832
+ </div>
833
+
834
+ ${a?l`<p class="notice">Applied diff differs from the preview.</p>`:null}
835
+ ${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
836
+ ${o===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(o,s===void 0?"Preview diff":"Applied diff")}
837
+ ${!t&&o===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
838
+ </section>
839
+ `}renderTextBody(e,t){return e===void 0||e===""?null:l`
840
+ <details class="text-body" ?open=${t}>
841
+ <summary>Result</summary>
842
+ <pre>${e}</pre>
843
+ </details>
844
+ `}renderDiffBody(e,t){const i=e.split(`
845
+ `),s=!this.showFullDiff&&i.length>Kr,r=s?i.slice(0,Kr):i;return l`
846
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
847
+ <summary>
848
+ <span>${t}</span>
849
+ <small>${String(i.length)} ${i.length===1?"line":"lines"}</small>
850
+ </summary>
851
+ <div class="diff-toolbar">
852
+ <span>${s?`Showing ${String(r.length)} of ${String(i.length)} lines`:"Full diff"}</span>
853
+ <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
854
+ </div>
855
+ <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${Of(o)}>${o}</span>`)}</code></pre>
856
+ ${s?l`
857
+ <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
858
+ Show all ${String(i.length)} diff lines
859
+ </button>
860
+ `:null}
861
+ </details>
862
+ `}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}}};Be.styles=E`
863
+ :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
864
+ .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); }
865
+ .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
866
+ .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
867
+ .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
868
+ .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
869
+ .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
870
+ .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
871
+ strong { color: var(--pi-text); }
872
+ .path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
873
+ .summary { color: var(--pi-muted); font-family: inherit; }
874
+ .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
875
+ .diff-stats { display: inline-flex; gap: 3px; }
876
+ .added, .diff .added { color: var(--pi-success); }
877
+ .removed, .diff .removed { color: var(--pi-danger); }
878
+ .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
879
+ .notice { margin: 0; color: var(--pi-warning); }
880
+ .muted { margin: 0; color: var(--pi-muted); }
881
+ .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
882
+ .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
883
+ .text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
884
+ .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
885
+ .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
886
+ .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
887
+ .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
888
+ .diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
889
+ .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
890
+ button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
891
+ button:hover, button:focus { border-color: var(--pi-accent); }
892
+ .diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
893
+ .diff-content { display: block; width: max-content; min-width: 100%; }
894
+ .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
895
+ .diff .context { color: var(--pi-muted); }
896
+ .diff .hunk { color: var(--pi-accent); }
897
+ .diff .file { color: var(--pi-dim); }
898
+ .diff .meta { color: var(--pi-dim); }
899
+ .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
900
+ .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
901
+ .show-more { justify-self: start; }
902
+ `;Et([d({attribute:!1})],Be.prototype,"execution",2);Et([x()],Be.prototype,"showFullDiff",2);Et([x()],Be.prototype,"copied",2);Et([x()],Be.prototype,"diffOpen",2);Be=Et([A("tool-execution-view")],Be);function Df(e){return os(e,"path")??os(e,"file_path")}function Gr(e){if(e.toolName!=="edit")return;const t=Gt(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof Gt(e.args,"oldText")=="string"&&typeof Gt(e.args,"newText")=="string")return"1 edit"}function _f(e){return os(e,"diff")}function Lf(e){let t=0,i=0;for(const s of e.split(`
903
+ `))bn(s)?t++:wn(s)&&i++;return{added:t,removed:i}}function Of(e){return bn(e)?"added":wn(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function bn(e){return e.startsWith("+")&&!e.startsWith("+++")}function wn(e){return e.startsWith("-")&&!e.startsWith("---")}function Wf(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function jf(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Nf(e){return typeof e=="object"&&e!==null}function Gt(e,t){return Nf(e)?e[t]:void 0}function os(e,t){const i=Gt(e,t);return typeof i=="string"?i:void 0}var Ff=Object.defineProperty,Bf=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?Bf(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ff(t,i,r),r};const zf=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Uf=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Ni=["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 Ni[Math.floor(Math.random()*Ni.length)]??Ni[0]}function Qr(e){return Jt(e,0,100)}function Jt(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let O=class extends T{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 tu,this.scrollController=new $u,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`
904
+ <div class="chat-wrap">
905
+ ${this.renderConversationRail()}
906
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
907
+ ${this.renderHistoryBoundary()}
908
+ ${Xh(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)))}
909
+ ${this.renderQueuedMessages()}
910
+ ${this.renderSessionActivity()}
911
+ </div>
912
+ ${this.renderActivityDock()}
913
+ </div>
914
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=ru(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`
915
+ <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
916
+ <span class="dot"></span>
917
+ <span class="activity-text">${this.activityText(e)}</span>
918
+ </div>
919
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
920
+ <aside class="queued-messages" aria-live="polite">
921
+ <div class="queued-header">
922
+ <strong>Queued messages</strong>
923
+ <small>${e.length} pending · Stop clears the queue</small>
924
+ </div>
925
+ ${e.map((t,i)=>l`
926
+ <div class="queued-message">
927
+ <span class="queued-kind">${t.kind==="steer"?"Steer":"Follow-up"} ${String(i+1)}</span>
928
+ <formatted-text .text=${t.text}></formatted-text>
929
+ </div>
930
+ `)}
931
+ </aside>
932
+ `}renderSessionActivity(){return this.isReceivingPartialStream?l`
933
+ <aside class="session-activity receiving" aria-live="polite">
934
+ <strong>Catching up…</strong>
935
+ <span>${this.currentPartialStreamNoticeBody()}</span>
936
+ </aside>
937
+ `:this.isCompacting?l`
938
+ <aside class="session-activity compacting" aria-live="polite">
939
+ <strong>Compacting history…</strong>
940
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
941
+ ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
942
+ </aside>
943
+ `: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?Qr(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=Jt(this.currentConversationIndex??t,0,e-1);return Qr(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`
944
+ <div class="history-boundary">
945
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
946
+ <span>Scroll up to load earlier messages</span>
947
+ ${e}
948
+ </div>
949
+ `:this.messages.length?l`<div class="history-boundary"><span>Beginning of session</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.loadedRawMessageEnd(),i=Math.max(this.messageTotal,t);return l`<small>Showing messages ${e}–${t} of ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
950
+ ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
951
+ <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
952
+ ${i?null:this.renderMessageHeader(e,String(t))}
953
+ ${e.parts.map(s=>this.renderPart(s,e))}
954
+ </article>
955
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const r=this.groupDisclosureKey(t,i,s),o=this.disclosures.isOpen(r,s);return l`
956
+ ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
957
+ <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
958
+ <summary>
959
+ <b class="label">${s?"live events":"events"}</b>
960
+ <span>${ou(e)}</span>
961
+ </summary>
962
+ <div class="group-body">
963
+ ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
964
+ <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
965
+ ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
966
+ ${n.parts.map(p=>this.renderPart(p,n))}
967
+ </section>
968
+ `})}
969
+ </div>
970
+ </details>
971
+ `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
972
+ <div class="msg-header">
973
+ <b class="label">${e.role}</b>
974
+ <div class="msg-header-trailing">
975
+ ${this.renderMessageActions(e,t)}
976
+ <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
977
+ </div>
978
+ </div>
979
+ `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
980
+ <div class="msg-actions" aria-label="Message actions">
981
+ <button type="button" class="msg-action" title=${i?"Copied":"Copy message"} aria-label=${`${i?"Copied":"Copy"} ${e.role} message`} @click=${s=>{this.copyMessage(e,t,s)}}>
982
+ <span aria-hidden="true">${i?"✓":"⧉"}</span>
983
+ </button>
984
+ </div>
985
+ `}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(`
986
+
987
+ `);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 r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:zf.format(t),full:Uf.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`
988
+ <details class="part skill-invocation">
989
+ <summary><b>[skill]</b> ${e.name}</summary>
990
+ <small>${e.location}</small>
991
+ <formatted-text .text=${e.content}></formatted-text>
992
+ </details>
993
+ `:e.type==="skillRead"?l`
994
+ <div class="part skill-read">
995
+ <strong>Loaded ${e.name}</strong>
996
+ <small>read ${e.path}</small>
997
+ </div>
998
+ `: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`
999
+ <details class="part" ?open=${e.isError}>
1000
+ <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1001
+ <formatted-text .text=${e.text}></formatted-text>
1002
+ </details>
1003
+ `: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&&gu({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?on(e):!0}isAtBottom(){const e=this.chat;return e?rn(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 au(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 r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(lu(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<nu){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=Jt(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Jt(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 jr(e,t)??jr(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)}`}};O.styles=Ph;F([d({attribute:!1})],O.prototype,"messages",2);F([d()],O.prototype,"sessionId",2);F([d({type:Number})],O.prototype,"messageStart",2);F([d({type:Number})],O.prototype,"messageEnd",2);F([d({type:Number})],O.prototype,"messageTotal",2);F([d({type:Boolean})],O.prototype,"hasMore",2);F([d({type:Boolean})],O.prototype,"loadingMore",2);F([d({type:Boolean})],O.prototype,"isReceivingPartialStream",2);F([d({type:Boolean})],O.prototype,"isCompacting",2);F([d({type:Number})],O.prototype,"pendingMessageCount",2);F([d({attribute:!1})],O.prototype,"status",2);F([d({attribute:!1})],O.prototype,"activity",2);F([d({attribute:!1})],O.prototype,"onLoadMore",2);F([re(".chat")],O.prototype,"chat",2);F([x()],O.prototype,"pinnedToBottom",2);F([x()],O.prototype,"expandedMetaKey",2);F([x()],O.prototype,"copiedMessageKey",2);F([x()],O.prototype,"currentConversationIndex",2);F([x()],O.prototype,"loadMoreRequested",2);O=F([A("chat-view")],O);class Hf extends Cs{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===$s.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const js=Ps(Hf);var qf=Object.defineProperty,Vf=Object.getOwnPropertyDescriptor,Si=(e,t,i,s)=>{for(var r=s>1?void 0:s?Vf(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&qf(t,i,r),r};let it=class extends T{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1004
+ <div class="menu">
1005
+ ${this.items.map((e,t)=>l`
1006
+ <button class=${t===this.selectedIndex?"selected":""} ${js(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1007
+ <strong>${e.insertText}</strong>
1008
+ <span>${e.detail}</span>
1009
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1010
+ </button>
1011
+ `)}
1012
+ </div>
1013
+ `:null}};it.styles=Th;Si([d({attribute:!1})],it.prototype,"items",2);Si([d({type:Number})],it.prototype,"selectedIndex",2);Si([d({attribute:!1})],it.prototype,"onPick",2);it=Si([A("autocomplete-menu")],it);var Kf=Object.defineProperty,Gf=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var r=s>1?void 0:s?Gf(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Kf(t,i,r),r};let z=class extends T{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 Bs,this.readOnlyCompartment=new Bs}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=Ft(i,t);s!==void 0&&si(s,this.draft);const r=Ft(this.machineId,this.sessionId);this.draft=r!==void 0?$o(r):"",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=ws(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return l`
1014
+ <footer class=${t?"shell-mode":""}>
1015
+ <div class="editor-wrap">
1016
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
1017
+ ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1018
+ ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1019
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
1020
+ </div>
1021
+ <div class="actions">
1022
+ ${this.renderCompactStatus()}
1023
+ <button ?disabled=${this.disabled} title=${i?"Queue until the current activity finishes":"Send message"} @click=${()=>{this.send("followUp")}}>${i?"Queue":"Send"}</button>
1024
+ ${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}
1025
+ <button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}>Stop</button>
1026
+ </div>
1027
+ </footer>
1028
+ `}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`
1029
+ <div class="compact-status" aria-label="Session status">
1030
+ <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1031
+ <button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${e.thinkingLevel??"off"}</button>
1032
+ </div>
1033
+ `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Je({parent:this.editorHost,state:$i.create({doc:this.draft,extensions:[$n(),_n(),Pn(),Cn.of(" "),In(Dn,{fallback:!0}),Je.lineWrapping,Je.contentAttributes.of(e=>eg(e.state.sliceDoc(0,e.state.selection.main.head))),Tn("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(Je.editable.of(!this.disabled)),this.readOnlyCompartment.of($i.readOnly.of(this.disabled)),Je.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Mn.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=>Ln(e)||En(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>zs.shift?.(e)??!1},{key:"Backspace",run:e=>On(e)},...An,...Rn])]})}))}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:Us.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Je.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure($i.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Ft(this.machineId,this.sessionId);t!==void 0&&si(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!==""){const i=await _.commands(this.sessionId,this.machineId).catch(Qf);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 _.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Zf);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Jf(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
1034
+ `))+1,r=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:r,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(r.startsWith("/")&&s===0)return{kind:"command",query:r.slice(1),from:s,to:e};if(r.startsWith("!@"))return{kind:"file",query:r.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-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}}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):zs.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:Us.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Ft(this.machineId,this.sessionId);i!==void 0&&bs(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};z.styles=Ah;U([d({type:Boolean})],z.prototype,"disabled",2);U([d()],z.prototype,"sessionId",2);U([d()],z.prototype,"cwd",2);U([d()],z.prototype,"machineId",2);U([d({type:Boolean})],z.prototype,"canSteer",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Boolean})],z.prototype,"canStop",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"onSend",2);U([d({attribute:!1})],z.prototype,"onStop",2);U([d({attribute:!1})],z.prototype,"onSelectModel",2);U([d({attribute:!1})],z.prototype,"onSelectThinking",2);U([re(".markdown-editor")],z.prototype,"editorHost",2);U([x()],z.prototype,"draft",2);U([x()],z.prototype,"completions",2);U([x()],z.prototype,"selectedIndex",2);z=U([A("prompt-editor")],z);function Ft(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return ko(e,t)}function Jf(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Qf(){return[]}function Zf(){return[]}const Xf={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Yf={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function eg(e){return ws(e).kind==="normal"?Xf:Yf}function Bt(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 tg(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var ig=Object.defineProperty,sg=Object.getOwnPropertyDescriptor,Dt=(e,t,i,s)=>{for(var r=s>1?void 0:s?sg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ig(t,i,r),r};let ze=class extends T{constructor(){super(...arguments),this.workspaceLabelItems=[]}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 ${Bt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Bt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1035
+ <div class="bar">
1036
+ <span>${this.machine?.name??"Local"}</span>
1037
+ <span>${en(this.workspace?.label??"workspace",this.workspaceLabelItems,this.workspace?.path)}</span>
1038
+ <span>↑${Bt(s.input)}</span>
1039
+ <span>↓${Bt(s.output)}</span>
1040
+ <span>${i}</span>
1041
+ <span>${tg(e.cost)}</span>
1042
+ ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1043
+ </div>
1044
+ `}};ze.styles=Ih;Dt([d({attribute:!1})],ze.prototype,"status",2);Dt([d({attribute:!1})],ze.prototype,"machine",2);Dt([d({attribute:!1})],ze.prototype,"workspace",2);Dt([d({attribute:!1})],ze.prototype,"workspaceLabelItems",2);ze=Dt([A("status-bar")],ze);var rg=Object.defineProperty,og=Object.getOwnPropertyDescriptor,Te=(e,t,i,s)=>{for(var r=s>1?void 0:s?og(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&rg(t,i,r),r};let fe=class extends T{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1045
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1046
+ <section @mousedown=${t=>{t.stopPropagation()}}>
1047
+ <header>
1048
+ <strong>${this.title}</strong>
1049
+ <button @click=${()=>this.onCancel?.()}>×</button>
1050
+ </header>
1051
+ ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1052
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1053
+ ${e.map((t,i)=>l`
1054
+ <button class=${i===this.selectedIndex?"selected":""} ${js(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1055
+ <span>${t.label}</span>
1056
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1057
+ </button>
1058
+ `)}
1059
+ ${e.length===0?l`<div class="empty">No matching options</div>`:null}
1060
+ </div>
1061
+ </section>
1062
+ </div>
1063
+ `}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)}}};fe.styles=Yo;Te([d()],fe.prototype,"title",2);Te([d({type:Boolean})],fe.prototype,"searchable",2);Te([d({attribute:!1})],fe.prototype,"options",2);Te([d({attribute:!1})],fe.prototype,"selectedValue",2);Te([d({attribute:!1})],fe.prototype,"onPick",2);Te([d({attribute:!1})],fe.prototype,"onCancel",2);Te([x()],fe.prototype,"selectedIndex",2);Te([x()],fe.prototype,"query",2);fe=Te([A("command-picker")],fe);var ng=Object.defineProperty,ag=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?ag(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ng(t,i,r),r};let Pe=class extends T{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1064
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1065
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1066
+ <header>
1067
+ <input
1068
+ .value=${this.queryText}
1069
+ placeholder="Search actions..."
1070
+ @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
1071
+ >
1072
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
1073
+ </header>
1074
+ <div class="options">
1075
+ ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1076
+ <button class=${i===this.selectedIndex?"selected":""} ${js(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1077
+ <span class="main">
1078
+ <strong>${t.title}</strong>
1079
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1080
+ </span>
1081
+ ${t.shortcut!==void 0?l`<kbd>${Oo(t.shortcut)}</kbd>`:null}
1082
+ ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1083
+ </button>
1084
+ `)}
1085
+ </div>
1086
+ </section>
1087
+ </div>
1088
+ `}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)}};Pe.styles=Mh;qe([d({attribute:!1})],Pe.prototype,"actions",2);qe([d({attribute:!1})],Pe.prototype,"onRun",2);qe([d({attribute:!1})],Pe.prototype,"onCancel",2);qe([re("input")],Pe.prototype,"input",2);qe([x()],Pe.prototype,"queryText",2);qe([x()],Pe.prototype,"selectedIndex",2);Pe=qe([A("action-palette")],Pe);var lg=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?cg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&lg(t,i,r),r};let G=class extends T{render(){const e=this.state;return e===void 0?null:l`
1089
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1090
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1091
+ <header>
1092
+ <strong>${this.dialogTitle(e)}</strong>
1093
+ <button title="Close" @click=${()=>{this.cancel()}}>×</button>
1094
+ </header>
1095
+ ${this.renderBody(e)}
1096
+ </section>
1097
+ </div>
1098
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"Configure provider authentication";case"providers":return e.authType===void 0?"Select provider authentication":e.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${e.provider.name}`;case"oauth":return`Login to ${e.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(e){switch(e.step){case"method":return l`
1099
+ <div class="options">
1100
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
1101
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
1102
+ </div>
1103
+ `;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No providers available.</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
1104
+ <div class="form">
1105
+ <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
1106
+ <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
1107
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1108
+ <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>
1109
+ </div>
1110
+ `;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`
1111
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Zr(t.authType)}</small></button>
1112
+ `)}</div>`}}renderProviderButton(e){return l`
1113
+ <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1114
+ <span>${e.name}${e.status.source!==void 0?l` <em>${pg(e)}</em>`:null}</span>
1115
+ <small>${e.id} · ${Zr(e.authType)}</small>
1116
+ </button>
1117
+ `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1118
+ <div class="form">
1119
+ ${t.auth!==void 0?l`
1120
+ <p>Open this authorization link:</p>
1121
+ <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1122
+ ${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
1123
+ `:l`<p>Starting login flow…</p>`}
1124
+ ${t.progress.length>0?l`<ul class="progress">${t.progress.map(r=>l`<li>${r}</li>`)}</ul>`:null}
1125
+ ${i!==void 0?l`
1126
+ <label>${i.message}</label>
1127
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
1128
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
1129
+ `:null}
1130
+ ${s!==void 0?l`
1131
+ <p>${s.message}</p>
1132
+ <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1133
+ `:null}
1134
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1135
+ ${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}
1136
+ ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1137
+ </div>
1138
+ `}focusInputIfNeeded(){const e=dg(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?.()}};G.styles=[Yo,E`
1139
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1140
+ .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1141
+ .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
1142
+ .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
1143
+ label { color: var(--pi-muted); }
1144
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
1145
+ .actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
1146
+ .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
1147
+ .actions button:disabled { opacity: .6; cursor: wait; }
1148
+ .warning { color: var(--pi-warning); }
1149
+ .error-text { color: var(--pi-danger); }
1150
+ .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1151
+ .inline-options { display: grid; gap: 8px; }
1152
+ em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1153
+ `];ae([d({attribute:!1})],G.prototype,"state",2);ae([d({attribute:!1})],G.prototype,"onChooseMethod",2);ae([d({attribute:!1})],G.prototype,"onSelectProvider",2);ae([d({attribute:!1})],G.prototype,"onApiKeyInput",2);ae([d({attribute:!1})],G.prototype,"onSaveApiKey",2);ae([d({attribute:!1})],G.prototype,"onLogoutProvider",2);ae([d({attribute:!1})],G.prototype,"onOAuthInput",2);ae([d({attribute:!1})],G.prototype,"onOAuthRespond",2);ae([d({attribute:!1})],G.prototype,"onOAuthCancel",2);ae([d({attribute:!1})],G.prototype,"onCancel",2);ae([re("input")],G.prototype,"input",2);G=ae([A("auth-dialog")],G);function Zr(e){return e==="oauth"?"subscription":"API key"}function dg(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 pg(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 hg=Object.defineProperty,ug=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var r=s>1?void 0:s?ug(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&hg(t,i,r),r};let te=class extends T{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 _.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`
1154
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1155
+ <section @click=${e=>{e.stopPropagation()}}>
1156
+ <header>
1157
+ <strong>Add project</strong>
1158
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1159
+ </header>
1160
+ <div class="body">
1161
+ <label>
1162
+ Project folder
1163
+ <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
1164
+ </label>
1165
+ <div class="suggestions">
1166
+ ${this.loading?l`<div class="hint">Loading folders…</div>`:null}
1167
+ ${this.suggestions.map((e,t)=>l`
1168
+ <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
1169
+ ${e.path}
1170
+ </button>
1171
+ `)}
1172
+ ${!this.loading&&this.suggestions.length===0?l`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
1173
+ </div>
1174
+ <label class="check">
1175
+ <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
1176
+ Create the folder if it does not exist
1177
+ </label>
1178
+ </div>
1179
+ <footer>
1180
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
1181
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
1182
+ </footer>
1183
+ </section>
1184
+ </div>
1185
+ `}};te.styles=E`
1186
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1187
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1188
+ 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; }
1189
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1190
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1191
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
1192
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1193
+ input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1194
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
1195
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
1196
+ .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1197
+ .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
1198
+ .hint { padding: 12px; color: var(--pi-muted); }
1199
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1200
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1201
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1202
+ button:disabled { opacity: .5; cursor: not-allowed; }
1203
+ `;ye([d({attribute:!1})],te.prototype,"onSubmit",2);ye([d({attribute:!1})],te.prototype,"onCancel",2);ye([d()],te.prototype,"machineId",2);ye([x()],te.prototype,"path",2);ye([x()],te.prototype,"createMissing",2);ye([x()],te.prototype,"suggestions",2);ye([x()],te.prototype,"selected",2);ye([x()],te.prototype,"loading",2);ye([re("input")],te.prototype,"pathInput",2);te=ye([A("project-dialog")],te);var fg=Object.defineProperty,gg=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?gg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&fg(t,i,r),r};let ie=class extends T{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=mg(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"&&Fi(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===""||Fi(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?Fi(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1204
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1205
+ <section @click=${s=>{s.stopPropagation()}}>
1206
+ <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
1207
+ <header>
1208
+ <strong>Add machine</strong>
1209
+ <button type="button" @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1210
+ </header>
1211
+ <div class="body">
1212
+ ${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
1213
+ <label>
1214
+ Remote PI WEB URL
1215
+ <input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
1216
+ </label>
1217
+ <small class=${t===void 0?"hint":"field-error"}>${t??"Enter the reachable base URL first, including http:// or https://."}</small>
1218
+ ${e?l`
1219
+ <label>
1220
+ Machine name
1221
+ <input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"Dev Box"} autocomplete="off" />
1222
+ </label>
1223
+ <small class="hint">Suggested from the URL. Edit it to use a friendlier sidebar label.</small>
1224
+ <label>
1225
+ Bearer token <span class="optional">optional</span>
1226
+ <input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="Leave blank if the remote machine does not require one" autocomplete="off" />
1227
+ </label>
1228
+ <small class="hint">Paste only the token value; PI WEB sends it as an Authorization: Bearer header.</small>
1229
+ `:l`<p class="hint intro">After you enter a URL, PI WEB will suggest a machine name and let you add an optional bearer token.</p>`}
1230
+ </div>
1231
+ <footer>
1232
+ <button type="button" @click=${()=>{this.onCancel?.()}}>Cancel</button>
1233
+ <button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"Adding…":"Add machine"}</button>
1234
+ </footer>
1235
+ </form>
1236
+ </section>
1237
+ </div>
1238
+ `}};ie.styles=E`
1239
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1240
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1241
+ 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; }
1242
+ form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
1243
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1244
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1245
+ .body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
1246
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1247
+ input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1248
+ input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
1249
+ .hint { color: var(--pi-muted); }
1250
+ .intro { margin: 4px 0 0; line-height: 1.4; }
1251
+ .optional { color: var(--pi-muted); font-weight: 400; }
1252
+ .field-error { color: var(--pi-danger); }
1253
+ .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; }
1254
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1255
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1256
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1257
+ button:disabled { opacity: .5; cursor: not-allowed; }
1258
+ `;xe([d({attribute:!1})],ie.prototype,"onSubmit",2);xe([d({attribute:!1})],ie.prototype,"onCancel",2);xe([d()],ie.prototype,"error",2);xe([x()],ie.prototype,"url",2);xe([x()],ie.prototype,"name",2);xe([x()],ie.prototype,"token",2);xe([x()],ie.prototype,"submitting",2);xe([re("input[name='baseUrl']")],ie.prototype,"urlInput",2);xe([re("input[name='name']")],ie.prototype,"nameInput",2);ie=xe([A("machine-dialog")],ie);function mg(e){const t=e.trim();if(t==="")return"";const i=Xr(t)??Xr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):vg(t)}function Fi(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 Xr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function vg(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 bg(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function wg(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(`
1259
+ `):""}}function yg(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const o=Number(r);if(!Number.isInteger(o)||o<1||o>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=o}return i.allowedHosts=e.allowedHostsMode==="all"?!0:xg(e.allowedHostsText),i}function xg(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var Sg=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?kg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Sg(t,i,r),r};let se=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=bg(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=wg(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1260
+ <div class="section-heading">
1261
+ <div>
1262
+ <h2>General configuration</h2>
1263
+ <p>Update the JSON config file PI WEB is using. Host and port changes are saved immediately, but require the web service to restart before the running server binds to the new address.</p>
1264
+ </div>
1265
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1266
+ </div>
1267
+ ${this.renderMessages()}
1268
+ ${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
1269
+ <div class="config-path-card">
1270
+ <span>Config file</span>
1271
+ <code>${e?.path??"Unknown"}</code>
1272
+ <small>${e?.exists===!0?"Existing file":"This file will be created on save"}</small>
1273
+ </div>
1274
+ <form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
1275
+ <label class="field">
1276
+ <span class="field-heading">
1277
+ <span>Host</span>
1278
+ ${this.renderOverrideBadge("host")}
1279
+ </span>
1280
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Yr(t)})}}>
1281
+ <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1282
+ </label>
1283
+
1284
+ <label class="field">
1285
+ <span class="field-heading">
1286
+ <span>Port</span>
1287
+ ${this.renderOverrideBadge("port")}
1288
+ </span>
1289
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Yr(t)})}}>
1290
+ <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1291
+ </label>
1292
+
1293
+ <div class="field">
1294
+ <span class="field-heading">
1295
+ <span>Allowed hosts</span>
1296
+ ${this.renderOverrideBadge("allowedHosts")}
1297
+ </span>
1298
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Pg(t)==="all"?"all":"list"})}}>
1299
+ <option value="list">Only listed hosts</option>
1300
+ <option value="all">Allow every host</option>
1301
+ </select>
1302
+ <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:Cg(t)})}}></textarea>
1303
+ <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1304
+ </div>
1305
+
1306
+ ${this.renderEffectiveConfig()}
1307
+
1308
+ <footer class="form-actions">
1309
+ <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"Saving…":"Save config"}</button>
1310
+ </footer>
1311
+ </form>
1312
+ `}
1313
+ `}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}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">environment override</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1314
+ <section class="effective-card" aria-label="Effective configuration summary">
1315
+ <h3>Effective after environment overrides</h3>
1316
+ <dl>
1317
+ <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1318
+ <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1319
+ <div><dt>Allowed hosts</dt><dd>${$g(e.allowedHosts)}</dd></div>
1320
+ </dl>
1321
+ </section>
1322
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(yg(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Ig(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};se.styles=E`
1323
+ :host { display: block; }
1324
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1325
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1326
+ h2, h3, p { margin: 0; }
1327
+ h2 { font-size: 17px; line-height: 1.25; }
1328
+ h3 { font-size: 13px; line-height: 1.3; }
1329
+ p { color: var(--pi-muted); line-height: 1.45; }
1330
+ button, input, select, textarea { font: inherit; }
1331
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1332
+ button:disabled { opacity: .55; cursor: not-allowed; }
1333
+ .secondary { flex: 0 0 auto; }
1334
+ .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1335
+ .message { margin-bottom: 12px; }
1336
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1337
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1338
+ .loading-card { color: var(--pi-muted); }
1339
+ .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1340
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1341
+ 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; }
1342
+ .config-path-card small, .field small { color: var(--pi-muted); }
1343
+ .config-form { display: grid; gap: 14px; }
1344
+ .field { display: grid; gap: 7px; }
1345
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1346
+ input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; }
1347
+ input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1348
+ textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1349
+ textarea:disabled { opacity: .55; }
1350
+ .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; }
1351
+ .effective-card { display: grid; gap: 10px; }
1352
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
1353
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1354
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1355
+ .muted { color: var(--pi-muted); }
1356
+ .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1357
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1358
+
1359
+ @media (max-width: 760px) {
1360
+ .section-heading { display: grid; gap: 12px; }
1361
+ .section-heading .secondary { justify-self: start; }
1362
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1363
+ }
1364
+ `;Se([d({attribute:!1})],se.prototype,"configResponse",2);Se([d({type:Boolean})],se.prototype,"loading",2);Se([d({type:Boolean})],se.prototype,"saving",2);Se([d()],se.prototype,"error",2);Se([d()],se.prototype,"savedMessage",2);Se([d({attribute:!1})],se.prototype,"onReload",2);Se([d({attribute:!1})],se.prototype,"onSave",2);Se([x()],se.prototype,"draft",2);Se([x()],se.prototype,"localError",2);se=Se([A("settings-general-panel")],se);function $g(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 Yr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Pg(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Cg(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Ig(e){return e instanceof Error?e.message:String(e)}var Tg=Object.defineProperty,Mg=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Tg(t,i,r),r};let ge=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1365
+ <div class="section-heading">
1366
+ <div>
1367
+ <h2>Plugins</h2>
1368
+ <p>Enable or disable discovered PI WEB plugins. Changes apply after reloading the browser tab; already-loaded plugin code is not unloaded from the current page.</p>
1369
+ </div>
1370
+ <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1371
+ </div>
1372
+ ${this.renderMessages()}
1373
+ <div class="plugin-note">Config key: <code>plugins</code>. Plugins are enabled unless their entry sets <code>enabled</code> to <code>false</code>.</div>
1374
+ ${this.loading&&e.length===0?l`<div class="loading-card">Loading plugins…</div>`:e.length===0?l`<div class="loading-card">No external or bundled plugins discovered.</div>`:l`
1375
+ <div class="plugin-list">
1376
+ ${e.map(t=>this.renderPlugin(t))}
1377
+ </div>
1378
+ `}
1379
+ `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage} Reload the browser tab to apply plugin changes.</div>`:null}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"Config disabled":t?.enabled===!0?"Config enabled":"Default enabled";return l`
1380
+ <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1381
+ <div class="plugin-main">
1382
+ <strong>${e.id}</strong>
1383
+ <small>${e.source} · ${e.scope}</small>
1384
+ <small>${i}</small>
1385
+ </div>
1386
+ <label class="toggle">
1387
+ <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
1388
+ <span>${e.enabled?"Enabled":"Disabled"}</span>
1389
+ </label>
1390
+ </article>
1391
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};ge.styles=E`
1392
+ :host { display: block; }
1393
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1394
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1395
+ h2, p { margin: 0; }
1396
+ h2 { font-size: 17px; line-height: 1.25; }
1397
+ p { color: var(--pi-muted); line-height: 1.45; }
1398
+ button, input { font: inherit; }
1399
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1400
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1401
+ .secondary { flex: 0 0 auto; }
1402
+ .message, .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1403
+ .message { margin-bottom: 12px; }
1404
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1405
+ .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1406
+ .loading-card, .plugin-note { color: var(--pi-muted); }
1407
+ .plugin-note { margin-bottom: 14px; }
1408
+ 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; }
1409
+ .plugin-list { display: grid; gap: 10px; }
1410
+ .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
1411
+ .plugin-card.disabled { opacity: .75; }
1412
+ .plugin-main { min-width: 0; display: grid; gap: 3px; }
1413
+ .plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1414
+ .plugin-main small { color: var(--pi-muted); }
1415
+ .toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
1416
+ .toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
1417
+
1418
+ @media (max-width: 760px) {
1419
+ .section-heading { display: grid; gap: 12px; }
1420
+ .section-heading .secondary { justify-self: start; }
1421
+ .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1422
+ .toggle { justify-self: start; }
1423
+ }
1424
+ `;Me([d({attribute:!1})],ge.prototype,"pluginsResponse",2);Me([d({attribute:!1})],ge.prototype,"configResponse",2);Me([d({type:Boolean})],ge.prototype,"loading",2);Me([d({type:Boolean})],ge.prototype,"saving",2);Me([d()],ge.prototype,"error",2);Me([d()],ge.prototype,"savedMessage",2);Me([d({attribute:!1})],ge.prototype,"onReload",2);Me([d({attribute:!1})],ge.prototype,"onTogglePlugin",2);ge=Me([A("settings-plugins-panel")],ge);var Ag=Object.defineProperty,Rg=Object.getOwnPropertyDescriptor,Ns=(e,t,i,s)=>{for(var r=s>1?void 0:s?Rg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ag(t,i,r),r};let $t=class extends T{constructor(){super(...arguments),this.actions=[]}render(){const e=Eg(this.actions);return l`
1425
+ <div class="section-heading">
1426
+ <div>
1427
+ <h2>Keyboard shortcuts</h2>
1428
+ <p>Review registered app actions and the shortcut config that will become editable here. Manual config entries use action ids and can override a default shortcut or set it to <code>null</code> to disable it.</p>
1429
+ </div>
1430
+ </div>
1431
+ <div class="shortcut-note">Config key: <code>shortcuts</code>. Example: <code>{ "core:view.chat": "mod+1", "core:session.stop": null }</code></div>
1432
+ ${e.length===0?l`<div class="loading-card">No actions registered.</div>`:e.map(t=>l`
1433
+ <section class="shortcut-group">
1434
+ <h3>${t.name}</h3>
1435
+ <div class="shortcut-list">
1436
+ ${t.actions.map(i=>this.renderShortcutRow(i))}
1437
+ </div>
1438
+ </section>
1439
+ `)}
1440
+ `}renderShortcutRow(e){const t=this.configResponse?.config.shortcuts,i=yn(e.id,t),s=i===null?void 0:i??e.shortcut,r=_g(e,t);return l`
1441
+ <div class="shortcut-row">
1442
+ <div class="shortcut-main">
1443
+ <strong>${e.title}</strong>
1444
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1445
+ <small class="shortcut-id">${e.id}</small>
1446
+ </div>
1447
+ <div class="shortcut-value">
1448
+ ${s!==void 0&&s!==""?l`<kbd>${Oo(s)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"Disabled":"Unassigned"}</span>`}
1449
+ <small class=${r}>${Lg(r)}</small>
1450
+ </div>
1451
+ </div>
1452
+ `}};$t.styles=E`
1453
+ :host { display: block; }
1454
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1455
+ .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1456
+ h2, h3, p { margin: 0; }
1457
+ h2 { font-size: 17px; line-height: 1.25; }
1458
+ h3 { font-size: 13px; line-height: 1.3; }
1459
+ p { color: var(--pi-muted); line-height: 1.45; }
1460
+ 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; }
1461
+ .loading-card, .shortcut-note { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1462
+ .loading-card, .shortcut-note { color: var(--pi-muted); }
1463
+ .shortcut-note { margin-bottom: 14px; }
1464
+ .shortcut-group { margin: 0 0 16px; }
1465
+ .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1466
+ .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
1467
+ .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
1468
+ .shortcut-row:last-child { border-bottom: 0; }
1469
+ .shortcut-main { min-width: 0; display: grid; gap: 3px; }
1470
+ .shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1471
+ .shortcut-main small { color: var(--pi-muted); }
1472
+ .shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1473
+ .shortcut-value { justify-self: end; display: grid; justify-items: end; gap: 3px; }
1474
+ kbd { justify-self: end; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-bg); color: var(--pi-text-secondary); padding: 3px 7px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
1475
+ .unassigned { justify-self: end; color: var(--pi-muted); font-size: 12px; }
1476
+ .shortcut-value small { color: var(--pi-muted); font-size: 11px; }
1477
+ .shortcut-value small.custom { color: var(--pi-accent); }
1478
+ .shortcut-value small.disabled { color: var(--pi-warning); }
1479
+
1480
+ @media (max-width: 760px) {
1481
+ .section-heading { display: grid; gap: 12px; }
1482
+ .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1483
+ .shortcut-value { justify-self: start; justify-items: start; }
1484
+ kbd, .unassigned { justify-self: start; }
1485
+ }
1486
+ `;Ns([d({attribute:!1})],$t.prototype,"actions",2);Ns([d({attribute:!1})],$t.prototype,"configResponse",2);$t=Ns([A("settings-shortcuts-panel")],$t);function Eg(e){const t=new Map;for(const i of[...e].sort(Dg)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Dg(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function yn(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function _g(e,t){const i=yn(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Lg(e){switch(e){case"default":return"Default";case"custom":return"Config override";case"disabled":return"Config disabled";case"unassigned":return"No default"}}var Og=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,le=(e,t,i,s)=>{for(var r=s>1?void 0:s?Wg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Og(t,i,r),r};let J=class extends T{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`
1487
+ <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1488
+ <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1489
+ <header class="settings-header">
1490
+ <div>
1491
+ <span class="eyebrow">Settings</span>
1492
+ <h1>PI WEB</h1>
1493
+ </div>
1494
+ <button class="close-button" title="Close settings" aria-label="Close settings" @click=${()=>this.onClose?.()}>×</button>
1495
+ </header>
1496
+ <div class="settings-body">
1497
+ <nav class="settings-nav" aria-label="Settings sections">
1498
+ ${this.renderNavButton("general","General","Server config")}
1499
+ ${this.renderNavButton("plugins","Plugins","Enable and disable")}
1500
+ ${this.renderNavButton("shortcuts","Keyboard","Shortcuts")}
1501
+ </nav>
1502
+ <main class="settings-content">
1503
+ ${this.renderActiveSection()}
1504
+ </main>
1505
+ </div>
1506
+ </section>
1507
+ </div>
1508
+ `}renderActiveSection(){return this.section==="shortcuts"?l`<settings-shortcuts-panel .actions=${this.actions} .configResponse=${this.configResponse}></settings-shortcuts-panel>`:this.section==="plugins"?l`
1509
+ <settings-plugins-panel
1510
+ .configResponse=${this.configResponse}
1511
+ .pluginsResponse=${this.pluginsResponse}
1512
+ .loading=${this.loading}
1513
+ .saving=${this.saving}
1514
+ .error=${this.error}
1515
+ .savedMessage=${this.savedMessage}
1516
+ .onReload=${()=>this.loadConfig()}
1517
+ .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
1518
+ ></settings-plugins-panel>
1519
+ `:l`
1520
+ <settings-general-panel
1521
+ .configResponse=${this.configResponse}
1522
+ .loading=${this.loading}
1523
+ .saving=${this.saving}
1524
+ .error=${this.error}
1525
+ .savedMessage=${this.savedMessage}
1526
+ .onReload=${()=>this.loadConfig()}
1527
+ .onSave=${e=>this.saveConfig(e)}
1528
+ ></settings-general-panel>
1529
+ `}renderNavButton(e,t,i){const s=this.section===e;return l`
1530
+ <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
1531
+ <strong>${t}</strong>
1532
+ <small>${i}</small>
1533
+ </button>
1534
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Yt.config(),Ki.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${Bi(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Yt.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${Bi(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Ki.plugins()}catch(e){this.error=`Failed to refresh plugins: ${Bi(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?.())}};J.styles=E`
1535
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1536
+ .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; }
1537
+ .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; }
1538
+ .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
1539
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1540
+ h1 { margin: 0; font-size: 20px; line-height: 1.2; }
1541
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1542
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1543
+ .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
1544
+ .settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
1545
+ .settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
1546
+ .settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
1547
+ .settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
1548
+ .settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1549
+ .settings-nav small { color: var(--pi-muted); }
1550
+ .settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
1551
+
1552
+ @media (max-width: 760px) {
1553
+ .backdrop { padding: 0; place-items: stretch; }
1554
+ .settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
1555
+ .settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
1556
+ .settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
1557
+ .settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
1558
+ .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1559
+ .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1560
+ }
1561
+ `;le([d({attribute:!1})],J.prototype,"section",2);le([d({attribute:!1})],J.prototype,"actions",2);le([d({attribute:!1})],J.prototype,"onNavigate",2);le([d({attribute:!1})],J.prototype,"onClose",2);le([d({attribute:!1})],J.prototype,"onConfigSaved",2);le([x()],J.prototype,"configResponse",2);le([x()],J.prototype,"pluginsResponse",2);le([x()],J.prototype,"loading",2);le([x()],J.prototype,"saving",2);le([x()],J.prototype,"error",2);le([x()],J.prototype,"savedMessage",2);J=le([A("settings-dialog")],J);function Bi(e){return e instanceof Error?e.message:String(e)}var jg=Object.defineProperty,Ng=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ng(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&jg(t,i,r),r};let Q=class extends T{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],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(){const e=this.workspace;if(e===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(r=>r.id===this.tool)??i[0];return l`
1562
+ <header>
1563
+ <div class=${this.workspaceHeaderFrameClass()}>
1564
+ <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
1565
+ ${this.hideToolTabs?null:l`
1566
+ <div class="tabs">
1567
+ ${i.map(r=>{const o=s?.id===r.id,n=r.badge?.(t),a=this.panelTabAriaLabel(r,n);return l`
1568
+ <button class=${this.panelTabClass(r,o)} title=${a} aria-label=${a} aria-pressed=${String(o)} @click=${()=>{this.onSelectTool(r.id)}}>
1569
+ ${this.renderPanelTabContent(r,n)}
1570
+ </button>
1571
+ `})}
1572
+ </div>
1573
+ `}
1574
+ <small>${en(e.label,this.workspaceLabelItems,e.path)}</small>
1575
+ </div>
1576
+ </div>
1577
+ </header>
1578
+ ${s===void 0?this.renderEmptyState({title:"No workspace tools available",body:"No tools are available for this workspace."}):l`
1579
+ <div class="panel-content">
1580
+ ${s.render(t)}
1581
+ </div>
1582
+ `}
1583
+ `}panelTabClass(e,t){return[...e.icon===void 0?[]:["icon-tab"],...t?["selected"]:[]].join(" ")}panelTabAriaLabel(e,t){if(typeof t!="string"&&typeof t!="number")return e.title;const i=String(t).trim();return i===""?e.title:`${e.title}, ${i}`}renderPanelTabContent(e,t){return l`
1584
+ ${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
1585
+ <span class="tab-label">${e.title}</span>
1586
+ ${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
1587
+ `}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
1588
+ <section class="empty-state" role="status">
1589
+ <h2>${e.title}</h2>
1590
+ ${e.body===void 0?null:l`<p>${e.body}</p>`}
1591
+ </section>
1592
+ `}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}};Q.styles=$h;ce([d({attribute:!1})],Q.prototype,"workspace",2);ce([d({attribute:!1})],Q.prototype,"panelContext",2);ce([d({attribute:!1})],Q.prototype,"emptyState",2);ce([d()],Q.prototype,"tool",2);ce([d({attribute:!1})],Q.prototype,"panels",2);ce([d({attribute:!1})],Q.prototype,"workspaceLabelItems",2);ce([d({type:Boolean})],Q.prototype,"hideToolTabs",2);ce([d({attribute:!1})],Q.prototype,"onSelectTool",2);ce([re(".workspace-header-strip")],Q.prototype,"workspaceHeaderStrip",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollLeft",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollRight",2);Q=ce([A("workspace-panel")],Q);var Fg=Object.defineProperty,Bg=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var r=s>1?void 0:s?Bg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Fg(t,i,r),r};let Z=class extends T{constructor(){super(...arguments),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=zg(this.machine),t=Hg(this.project),i=Vg(this.workspace),s=Gg(this.session);return l`
1593
+ <nav class=${this.contextBarClass()} aria-label="Current location">
1594
+ <span class="context-bar-label">Location</span>
1595
+ <ol class="context-items" @scroll=${this.onContextScroll}>
1596
+ <li class="context-item">
1597
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Ug(this.machine)} aria-label=${`Machine: ${e}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
1598
+ <span class="context-kind">Machine</span>
1599
+ ${this.renderMachineActivity()}
1600
+ <span class="context-value">${e}</span>
1601
+ </button>
1602
+ </li>
1603
+ <li class="context-item">
1604
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${qg(this.project)} aria-label=${`Project: ${t}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
1605
+ <span class="context-kind">Project</span>
1606
+ <span class="context-value">${t}</span>
1607
+ </button>
1608
+ </li>
1609
+ <li class="context-item">
1610
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Kg(this.workspace)} aria-label=${`Workspace: ${i}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1611
+ <span class="context-kind">Workspace</span>
1612
+ <span class="context-value">${i}</span>
1613
+ </button>
1614
+ </li>
1615
+ <li class="context-item">
1616
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Jg(this.session)} aria-label=${`Session: ${s}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1617
+ <span class="context-kind">Session</span>
1618
+ <span class="context-value">${s}</span>
1619
+ </button>
1620
+ </li>
1621
+ </ol>
1622
+ ${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
1623
+ </nav>
1624
+ `}renderMachineActivity(){return At(this.machineActivityKind,this.machineActivityKind==="terminal"?"Machine terminal active":"Machine active")}renderActionsButton(){return this.onShowActions===void 0?null:l`
1625
+ <button type="button" class="context-action-button" title="Show Actions" aria-label="Show Actions" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
1626
+ <svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1627
+ <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1628
+ </svg>
1629
+ </button>
1630
+ `}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}};Z.styles=E`
1631
+ /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1632
+ :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1633
+ .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); }
1634
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
1635
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1636
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1637
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
1638
+ .context-bar-label { display: none; }
1639
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
1640
+ .context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
1641
+ .context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
1642
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
1643
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--pi-bg); pointer-events: none; }
1644
+ .context-actions::before { content: ""; position: absolute; top: 0; bottom: 0; left: -24px; z-index: 0; width: 24px; background: linear-gradient(90deg, transparent, var(--pi-bg)); pointer-events: none; }
1645
+ app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
1646
+ .context-action-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; }
1647
+ .context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1648
+ .context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
1649
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
1650
+ .context-chip:hover { background: var(--pi-surface-hover); }
1651
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
1652
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
1653
+ .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; margin-right: 0; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
1654
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
1655
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
1656
+ .context-kind { display: none; }
1657
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1658
+ button { cursor: pointer; }
1659
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
1660
+ `;de([d({attribute:!1})],Z.prototype,"machine",2);de([d({attribute:!1})],Z.prototype,"machineActivityKind",2);de([d({attribute:!1})],Z.prototype,"project",2);de([d({attribute:!1})],Z.prototype,"workspace",2);de([d({attribute:!1})],Z.prototype,"session",2);de([d({attribute:!1})],Z.prototype,"refreshControl",2);de([d({attribute:!1})],Z.prototype,"onOpenSection",2);de([d({attribute:!1})],Z.prototype,"onShowActions",2);de([re(".context-items")],Z.prototype,"contextItems",2);de([x()],Z.prototype,"canScrollLeft",2);de([x()],Z.prototype,"canScrollRight",2);Z=de([A("app-context-bar")],Z);function zg(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function Ug(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Hg(e){return e?.name??"No project"}function qg(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function Vg(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Kg(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function Gg(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 Jg(e){return e===void 0?"No session selected":e.path}var Qg=Object.defineProperty,Zg=Object.getOwnPropertyDescriptor,Ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?Zg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Qg(t,i,r),r};let Ce=class extends T{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`
1661
+ <div class=${this.frameClass()}>
1662
+ <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1663
+ ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
1664
+ <button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
1665
+ ${this.renderTabMark(t,e)}
1666
+ <span class="tab-label">${t.label}</span>
1667
+ ${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
1668
+ </button>
1669
+ `})}
1670
+ </div>
1671
+ </div>
1672
+ `}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>`:ap(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}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}};Ce.styles=E`
1673
+ :host { flex: 0 0 auto; min-width: 0; }
1674
+ .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); }
1675
+ .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; }
1676
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1677
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1678
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
1679
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
1680
+ .mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
1681
+ .mobile-tabs .navigation-tab { display: none; }
1682
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1683
+ .tab-icon { flex: 0 0 auto; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1684
+ .tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
1685
+ .tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
1686
+ .tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
1687
+ .tab-label { min-width: 0; }
1688
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; margin-left: 0; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
1689
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1690
+ @media (max-width: 760px) {
1691
+ .mobile-tabs { gap: 4px; padding: 6px 8px; }
1692
+ .mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
1693
+ .mobile-tabs .navigation-tab { display: inline-flex; }
1694
+ .tab-fallback { display: inline-block; }
1695
+ .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; }
1696
+ .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1697
+ }
1698
+ `;Ve([d({attribute:!1})],Ce.prototype,"tabs",2);Ve([d({attribute:!1})],Ce.prototype,"selectedView",2);Ve([d({attribute:!1})],Ce.prototype,"onSelect",2);Ve([re(".mobile-tabs")],Ce.prototype,"mobileTabs",2);Ve([x()],Ce.prototype,"canScrollLeft",2);Ve([x()],Ce.prototype,"canScrollRight",2);Ce=Ve([A("app-mobile-main-tabs")],Ce);var Xg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,C=(e,t,i,s)=>{for(var r=s>1?void 0:s?Yg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Xg(t,i,r),r};let P=class extends T{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.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1}render(){return l`
1699
+ <header>
1700
+ <strong>PI WEB</strong>
1701
+ <div class="header-actions">
1702
+ ${this.refreshControl}
1703
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
1704
+ </div>
1705
+ </header>
1706
+ ${em(this.machines)?l`
1707
+ <machine-list
1708
+ .machines=${this.machines}
1709
+ .selected=${this.selectedMachine}
1710
+ .statuses=${this.machineStatuses}
1711
+ .activities=${this.machineActivities}
1712
+ .collapsible=${this.collapsible}
1713
+ .collapsed=${this.machinesCollapsed}
1714
+ .onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
1715
+ .onSelect=${e=>this.onSelectMachine?.(e)}
1716
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
1717
+ ></machine-list>
1718
+ `:null}
1719
+ <project-list
1720
+ .projects=${this.projects}
1721
+ .selected=${this.selectedProject}
1722
+ .activities=${this.workspaceActivities}
1723
+ .workspacesByProjectId=${this.workspacesByProjectId}
1724
+ .collapsible=${this.collapsible}
1725
+ .collapsed=${this.projectsCollapsed}
1726
+ .onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
1727
+ .onSelect=${e=>this.onSelectProject?.(e)}
1728
+ .onClose=${e=>this.onCloseProject?.(e)}
1729
+ ></project-list>
1730
+ <workspace-list
1731
+ .workspaces=${this.workspaces}
1732
+ .selected=${this.selectedWorkspace}
1733
+ .activities=${this.workspaceActivities}
1734
+ .deletingWorkspaceIds=${this.deletingWorkspaceIds}
1735
+ .collapsible=${this.collapsible}
1736
+ .collapsed=${this.workspacesCollapsed}
1737
+ .workspaceLabelItems=${this.workspaceLabelItems}
1738
+ .onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
1739
+ .onSelect=${e=>this.onSelectWorkspace?.(e)}
1740
+ .onDelete=${e=>this.onDeleteWorkspace?.(e)}
1741
+ ></workspace-list>
1742
+ <session-list
1743
+ .sessions=${this.sessions}
1744
+ .statuses=${this.sessionStatuses}
1745
+ .activities=${this.sessionActivities}
1746
+ .selected=${this.selectedSession}
1747
+ .canStart=${this.canStartSession}
1748
+ .collapsible=${this.collapsible}
1749
+ .collapsed=${this.sessionsCollapsed}
1750
+ .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
1751
+ .onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
1752
+ .onStart=${()=>this.onStartSession?.()}
1753
+ .onSelect=${e=>this.onSelectSession?.(e)}
1754
+ .onArchive=${e=>this.onArchiveSession?.(e)}
1755
+ .onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
1756
+ .onRestore=${e=>this.onRestoreSession?.(e)}
1757
+ .onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
1758
+ .onDetachParent=${e=>this.onDetachParentSession?.(e)}
1759
+ ></session-list>
1760
+ `}};P.styles=E`
1761
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
1762
+ :host([collapsible]) { flex: 1 1 auto; }
1763
+ 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); }
1764
+ :host([collapsible]) header { display: none; }
1765
+ .header-actions { display: flex; align-items: center; gap: 8px; }
1766
+ machine-list, project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
1767
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
1768
+ :host([collapsible]) machine-list,
1769
+ :host([collapsible]) project-list,
1770
+ :host([collapsible]) workspace-list,
1771
+ :host([collapsible]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
1772
+ :host([collapsible]) machine-list[collapsed],
1773
+ :host([collapsible]) project-list[collapsed],
1774
+ :host([collapsible]) workspace-list[collapsed],
1775
+ :host([collapsible]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1776
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1777
+ `;C([d({attribute:!1})],P.prototype,"machines",2);C([d({attribute:!1})],P.prototype,"selectedMachine",2);C([d({attribute:!1})],P.prototype,"machineStatuses",2);C([d({attribute:!1})],P.prototype,"machineActivities",2);C([d({attribute:!1})],P.prototype,"projects",2);C([d({attribute:!1})],P.prototype,"selectedProject",2);C([d({attribute:!1})],P.prototype,"workspaces",2);C([d({attribute:!1})],P.prototype,"selectedWorkspace",2);C([d({attribute:!1})],P.prototype,"sessions",2);C([d({attribute:!1})],P.prototype,"selectedSession",2);C([d({attribute:!1})],P.prototype,"workspaceActivities",2);C([d({attribute:!1})],P.prototype,"sessionActivities",2);C([d({attribute:!1})],P.prototype,"sessionStatuses",2);C([d({attribute:!1})],P.prototype,"workspacesByProjectId",2);C([d({attribute:!1})],P.prototype,"deletingWorkspaceIds",2);C([d({attribute:!1})],P.prototype,"workspaceLabelItems",2);C([d({attribute:!1})],P.prototype,"refreshControl",2);C([d({type:Boolean,reflect:!0})],P.prototype,"collapsible",2);C([d({type:Boolean})],P.prototype,"machinesCollapsed",2);C([d({type:Boolean})],P.prototype,"projectsCollapsed",2);C([d({type:Boolean})],P.prototype,"workspacesCollapsed",2);C([d({type:Boolean})],P.prototype,"sessionsCollapsed",2);C([d({type:Boolean})],P.prototype,"canStartSession",2);C([d({attribute:!1})],P.prototype,"onShowActions",2);C([d({attribute:!1})],P.prototype,"onToggleMachines",2);C([d({attribute:!1})],P.prototype,"onToggleProjects",2);C([d({attribute:!1})],P.prototype,"onToggleWorkspaces",2);C([d({attribute:!1})],P.prototype,"onToggleSessions",2);C([d({attribute:!1})],P.prototype,"onSelectProject",2);C([d({attribute:!1})],P.prototype,"onCloseProject",2);C([d({attribute:!1})],P.prototype,"onSelectWorkspace",2);C([d({attribute:!1})],P.prototype,"onDeleteWorkspace",2);C([d({attribute:!1})],P.prototype,"onStartSession",2);C([d({attribute:!1})],P.prototype,"onSelectSession",2);C([d({attribute:!1})],P.prototype,"onArchiveSession",2);C([d({attribute:!1})],P.prototype,"onArchiveSessionWithDescendants",2);C([d({attribute:!1})],P.prototype,"onRestoreSession",2);C([d({attribute:!1})],P.prototype,"onDeleteCachedNewSession",2);C([d({attribute:!1})],P.prototype,"onDetachParentSession",2);C([d({attribute:!1})],P.prototype,"onArchivedCollapsed",2);C([d({attribute:!1})],P.prototype,"onSelectMachine",2);C([d({attribute:!1})],P.prototype,"onRemoveMachine",2);P=C([A("app-navigation-panel")],P);function em(e){return e.length>1}var tm=Object.defineProperty,im=Object.getOwnPropertyDescriptor,Ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?im(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&tm(t,i,r),r};let Ie=class extends T{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.controls="",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel"}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
1778
+ <button
1779
+ type="button"
1780
+ class="edge-button"
1781
+ title=${e}
1782
+ aria-label=${e}
1783
+ aria-controls=${this.controls}
1784
+ aria-expanded=${String(!this.collapsed)}
1785
+ @click=${()=>{this.onToggle?.()}}
1786
+ >${this.renderIcon()}</button>
1787
+ `}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"}};Ie.styles=E`
1788
+ :host { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
1789
+ :host([side="navigation"]) { grid-column: 2; }
1790
+ :host([side="workspace"]) { grid-column: 4; }
1791
+ .edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
1792
+ .edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
1793
+ :host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
1794
+ :host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
1795
+ .edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1796
+ @media (max-width: 1180px) {
1797
+ :host([side="navigation"]) { grid-row: 1 / 3; }
1798
+ :host([side="workspace"]) { display: none; }
1799
+ }
1800
+ @media (max-width: 760px) {
1801
+ :host([side="navigation"]) { display: none; }
1802
+ }
1803
+ `;Ke([d({reflect:!0})],Ie.prototype,"side",2);Ke([d({type:Boolean,reflect:!0})],Ie.prototype,"collapsed",2);Ke([d()],Ie.prototype,"controls",2);Ke([d()],Ie.prototype,"expandLabel",2);Ke([d()],Ie.prototype,"collapseLabel",2);Ke([d({attribute:!1})],Ie.prototype,"onToggle",2);Ie=Ke([A("app-panel-edge-control")],Ie);var sm=Object.defineProperty,rm=Object.getOwnPropertyDescriptor,_t=(e,t,i,s)=>{for(var r=s>1?void 0:s?rm(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&sm(t,i,r),r};const om=550,eo="pi-web-app-refresh-menu-portal-style";let Ue=class extends T{constructor(){super(...arguments),this.isRefreshing=!1,this.menuOpen=!1,this.menuStyle="",this.suppressNextClick=!1,this.onRefreshClick=e=>{if(e.stopPropagation(),this.suppressNextClick){this.suppressNextClick=!1;return}this.refresh()},this.onRefreshPointerDown=e=>{if(!e.isPrimary||e.button!==0)return;const t=e.currentTarget;t instanceof HTMLElement&&(this.clearLongPressTimer(),this.suppressNextClick=!1,this.longPressTimer=window.setTimeout(()=>{this.longPressTimer=void 0,this.suppressNextClick=!0,this.openMenu(t)},om))},this.onRefreshContextMenu=e=>{e.preventDefault(),e.stopPropagation(),this.clearLongPressTimer(),this.suppressNextClick=!0,this.openMenu(e.currentTarget)},this.onDocumentClick=e=>{const t=e.composedPath();t.includes(this)||this.menuPortal!==void 0&&t.includes(this.menuPortal)||this.closeMenu()},this.onDocumentKeyDown=e=>{e.key!=="Escape"||!this.menuOpen||(e.preventDefault(),e.stopPropagation(),this.closeMenu())},this.onPortalMenuClick=e=>{e.stopPropagation()}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick),document.addEventListener("keydown",this.onDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),document.removeEventListener("keydown",this.onDocumentKeyDown),this.clearLongPressTimer(),this.removePortalMenu(),super.disconnectedCallback()}render(){const e=this.isRefreshing?"Refreshing app data. Long-press for reload options.":"Refresh app data. Long-press for reload options.";return l`
1804
+ <button
1805
+ class=${`app-refresh-button${this.isRefreshing?" refreshing":""}`}
1806
+ title=${e}
1807
+ aria-label=${e}
1808
+ aria-haspopup="menu"
1809
+ aria-expanded=${String(this.menuOpen)}
1810
+ aria-busy=${String(this.isRefreshing)}
1811
+ @click=${this.onRefreshClick}
1812
+ @contextmenu=${this.onRefreshContextMenu}
1813
+ @pointerdown=${this.onRefreshPointerDown}
1814
+ @pointerup=${()=>{this.clearLongPressTimer()}}
1815
+ @pointercancel=${()=>{this.clearLongPressTimer()}}
1816
+ @pointerleave=${()=>{this.clearLongPressTimer()}}
1817
+ >${this.renderRefreshIcon()}</button>
1818
+ `}renderRefreshIcon(){return l`
1819
+ <svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1820
+ <path d="M20 6v5h-5"></path>
1821
+ <path d="M4 18v-5h5"></path>
1822
+ <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
1823
+ <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
1824
+ </svg>
1825
+ `}openMenu(e){this.menuStyle=Mt(e,{constrainTo:"viewport"}),this.menuOpen=!0,this.renderPortalMenu()}closeMenu(){this.menuOpen=!1,this.suppressNextClick=!1,this.removePortalMenu()}refresh(){this.closeMenu(),this.onRefresh?.()}reload(){this.closeMenu(),this.onReload?.()}clearLongPressTimer(){this.longPressTimer!==void 0&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=void 0)}renderPortalMenu(){const e=this.ownerDocument;nm(e);const t=this.menuPortal??e.createElement("div");this.menuPortal=t,t.className="pi-web-app-refresh-menu-portal",t.setAttribute("role","menu"),t.setAttribute("style",this.menuStyle),t.replaceChildren(this.createPortalMenuButton("Refresh app data",()=>{this.refresh()}),this.createPortalMenuButton("Full page reload",()=>{this.reload()})),t.addEventListener("click",this.onPortalMenuClick),t.isConnected||e.body.append(t)}createPortalMenuButton(e,t){const i=this.ownerDocument.createElement("button");return i.type="button",i.setAttribute("role","menuitem"),i.textContent=e,i.addEventListener("click",s=>{s.stopPropagation(),t()}),i}removePortalMenu(){this.menuPortal?.removeEventListener("click",this.onPortalMenuClick),this.menuPortal?.remove(),this.menuPortal=void 0}};Ue.styles=E`
1826
+ :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; }
1827
+ :host, :host * { -webkit-user-select: none; user-select: none; }
1828
+ .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; }
1829
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1830
+ .app-refresh-button.refreshing .app-refresh-icon { animation: app-refresh-spin .8s linear infinite; }
1831
+ @keyframes app-refresh-spin { to { transform: rotate(360deg); } }
1832
+ `;_t([d({type:Boolean})],Ue.prototype,"isRefreshing",2);_t([d({attribute:!1})],Ue.prototype,"onRefresh",2);_t([d({attribute:!1})],Ue.prototype,"onReload",2);_t([x()],Ue.prototype,"menuOpen",2);Ue=_t([A("app-refresh-control")],Ue);function nm(e){if(e.getElementById(eo)!==null)return;const t=e.createElement("style");t.id=eo,t.textContent=`
1833
+ .pi-web-app-refresh-menu-portal {
1834
+ position: fixed;
1835
+ z-index: 2147483647;
1836
+ box-sizing: border-box;
1837
+ min-width: min(170px, calc(100vw - 16px));
1838
+ overflow: auto;
1839
+ padding: 4px;
1840
+ border: 1px solid var(--pi-border);
1841
+ border-radius: 8px;
1842
+ background: var(--pi-surface);
1843
+ color: var(--pi-text);
1844
+ box-shadow: 0 8px 24px var(--pi-shadow);
1845
+ overflow-wrap: anywhere;
1846
+ font: 14px system-ui, sans-serif;
1847
+ -webkit-touch-callout: none;
1848
+ -webkit-user-select: none;
1849
+ user-select: none;
1850
+ }
1851
+ .pi-web-app-refresh-menu-portal button {
1852
+ display: block;
1853
+ width: 100%;
1854
+ border: 0;
1855
+ border-radius: 8px;
1856
+ background: transparent;
1857
+ color: var(--pi-text);
1858
+ padding: 7px 9px;
1859
+ text-align: left;
1860
+ white-space: normal;
1861
+ overflow-wrap: anywhere;
1862
+ font: inherit;
1863
+ cursor: pointer;
1864
+ }
1865
+ .pi-web-app-refresh-menu-portal button:hover,
1866
+ .pi-web-app-refresh-menu-portal button:focus {
1867
+ background: var(--pi-selection-bg);
1868
+ }
1869
+ `,e.head.append(t)}var am=Object.defineProperty,lm=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?lm(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&am(t,i,r),r};const cm=900*1e3,to={capture:!0},zi="auto:on",io="auto:off",zt="theme:",Ui=Pt("core:workspace.files"),Hi=Pt("core:workspace.git"),Ut=Pt("core:workspace.terminal");let we=class extends T{constructor(){super(...arguments),this.state=Pl(),this.sessions=new ad(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new td),this.activity=new Cl(()=>this.state,e=>{this.setState(e)}),this.auth=new Ml(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new vd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gd),this.projects=new Nl(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Wl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Dl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Ol(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Ad,this.realtime=new br,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new xd,this.terminalSelection=new Td,this.appShell=new Zp(this),this.panelCollapse=new rh(this),this.mobileNavigation=new sh(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.plugins=dm(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=jd()??Ld,this.activeThemeId=Ss,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.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.keyboard.handle(e,this.getActions())&&(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,to),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},cm),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute()}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,to),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.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!fm(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),pm(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Tr();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await wo.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}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=>xn(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 Yt.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.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}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(Tr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=e.projectId===void 0||e.projectId===""?oo():i,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await n,!this.isCurrentRouteRestore(o))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 a=this.state.projects.find(c=>c.id===e.projectId);if(!a){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(a,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))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)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?oo():{selectedFilePath:Ti(Ui,"file"),selectedDiffPath:Ti(Hi,"diff"),selectedTerminalId:Ti(Ut,"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){Ei(e,{replace:!0}),pe(Ui,"file",void 0,{replace:!0}),pe(Hi,"diff",void 0,{replace:!0}),pe(Ut,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.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 bm(),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(),Ei({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(wr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(wr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ei(yr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){pe(Ui,"file",e.selectedFilePath,{replace:!0}),pe(Hi,"diff",e.selectedDiffPath,{replace:!0}),pe(Ut,"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)??Sd(e.id);if(await this.restoreRouteFor(yr(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=no(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=ph(e,{api:{runTerminalCommand:(o,n)=>et.runTerminalCommand(o,n,t),listCommandRuns:o=>et.listCommandRuns(o,t),getCommandRun:o=>et.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}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){pe(Ut,"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,Di(e)}closeSettings(){this.settingsSection=void 0,Di(void 0)}navigateSettings(e){this.settingsSection=e,Di(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 br;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=>hm(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):gm(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 et.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=ro(e),s=ro(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),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.workspaceLabelItems(e),s=e===void 0?this.workspacePanelEmptyState():void 0;return l`
1870
+ <workspace-panel
1871
+ id="workspace-panel"
1872
+ .workspace=${e}
1873
+ .panelContext=${t}
1874
+ .emptyState=${s}
1875
+ .tool=${this.state.workspaceTool}
1876
+ .panels=${this.visibleWorkspacePanels()}
1877
+ .workspaceLabelItems=${i}
1878
+ .onSelectTool=${r=>{this.openWorkspaceTool(r)}}
1879
+ ></workspace-panel>
1880
+ `}renderNavigationPanelEdgeControl(){return l`
1881
+ <app-panel-edge-control
1882
+ side="navigation"
1883
+ controls="navigation-panel"
1884
+ expandLabel="Expand navigation panel"
1885
+ collapseLabel="Collapse navigation panel"
1886
+ .collapsed=${this.panelCollapse.navigationPanelCollapsed}
1887
+ .onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
1888
+ ></app-panel-edge-control>
1889
+ `}renderWorkspacePanelEdgeControl(){return l`
1890
+ <app-panel-edge-control
1891
+ side="workspace"
1892
+ controls="workspace-panel"
1893
+ expandLabel="Expand workspace panel"
1894
+ collapseLabel="Collapse workspace panel"
1895
+ .collapsed=${this.panelCollapse.workspacePanelCollapsed}
1896
+ .onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
1897
+ ></app-panel-edge-control>
1898
+ `}renderNavigationPanel(e){const t=i=>this.withChatScrollTransition(async()=>{await i(),e&&this.setState({mainView:"chat"}),e&&this.updateUrl()});return l`
1899
+ <app-navigation-panel
1900
+ .machines=${this.state.machines}
1901
+ .selectedMachine=${this.state.selectedMachine}
1902
+ .machineStatuses=${this.state.machineStatuses}
1903
+ .machineActivities=${this.state.machineActivities}
1904
+ .machinesCollapsed=${this.mobileNavigation.isCollapsed("machines")}
1905
+ .onToggleMachines=${()=>{this.mobileNavigation.toggle("machines")}}
1906
+ .onSelectMachine=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("projects"),await this.selectMachineWithMemory(i)})}
1907
+ .onRemoveMachine=${i=>{this.removeMachine(i)}}
1908
+ .projects=${this.state.projects}
1909
+ .selectedProject=${this.state.selectedProject}
1910
+ .workspaceActivities=${this.state.workspaceActivities}
1911
+ .workspacesByProjectId=${this.state.workspacesByProjectId}
1912
+ .workspaces=${this.state.workspaces}
1913
+ .selectedWorkspace=${this.state.selectedWorkspace}
1914
+ .deletingWorkspaceIds=${Xd(this.state.workspaceDeletionRuns)}
1915
+ .sessions=${this.state.sessions}
1916
+ .sessionStatuses=${this.state.sessionStatuses}
1917
+ .sessionActivities=${this.state.sessionActivities}
1918
+ .selectedSession=${this.state.selectedSession}
1919
+ .canStartSession=${!!this.state.selectedWorkspace}
1920
+ .collapsible=${this.appShell.isMobileNavigationLayout}
1921
+ .projectsCollapsed=${this.mobileNavigation.isCollapsed("projects")}
1922
+ .workspacesCollapsed=${this.mobileNavigation.isCollapsed("workspaces")}
1923
+ .sessionsCollapsed=${this.mobileNavigation.isCollapsed("sessions")}
1924
+ .workspaceLabelItems=${i=>this.workspaceLabelItems(i)}
1925
+ .refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
1926
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
1927
+ .onToggleProjects=${()=>{this.mobileNavigation.toggle("projects")}}
1928
+ .onToggleWorkspaces=${()=>{this.mobileNavigation.toggle("workspaces")}}
1929
+ .onToggleSessions=${()=>{this.mobileNavigation.toggle("sessions")}}
1930
+ .onSelectProject=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("workspaces"),await this.workspaces.selectProject(i)})}
1931
+ .onCloseProject=${i=>this.projects.closeProject(i.id)}
1932
+ .onSelectWorkspace=${i=>this.withChatScrollTransition(async()=>{this.mobileNavigation.expand("sessions"),await this.workspaces.selectWorkspace(i)})}
1933
+ .onDeleteWorkspace=${i=>{this.deleteWorkspace(i)}}
1934
+ .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
1935
+ .onStartSession=${()=>t(()=>this.sessions.startSession())}
1936
+ .onSelectSession=${i=>t(()=>this.sessions.selectSession(i))}
1937
+ .onArchiveSession=${i=>this.sessions.archiveSession(i)}
1938
+ .onArchiveSessionWithDescendants=${i=>this.sessions.archiveSessionWithDescendants(i)}
1939
+ .onRestoreSession=${i=>t(()=>this.sessions.restoreSession(i))}
1940
+ .onDeleteCachedNewSession=${i=>this.sessions.deleteCachedNewSession(i)}
1941
+ .onDetachParentSession=${i=>this.sessions.detachParent(i)}
1942
+ ></app-navigation-panel>
1943
+ `}openNavigationSection(e){this.mobileNavigation.open(e,()=>{this.selectMainView("navigation")})}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=so(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=>Gi.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=so(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return Np({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},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 lh(this.plugins.getActions(this.createPluginRuntimeContext()),this.shortcutConfig)}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Cr())}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}`,()=>Cr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id})).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(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>jp({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:()=>this.machines.refreshMachineHealth(),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(!bd(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Bo(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
1944
+
1945
+ This will run git worktree remove and delete:
1946
+ ${e.path}
1947
+
1948
+ The Git branch will not be deleted.`))return;const s=g(this.state);try{const r=await Gi.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(g(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${mm(r)}`})}}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=Yi(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(Qd(t.id));if(g(this.state)!==e)return;const s=Zd(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))ni(r)||await this.handleCompletedWorkspaceDeletionRun(r,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(ni);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=no(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Yi(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:vm(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})}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
1949
+
1950
+ 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 r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ current":""}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?io:zi;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${zt}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${zt}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===zi||e===io){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===zi},this.applyPreferredTheme(!0);return}if(!e.startsWith(zt))return;const t=e.slice(zt.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,Fd(t),e&&Nd(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Bd({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Fo(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:ym(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),wm(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`
1951
+ <app-context-bar
1952
+ .machine=${this.state.selectedMachine}
1953
+ .machineActivityKind=${um(this.state)}
1954
+ .project=${this.state.selectedProject}
1955
+ .workspace=${this.state.selectedWorkspace}
1956
+ .session=${this.state.selectedSession}
1957
+ .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
1958
+ .onOpenSection=${e=>{this.openNavigationSection(e)}}
1959
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
1960
+ ></app-context-bar>
1961
+ `:null}renderMobileMainTabs(){return l`
1962
+ <app-mobile-main-tabs
1963
+ .tabs=${this.mobileMainTabs()}
1964
+ .selectedView=${this.state.mainView}
1965
+ .onSelect=${e=>{this.selectMainView(e)}}
1966
+ ></app-mobile-main-tabs>
1967
+ `}mobileMainTabs(){return[{id:"navigation",label:"Sessions",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"Chat",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .isRefreshing=${this.isRefreshingApp} .onRefresh=${()=>this.refreshAppData()} .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
1968
+ <div class=${this.panelCollapse.shellClass(e.mainView)}>
1969
+ <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
1970
+ ${this.renderNavigationPanelEdgeControl()}
1971
+ <main class=${Ko(e.mainView)}>
1972
+ ${this.renderContextBar()}
1973
+ ${this.renderMobileMainTabs()}
1974
+ ${e.error?l`<div class="error">${e.error}</div>`:null}
1975
+ <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel(!0):null}</div>
1976
+ ${e.selectedSession?l`
1977
+ <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>
1978
+ <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>
1979
+ <status-bar .status=${e.status} .machine=${e.selectedMachine} .workspace=${e.selectedWorkspace} .workspaceLabelItems=${e.selectedWorkspace===void 0?[]:this.workspaceLabelItems(e.selectedWorkspace)}></status-bar>
1980
+ ${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}
1981
+ ${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}
1982
+ ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
1983
+ ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
1984
+ `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
1985
+ </main>
1986
+ ${this.renderWorkspacePanelEdgeControl()}
1987
+ ${this.renderWorkspacePanel()}
1988
+ ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
1989
+ ${e.projectDialogOpen?l`<project-dialog .machineId=${g(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
1990
+ ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
1991
+ ${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}
1992
+ ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
1993
+ </div>
1994
+ `}};we.styles=kh;De([x()],we.prototype,"state",2);De([re("chat-view")],we.prototype,"chatView",2);De([re("prompt-editor")],we.prototype,"promptEditor",2);De([x()],we.prototype,"activeThemeId",2);De([x()],we.prototype,"isRefreshingApp",2);De([x()],we.prototype,"settingsSection",2);De([x()],we.prototype,"shortcutConfig",2);we=De([A("pi-web-app")],we);function dm(){const e=new Op;return e.register({id:"core",plugin:yp}),e.register({id:"themes",plugin:$p}),e}function so(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 pm(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function hm(e,t){return xn(e,t)}function xn(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function um(e){const t=g(e),i=e.selectedMachine,s=e.machineStatuses[t]?.status??i?.status;if(!(s==="offline"||s==="error"))return Jo(e.machineActivities[t])}function fm(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function ro(e){return fi(e.status,e.activity)}function gm(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function oo(){return{}}function no(e,t){return JSON.stringify([e,t])}function mm(e){return e instanceof Error?e.message:String(e)}function vm(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function bm(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function wm(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function ym(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{E as a,l as b,et as c,Em as d,re as e,Am as f,T as i,d as n,x as r,Rm as s,A as t};