@jmfederico/pi-web 1.202607.3 → 1.202608.0

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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/client/assets/{CodeViewer-CDVbMiN9.js → CodeViewer-D91Sp61M.js} +1 -1
  3. package/dist/client/assets/{TerminalPanel-CTS1CgqF.js → TerminalPanel-fYrKc3jh.js} +1 -1
  4. package/dist/client/assets/{UnifiedDiffViewer-Cqke12ZX.js → UnifiedDiffViewer-BafLWGtF.js} +1 -1
  5. package/dist/client/assets/{index-LME0LfPb.js → index-CA8q9_o7.js} +310 -353
  6. package/dist/client/index.html +1 -1
  7. package/dist/pi-web-plugins/relays/relayDiscovery.js +159 -27
  8. package/dist/pi-web-plugins/relays/relaysPanelElement.js +173 -16
  9. package/dist/server/app.js +0 -22
  10. package/dist/server/app.js.map +1 -1
  11. package/dist/server/browserMessageProjection.js +0 -2
  12. package/dist/server/browserMessageProjection.js.map +1 -1
  13. package/dist/server/configRoutes.js +4 -13
  14. package/dist/server/configRoutes.js.map +1 -1
  15. package/dist/server/machines/machineProxyRoutes.js +2 -13
  16. package/dist/server/machines/machineProxyRoutes.js.map +1 -1
  17. package/dist/server/piWebStatus.js +12 -38
  18. package/dist/server/piWebStatus.js.map +1 -1
  19. package/dist/server/sessiond/agentHttpDispatcher.js +108 -0
  20. package/dist/server/sessiond/agentHttpDispatcher.js.map +1 -0
  21. package/dist/server/sessiond/agentProcessEnvironment.js +62 -0
  22. package/dist/server/sessiond/agentProcessEnvironment.js.map +1 -0
  23. package/dist/server/sessiond/sessionServiceDependencies.js +1 -0
  24. package/dist/server/sessiond/sessionServiceDependencies.js.map +1 -1
  25. package/dist/server/sessiond.js +26 -5
  26. package/dist/server/sessiond.js.map +1 -1
  27. package/dist/server/sessions/askUserTool.js +0 -3
  28. package/dist/server/sessions/askUserTool.js.map +1 -1
  29. package/dist/server/sessions/authRoutes.js +0 -10
  30. package/dist/server/sessions/authRoutes.js.map +1 -1
  31. package/dist/server/sessions/authService.js +0 -24
  32. package/dist/server/sessions/authService.js.map +1 -1
  33. package/dist/server/sessions/messagePaging.js +2 -2
  34. package/dist/server/sessions/messagePaging.js.map +1 -1
  35. package/dist/server/sessions/oauthLoginFlowService.js +2 -5
  36. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -1
  37. package/dist/server/sessions/pendingAskStore.js +0 -3
  38. package/dist/server/sessions/pendingAskStore.js.map +1 -1
  39. package/dist/server/sessions/piSessionManagerGateway.js +182 -2
  40. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
  41. package/dist/server/sessions/piSessionService.js +244 -186
  42. package/dist/server/sessions/piSessionService.js.map +1 -1
  43. package/dist/server/sessions/sessionFileHeader.js +92 -20
  44. package/dist/server/sessions/sessionFileHeader.js.map +1 -1
  45. package/dist/server/sessions/sessionRoutes.js +74 -56
  46. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  47. package/dist/server/sessions/sessionSummaryScanner.js +619 -0
  48. package/dist/server/sessions/sessionSummaryScanner.js.map +1 -0
  49. package/dist/server/sessions/spawnSessionTool.js +8 -1
  50. package/dist/server/sessions/spawnSessionTool.js.map +1 -1
  51. package/dist/server/sessions/spawnSubsessionTool.js +7 -1
  52. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -1
  53. package/dist/server/workspaces/effectivePathAccess.js +0 -19
  54. package/dist/server/workspaces/effectivePathAccess.js.map +1 -1
  55. package/dist/server/workspaces/workspaceDeletionRoutes.js +30 -4
  56. package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -1
  57. package/dist/server/workspaces/workspaceService.js.map +1 -1
  58. package/dist/sessiond/config.js +2 -2
  59. package/dist/sessiond/config.js.map +1 -1
  60. package/dist/shared/apiTypes.d.ts +12 -29
  61. package/dist/shared/apiTypes.js +7 -16
  62. package/dist/shared/apiTypes.js.map +1 -1
  63. package/dist/shared/capabilities.js +10 -44
  64. package/dist/shared/capabilities.js.map +1 -1
  65. package/dist/shared/federatedRoutes.js +0 -3
  66. package/dist/shared/federatedRoutes.js.map +1 -1
  67. package/docs/config.md +59 -4
  68. package/docs/plugins.md +5 -3
  69. package/package.json +10 -9
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-CDVbMiN9.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-CTS1CgqF.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-D91Sp61M.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-fYrKc3jh.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>i.map(i=>d[i]);
2
2
  import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var re=globalThis,ie=re.ShadowRoot&&(re.ShadyCSS===void 0||re.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,ae=Symbol(),oe=new WeakMap,se=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==ae)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(ie&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=oe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&oe.set(t,e))}return e}toString(){return this.cssText}},ce=e=>new se(typeof e==`string`?e:e+``,void 0,ae),h=(e,...t)=>new se(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,ae),le=(e,t)=>{if(ie)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=re.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ue=ie?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return ce(t)})(e):e,{is:de,defineProperty:fe,getOwnPropertyDescriptor:pe,getOwnPropertyNames:me,getOwnPropertySymbols:he,getPrototypeOf:ge}=Object,_e=globalThis,ve=_e.trustedTypes,ye=ve?ve.emptyScript:``,be=_e.reactiveElementPolyfillSupport,xe=(e,t)=>e,Se={toAttribute(e,t){switch(t){case Boolean:e=e?ye:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Ce=(e,t)=>!de(e,t),we={attribute:!0,type:String,converter:Se,reflect:!1,useDefault:!1,hasChanged:Ce};Symbol.metadata??=Symbol(`metadata`),_e.litPropertyMetadata??=new WeakMap;var Te=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=we){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&fe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=pe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(xe(`elementProperties`)))return;let e=ge(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(xe(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(xe(`properties`))){let e=this.properties,t=[...me(e),...he(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(ue(e))}else e!==void 0&&t.push(ue(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return le(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Se:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Se:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??Ce)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};Te.elementStyles=[],Te.shadowRootOptions={mode:`open`},Te[xe(`elementProperties`)]=new Map,Te[xe(`finalized`)]=new Map,be?.({ReactiveElement:Te}),(_e.reactiveElementVersions??=[]).push(`2.1.2`);var Ee=globalThis,De=e=>e,Oe=Ee.trustedTypes,ke=Oe?Oe.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Ae=`$lit$`,je=`lit$${Math.random().toFixed(9).slice(2)}$`,Me=`?`+je,Ne=`<${Me}>`,Pe=document,Fe=()=>Pe.createComment(``),Ie=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Le=Array.isArray,Re=e=>Le(e)||typeof e?.[Symbol.iterator]==`function`,ze=`[
3
- \f\r]`,Be=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ve=/-->/g,He=/>/g,Ue=RegExp(`>|${ze}(?:([^\\s"'>=/]+)(${ze}*=${ze}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),We=/'/g,Ge=/"/g,Ke=/^(?:script|style|textarea|title)$/i,qe=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=qe(1),Je=qe(2),Ye=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Xe=new WeakMap,Ze=Pe.createTreeWalker(Pe,129);function Qe(e,t){if(!Le(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return ke===void 0?t:ke.createHTML(t)}var $e=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Be;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Be?c[1]===`!--`?o=Ve:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ue):(Ke.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ue):o=He:o===Ue?c[0]===`>`?(o=i??Be,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ue:c[3]===`"`?Ge:We):o===Ge||o===We?o=Ue:o===Ve||o===He?o=Be:(o=Ue,i=void 0);let d=o===Ue&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Be?n+Ne:l>=0?(r.push(s),n.slice(0,l)+Ae+n.slice(l)+je+d):n+je+(l===-2?t:d)}return[Qe(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},et=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=$e(t,n);if(this.el=e.createElement(l,r),Ze.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Ze.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Ae)){let t=u[o++],n=i.getAttribute(e).split(je),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?at:r[1]===`?`?ot:r[1]===`@`?st:it}),i.removeAttribute(e)}else e.startsWith(je)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ke.test(i.tagName)){let e=i.textContent.split(je),t=e.length-1;if(t>0){i.textContent=Oe?Oe.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Fe()),Ze.nextNode(),c.push({type:2,index:++a});i.append(e[t],Fe())}}}else if(i.nodeType===8)if(i.data===Me)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(je,e+1))!==-1;)c.push({type:7,index:a}),e+=je.length-1}a++}}static createElement(e,t){let n=Pe.createElement(`template`);return n.innerHTML=e,n}};function tt(e,t,n=e,r){if(t===Ye)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Ie(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=tt(e,i._$AS(e,t.values),i,r)),t}var nt=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Pe).importNode(t,!0);Ze.currentNode=r;let i=Ze.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new rt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ct(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Ze.nextNode(),a++)}return Ze.currentNode=Pe,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},rt=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=tt(this,e,t),Ie(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Ye&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Re(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==_&&Ie(this._$AH)?this._$AA.nextSibling.data=e:this.T(Pe.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=et.createElement(Qe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new nt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Xe.get(e.strings);return t===void 0&&Xe.set(e.strings,t=new et(e)),t}k(t){Le(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Fe()),this.O(Fe()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=De(e).nextSibling;De(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},it=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=_,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=_}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=tt(this,e,t,0),a=!Ie(e)||e!==this._$AH&&e!==Ye,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=tt(this,r[n+o],t,o),s===Ye&&(s=this._$AH[o]),a||=!Ie(s)||s!==this._$AH[o],s===_?e=_:e!==_&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},at=class extends it{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},ot=class extends it{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},st=class extends it{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=tt(this,e,t,0)??_)===Ye)return;let n=this._$AH,r=e===_&&n!==_||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==_&&(n===_||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ct=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){tt(this,e)}},lt={M:Ae,P:je,A:Me,C:1,L:$e,R:nt,D:Re,V:tt,I:rt,H:it,N:ot,U:st,B:at,F:ct},ut=Ee.litHtmlPolyfillSupport;ut?.(et,rt),(Ee.litHtmlVersions??=[]).push(`3.3.3`);var dt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new rt(t.insertBefore(Fe(),e),e,void 0,n??{})}return i._$AI(e),i},ft=globalThis,v=class extends Te{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=dt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ye}};v._$litElement$=!0,v.finalized=!0,ft.litElementHydrateSupport?.({LitElement:v});var pt=ft.litElementPolyfillSupport;pt?.({LitElement:v}),(ft.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},mt={attribute:!0,type:String,converter:Se,reflect:!1,hasChanged:Ce},ht=(e=mt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function b(e){return(t,n)=>typeof n==`object`?ht(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function x(e){return b({...e,state:!0,attribute:!1})}var gt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function S(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return gt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return gt(n,r,{get(){return a(this)}})}}function _t(e,t=yt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(bt(e),n).toString()}function vt(e,t=yt()){let n=new URL(_t(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function yt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function bt(e){return e.startsWith(`/`)?`.${e}`:e}async function C(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(_t(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(xt(e)??i.statusText)}return t(await i.json())}function xt(e){if(St(e))return typeof e.error==`string`?e.error:void 0}function St(e){return typeof e==`object`&&!!e}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,sessionsAskUser:`sessions.askUser`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`},Ct=1e3,wt=32*1024,Tt=8*1024,Et=1e3,Dt=4e3,Ot=1e3,kt=4e3,At=1e4;function jt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Mt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&jt(e)}var Nt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Pt=/^sha256:[0-9a-f]{64}$/u,Ft=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,It=new Set([`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Lt(e){if(!Ht(e)||Object.keys(e).some(e=>!Nt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Pt.test(n))&&!(typeof r!=`string`||!Rt(r))&&!(typeof i!=`string`||!zt(i))&&Vt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEB_AGENT_SESSION_DIR`||a.some(e=>!It.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Rt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:zt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Ft.test(e)}function zt(e){if(e===``||e!==e.trim()||Bt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Bt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Vt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ut=Object.values(w),Wt=new Set(Ut);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig;function Gt(e){return typeof e==`string`&&Wt.has(e)}function T(e,t){return e?.capabilities?.includes(t)===!0}function Kt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Gt)}function qt(e){return typeof e==`object`&&!!e}function E(e){if(!qt(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Jt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Yt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Xt(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:Jt(t.messages),start:k(t,`start`),total:k(t,`total`)}}function Zt(e){let t=E(e);return j(Qt)(t.machines)}function Qt(e){let t=E(e),n=tn(t,`kind`),r=O(t,`baseUrl`),i=nn(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function $t(e){let t=E(e),n=nn(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Ni(t.web)},...t.sessiond===void 0?{}:{sessiond:Ni(t.sessiond)},...r===void 0?{}:{error:r}}}function en(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...N(`packageName`,O(t,`packageName`)),...N(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:ji(t.components)},...t.capabilities===void 0?{}:{capabilities:zi(t.capabilities)},...n===void 0?{}:{error:n}}}function tn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function nn(e,t){let n=O(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function rn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function an(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...N(`effectiveConfig`,on(t.effectiveConfig))}}function on(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,di(e.uploads))}}}function sn(e){let t=E(e),n=O(t,`name`),r=Ei(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`parentSessionCwd`),o=O(t,`parentSessionId`),s=Di(t.childSessionsElsewhere,`childSessionsElsewhere`),c=O(t,`archivedAt`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...a===void 0?{}:{parentSessionCwd:a},...o===void 0?{}:{parentSessionId:o},...s===void 0?{}:{childSessionsElsewhere:s},...t.archived===!0?{archived:!0}:{},...c===void 0?{}:{archivedAt:c}}}function cn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function ln(e){if(e!==void 0)return{id:D(E(e),`id`)}}function un(e){let t=E(e),n=ln(t.dismiss);return{severity:cn(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function dn(e){return e===void 0?{}:{warnings:j(un)(e)}}function fn(e){let t=E(e);return{value:M(t,`value`,128),label:M(t,`label`,Et),...N(`detail`,Gn(t,`detail`,Et))}}function pn(e){let t=E(e),n=nr(t.options,fn,12,`options`);Cn(n.map(e=>e.value),`ask option value`),Ei(t.allowOther,`allowOther`);let r=Ei(t.multiple,`multiple`);return{id:M(t,`id`,128),question:M(t,`question`,Et),...N(`detail`,Gn(t,`detail`,Et)),options:n,allowOther:!0,...r===void 0?{}:{multiple:r}}}function mn(e){let t=E(e),n=nr(t.questions,pn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Cn(n.map(e=>e.id),`ask question id`),{askId:M(t,`askId`,128),askedAt:ir(t,`askedAt`),questions:n}}function hn(e){return e===void 0?{}:{pendingAsk:mn(e)}}function gn(e){let t=E(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:mn(t.ask)}}function _n(e){let t=E(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:M(t,`askId`,128),reason:vn(t.reason)}}function vn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function yn(e){let t=E(e),n=pn(t.question),r=nr(t.values,rr,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=Gn(t,`otherText`,Dt),o=A(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function bn(e){let t=E(e),n=nr(t.questions,yn,20,`questions`),r=ar(t,`answeredCount`),i=Yt(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:M(t,`askId`,128),reason:vn(t.reason),askedAt:ir(t,`askedAt`),closedAt:ir(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:ir(t,`summary`)}}function xn(e){let t=E(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:bn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Pn(t.sessionStatus)}}function Sn(e){let t=E(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Mn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Pn(t.sessionStatus)}}function Cn(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function wn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Tn(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function En(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function Dn(e){let t=rr(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function On(e){let t=E(e),n=wn(t.kind),r=t.options===void 0?void 0:nr(t.options,Dn,24,`options`);if(r!==void 0&&Cn(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:M(t,`dialogId`,128),kind:n,title:M(t,`title`,Ot),...N(`message`,Gn(t,`message`,Ot)),...r===void 0?{}:{options:r},...N(`placeholder`,Gn(t,`placeholder`,Ot)),askedAt:ir(t,`askedAt`),...N(`timeoutAt`,Nn(t,`timeoutAt`)),runScoped:A(t,`runScoped`)}}function kn(e){if(e===void 0)return{};let t=j(On)(e);return Cn(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function An(e){let t=E(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:On(t.dialog)}}function jn(e){let t=E(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Tn(t.reason),r=t.answer===void 0?void 0:En(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:M(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Mn(e){let t=E(e),n=Tn(t.reason),r=t.answer===void 0?void 0:En(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:M(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:ir(t,`askedAt`),closedAt:ir(t,`closedAt`)}}function Nn(e,t){let n=O(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function Pn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,Ei(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(vr)(t.queuedMessages),...N(`messageCount`,ua(t,`messageCount`)),tokens:yr(t.tokens),cost:k(t,`cost`),...xr(t.model),...zr(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...dn(t.warnings),...hn(t.pendingAsk),...kn(t.pendingDialogs)}}function Fn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function In(e){let t=E(e),n=ar(t,`catalogRevision`),r=nr(t.sessions,Hn,Ct,`sessions`);if(Un(r),Wn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:M(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Ln(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=M(t,`sessionId`,512),r=M(t,`cwd`,wt),i=Kn(t,`catalogRevision`),a=t.unread===null?null:Hn(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:M(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Rn(e){let t=E(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=O(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...N(`startupToken`,n),activity:zn(t.activity)}}function zn(e){let t=E(e);return{sessionId:ir(t,`sessionId`),phase:Vn(t,`phase`),label:ir(t,`label`),...N(`detail`,O(t,`detail`)),at:ir(t,`at`),...N(`startup`,Bn(t))}}function Bn(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function Vn(e,t){let n=D(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function Hn(e){let t=E(e),n=M(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:M(t,`sessionId`,512),cwd:M(t,`cwd`,wt),completionOrder:Kn(t,`completionOrder`),completedAt:n}}function Un(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function Wn(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function M(e,t,n){let r=ir(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Gn(e,t,n){let r=O(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function Kn(e,t){let n=ar(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function qn(e){let t=E(e),n=Yn(t.summary),r=nr(t.notifications,Xn,100,`notifications`);if(or(r),sr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==lr(r))throw Error(`Notification snapshot severity mismatch`);let i=Zn(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:ir(t,`daemonInstanceId`),catalogRevision:ar(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Jn(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Yn(t.summary),r=Zn(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Qn(t.delta);if(i.kind===`cleared`&&!cr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:ir(t,`daemonInstanceId`),catalogRevision:ar(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Yn(e){let t=E(e),n=ar(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=ar(t,`discardedCount`),i=er(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:ir(t,`sessionId`),cwd:ir(t,`cwd`),inboxRevision:ar(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Xn(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=ar(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:ir(t,`id`),message:n,truncated:A(t,`truncated`),severity:$n(t.severity),receivedAt:r,order:i}}function Zn(e){let t=E(e);return{order:ar(t,`order`),overflowWatermark:ar(t,`overflowWatermark`)}}function Qn(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:Xn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=nr(t.notificationIds,rr,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:tr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function $n(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function er(e){return e===void 0?void 0:$n(e)}function tr(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function nr(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function rr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function ir(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function ar(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function or(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function sr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function cr(e){return e.retainedCount===0&&e.discardedCount===0}function lr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function ur(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:Yt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:hr(t.thresholds),projects:j(gr)(t.projects),totals:_r(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function dr(e){let t=E(e);return{...ur(t),archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`)}}function fr(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),failures:j(mr)(t.failures),generatedAt:D(t,`generatedAt`)}}function pr(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`),failures:j(mr)(t.failures),generatedAt:D(t,`generatedAt`)}}function mr(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function hr(e){let t=E(e);return{...N(`archiveIdleDays`,ua(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,ua(t,`deleteArchivedDays`))}}function gr(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function _r(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function vr(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function yr(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function br(e){let t=E(e);return{...N(`provider`,O(t,`provider`)),...N(`id`,O(t,`id`)),...N(`name`,O(t,`name`)),...N(`contextWindow`,ua(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function xr(e){return e===void 0?{}:{model:br(e)}}function Sr(e){let t=E(e);return{models:j(br)(t.models)}}function Cr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function wr(e){let t=E(e);return{levels:j(Cr)(t.levels)}}function Tr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Er(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Dr(e){let t=E(e),n=t.source===void 0?void 0:Er(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function Or(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:Tr(t.authType),status:Dr(t.status),...n===void 0?{}:{loginFlow:n}}}function kr(e){let t=E(e);return{providers:j(Or)(t.providers)}}function Ar(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:jr(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,O(t,`error`)),...N(`auth`,Mr(t.auth)),...N(`prompt`,Pr(t.prompt)),...N(`select`,Ir(t.select)),...N(`info`,Lr(t.info))}}function jr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Mr(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,Nr(t.deviceCode))}}function Nr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...N(`intervalSeconds`,ua(t,`intervalSeconds`)),...N(`expiresInSeconds`,ua(t,`expiresInSeconds`))}}function Pr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Fr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,la(t,`allowEmpty`))}}function Fr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Ir(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(Xi)(t.options)}}function Lr(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...N(`links`,t.links===void 0?void 0:j(Rr)(t.links))}})(e)}function Rr(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function zr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:da(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:da(t,`percent`)}}}function Br(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...N(`description`,O(t,`description`))}}function Vr(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function Hr(e){let t=E(e);return{path:D(t,`path`),entries:j(Ur)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Ur(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...N(`size`,ua(t,`size`)),...N(`modifiedAt`,O(t,`modifiedAt`))}}function Wr(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...N(`language`,O(t,`language`)),...N(`mediaType`,Jr(t.mediaType)),...N(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function Gr(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Kr(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function qr(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Jr(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Yr(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...N(`branch`,O(t,`branch`)),...N(`upstream`,O(t,`upstream`)),...N(`ahead`,ua(t,`ahead`)),...N(`behind`,ua(t,`behind`)),files:j(Xr)(t.files),submodules:t.submodules===void 0?[]:Yt(t.submodules,`submodules`)}}function Xr(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:Zr(t.index),workingTree:Zr(t.workingTree),...N(`submoduleFromCommit`,O(t,`submoduleFromCommit`)),...N(`submoduleToCommit`,O(t,`submoduleToCommit`))}}function Zr(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 Error(`Invalid git file state`)}}function Qr(e){let t=E(e);return{...N(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function $r(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...N(`exitCode`,ua(t,`exitCode`)),...N(`commandRunId`,O(t,`commandRunId`))}}function ei(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:ti(t.status),...N(`exitCode`,ua(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:ni(t.metadata,`metadata`)}}function ti(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ni(e,t){let n=E(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function ri(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function ii(e){let t=E(e);return{workspaces:j(ri)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function ai(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:oi(t.config),effectiveConfig:oi(t.effectiveConfig),envOverrides:gi(t.envOverrides)}}function oi(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,ua(t,`port`)),...N(`allowedHosts`,ci(t.allowedHosts)),...N(`shortcuts`,mi(t.shortcuts)),...N(`plugins`,hi(t.plugins)),...N(`pathAccess`,li(t.pathAccess)),...N(`uploads`,di(t.uploads)),...N(`maxUploadBytes`,ua(t,`maxUploadBytes`)),...N(`agent`,si(t.agent)),...N(`spawnSessions`,la(t,`spawnSessions`)),...N(`subsessions`,la(t,`subsessions`)),...N(`askUser`,la(t,`askUser`))}}function si(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function ci(e){if(e!==void 0){if(e===!0)return!0;if(fi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function li(e){if(e===void 0)return;if(!qt(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,ui(t,`pathAccess.allowedPaths`))}}function ui(e,t){if(e!==void 0){if(pi(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function di(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function fi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function pi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function mi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function hi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!qt(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!qt(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function gi(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),askUser:la(t,`askUser`)??!1,agentCommand:la(t,`agentCommand`)??!1,agentDir:la(t,`agentDir`)??!1,..._i(t),agentSessionDir:la(t,`agentSessionDir`)??!1}}function _i(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function vi(e){let t=E(e);return{packages:j(bi)(t.packages)}}function yi(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:xi(t.scope),i=Ei(t.removed,`removed`);return{action:Si(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(bi)(t.packages)}}function bi(e){let t=E(e);return{source:D(t,`source`),scope:xi(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function xi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Si(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ci(e){let t=E(e);return{plugins:j(wi)(t.plugins)}}function wi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ti(t.scope),machineSpecific:Ei(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ti(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function Ei(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Di(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`Expected optional count field: ${t}`);return e===0?void 0:e}}function Oi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Ai(t.components),release:Fi(t.release),commands:Ii(t.commands),messages:j(Li)(t.messages)}}function ki(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:ji(t.components),capabilities:zi(t.capabilities)}}function Ai(e){let t=E(e);return{web:Ni(t.web),sessiond:Ni(t.sessiond)}}function ji(e){let t=E(e);return{web:Mi(t.web),sessiond:Mi(t.sessiond)}}function Mi(e){let t=E(e),n=Ri(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Lt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:zi(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function Ni(e){let t=E(e);return{component:Ri(t.component),label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...N(`installation`,Pi(t.installation)),...N(`error`,O(t,`error`))}}function Pi(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...N(`path`,O(t,`path`)),...N(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Fi(e){let t=E(e);return{packageName:D(t,`packageName`),...N(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...N(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,O(t,`error`))}}function Ii(e){let t=E(e);return{...N(`update`,O(t,`update`)),...N(`restart`,O(t,`restart`)),...N(`restartWeb`,O(t,`restartWeb`)),...N(`restartSessiond`,O(t,`restartSessiond`)),...N(`status`,O(t,`status`))}}function Li(e){let t=E(e);return{id:D(t,`id`),severity:Bi(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function Ri(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function zi(e){let t=Kt(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Bi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Vi(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(Xi)(t.options)};if(n===`tree`)return{type:n,tree:Hi(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...Zi(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Hi(e){let t=E(e),n=j(Ui)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=qi(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Yi(t.activePathIds,`activePathIds`)}}function Ui(e){let t=E(e);return{id:Ji(t,`id`),parentId:qi(t,`parentId`),kind:Wi(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function Wi(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Gi(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Ki(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return Ki(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function Ki(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function qi(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function Ji(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Yi(e,t){let n=Yt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Xi(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function Zi(e){return e===void 0?{}:{session:sn(e)}}function Qi(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function $i(e){let t=E(e);return j(ea)(t.attachments)}function ea(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function ta(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function na(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function ra(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ia(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Yt(t.sessionIds,`sessionIds`),r=ua(t,`archivedCount`),i=ua(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function aa(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function oa(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function sa(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ca(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function la(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function ua(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function da(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function N(e,t){return t===void 0?{}:{[e]:t}}function fa(e){return typeof e==`string`?e:e.id}function pa(e){return typeof e==`string`?void 0:e.cwd}function ma(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function ha(e,t,n=`local`){let r=new URLSearchParams,i=pa(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(fa(e))}/messages${a===``?``:`?${a}`}`}function ga(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),_t(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function _a(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),_t(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function va(e){return typeof e==`string`?e:e.id}function ya(e){return typeof e==`string`?void 0:e.cwd}function ba(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(va(e))}`}function F(e,t,n=`local`){return`${ba(e,n)}/${t}`}function xa(e,t,n=`local`){return`${F(e,t,n)}${Ca(e)}`}function Sa(e,t=`local`){return`${ba(e,t)}${Ca(e)}`}function Ca(e){let t=ya(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function I(e,t={}){let n=ya(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function wa(e){return JSON.stringify({sessions:e.map(Ta)})}function Ta(e){let t=va(e),n=ya(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ea(e){return e===`local`?`api/pi-web/status`:`${P(e)}/pi-web/status`}var Da={piWebStatus:(e=`local`)=>C(Ea(e),Oi),checkForUpdates:(e=`local`)=>C(`${Ea(e)}?refresh=1`,Oi,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,ki)},Oa={machines:()=>C(`api/machines`,Zt),addMachine:e=>C(`api/machines`,Qt,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,$t),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,en,t?{cache:`no-store`}:{})};function ka(e){return e===void 0?`api/config`:`${P(e)}/config`}function Aa(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var ja={config:e=>C(ka(e),ai),saveConfig:(e,t)=>C(ka(t),ai,{method:`PUT`,body:JSON.stringify({config:e})})},Ma={plugins:e=>C(Aa(e),Ci)};function Na(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Pa={packages:e=>C(Na(``,e),vi),install:(e,t)=>{let n={source:e};return C(Na(`install`,t),yi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(Na(`remove`,n),yi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(Na(`update`,t),yi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Fa={workspaceActivity:(e=`local`)=>C(`${P(e)}/activity`,ii)},Ia={projects:(e=`local`)=>C(`${P(e)}/projects`,j(rn)),addProject:(e,t,n,r=`local`)=>C(`${P(r)}/projects`,rn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${P(t)}/projects/${encodeURIComponent(e)}`,ta,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Vr))},La={workspaces:(e,t=`local`)=>C(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(an)),deleteWorkspace:(e,t,n=`local`)=>C(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ei,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Hr),workspaceFile:(e,t,n,r=`local`)=>C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Wr),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return C(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Gr,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Kr,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),C(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,qr,{method:`POST`})}},Ra={sessions:(e,t=`local`)=>C(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(sn)),unreadCatalog:(e=`local`)=>C(`${P(e)}/sessions/unread`,In,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return C(F(e,`unread/acknowledge`,r),In,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(xa(e,`notifications`,t),qn),dismissNotification:(e,t,n,r=`local`)=>C(F(e,`notifications/dismiss`,r),qn,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(F(e,`notifications/dismiss-all`,r),qn,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${P(t)}/sessions`,sn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${P(t)}/sessions/cleanup/preview`,ur,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${P(t)}/sessions/cleanup`,dr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${P(t)}/sessions/bulk/archive`,fr,{method:`POST`,body:wa(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${P(t)}/sessions/bulk/delete-archived`,pr,{method:`POST`,body:wa(e)}),messages:(e,t,n=`local`)=>C(ha(e,t,n),Xt),status:(e,t=`local`)=>C(xa(e,`status`,t),Pn),streamSnapshot:(e,t=`local`)=>C(xa(e,`stream-snapshot`,t),Fn),clearQueue:(e,t=`local`)=>C(F(e,`queue/clear`,t),Pn,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>C(F(e,`warnings/dismiss`,n),Pn,{method:`POST`,body:I(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(F(e,`ask/submit`,r),xn,{method:`POST`,body:I(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(F(e,`ask/cancel`,n),xn,{method:`POST`,body:I(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(F(e,`dialogs/answer`,r),Sn,{method:`POST`,body:I(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(F(e,`dialogs/cancel`,n),Sn,{method:`POST`,body:I(e,{dialogId:t})}),models:(e,t=`local`)=>C(xa(e,`models`,t),Sr),setModel:(e,t,n,r=`local`)=>C(F(e,`model`,r),Pn,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(F(e,`model/cycle`,n),Pn,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(xa(e,`thinking-levels`,t),wr),setThinkingLevel:(e,t,n=`local`)=>C(F(e,`thinking-level`,n),Pn,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(F(e,`thinking-level/cycle`,t),Pn,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>C(xa(e,`commands`,t),j(Br)),prompt:(e,t,n,r=`local`,i)=>C(F(e,`prompt`,r),Qi,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>C(F(e,`attachments`,n),$i,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(F(e,`shell`,n),Qi,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(F(e,`commands/run`,n),Vi,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(F(e,`commands/respond`,r),Vi,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(F(e,`tree/navigate`,n),Gi,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),abort:(e,t=`local`)=>C(F(e,`abort`,t),na,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>C(F(e,`stop`,t),ra,{method:`POST`,body:I(e)}),archive:(e,t=`local`)=>C(F(e,`archive`,t),ia,{method:`POST`,body:I(e)}),archiveWithDescendants:(e,t=`local`)=>C(F(e,`archive-tree`,t),ia,{method:`POST`,body:I(e)}),restore:(e,t=`local`)=>C(F(e,`restore`,t),aa,{method:`POST`,body:I(e)}),deleteArchived:(e,t=`local`)=>C(Sa(e,t),oa,{method:`DELETE`}),detachParent:(e,t=`local`)=>C(F(e,`detach-parent`,t),sa,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>C(F(e,`reload`,t),ca,{method:`POST`,body:I(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return C(`${P(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,kr)},saveApiKey:(e,t,n=`local`)=>C(`${P(n)}/auth/api-key`,Qi,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${P(t)}/auth/api-key/interactive`,Ar,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${P(t)}/auth/logout`,Qi,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${P(t)}/auth/oauth`,Ar,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${P(t)}/auth/oauth/${encodeURIComponent(e)}`,Ar),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${P(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,Ar,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${P(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Ar,{method:`POST`})},za={terminals:(e,t,n=`local`)=>C(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j($r)),startTerminal:(e,t,n,r=`local`)=>C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,$r,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ta,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,ta,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,$r,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ei,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${P(t)}/terminal-command-runs${Va(e)}`,j(ei)),getCommandRun:(e,t=`local`)=>Ba(e,t),cancelCommandRun:(e,t=`local`)=>C(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ei,{method:`POST`})};async function Ba(e,t){let n=await fetch(_t(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(Ha(e)??n.statusText)}return ei(await n.json())}}function Va(e){if(e===void 0)return``;let 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));let n=t.toString();return n===``?``:`?${n}`}function Ha(e){if(!Ua(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Ua(e){return typeof e==`object`&&!!e}var Wa={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?C(`${P(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Vr)):(r.set(`cwd`,e),C(`${P(n.machineId)}/files?${r.toString()}`,j(Vr)))}},Ga={gitStatus:(e,t,n=`local`)=>C(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Yr),gitDiff:(e,t,n,r=`local`)=>C(ma(r,e,t,n),Qr)},L={...Da,...Oa,...ja,...Ma,...Pa,...Fa,...Ia,...La,...Ra,...za,...Wa,...Ga};function Ka(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(vt(`${Ya(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function qa(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(vt(`${Ya(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Ja(e=`local`){return new WebSocket(vt(`${Ya(e)}/events`))}function Ya(e){return`api/machines/${encodeURIComponent(e)}`}var Xa=`.pi-web/uploads`,Za=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Qa=class extends Error{constructor(e,t){super(lo(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function $a(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function eo(e,t){return e?.uploads?.defaultFolder??t}function to(e,t){let n=po(e,`upload destination`,{allowEmpty:!0}),r=po(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function no(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,ga(e,t,n.path,ao(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(oo(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(Gr(ho(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(go(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Za(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function ro(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:to(i,e.name),loaded:0,total:e.size,percent:co(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(so(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new Za;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=no(e,t,{path:p.path,file:f},{...io(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(fo(e,c))throw e;let t=uo(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new Qa(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function io(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function ao(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function oo(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:co(e.loaded,n),lengthComputable:e.lengthComputable}}function so(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:co(i,r),done:n}}function co(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function lo(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function uo(e){return e instanceof Error?e.message:String(e)}function fo(e,t){return t.requested||e instanceof Za}function po(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(mo(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function mo(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function ho(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function go(e){let t=_o(e);return vo(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function _o(e){try{return ho(e)}catch{return}}function vo(e){return typeof e==`object`&&!!e}function yo(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,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 bo(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog: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,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function xo(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function So(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Co(e,t){return`${e}:${t}`}function wo(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var To=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Eo=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new To,this.api=n.api??Fa,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Do(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=Oo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Do(e){let t={};for(let n of e.workspaces)So(n)&&(t[n.cwd]=n);return t}function Oo(e,t){let n={...e};return So(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var ko=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??L,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=jo(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Ao(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Ao(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEB instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Ao(n.flow):void 0,a=Ao(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=Ao(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||Ao(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Ao(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Ao(e){return e.prompt?.requestId??e.select?.requestId}function jo(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function Mo(e){return e.replaceAll(`:`,`.`)}function No(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function Po(e,t){let n=No(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Fo(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));Io(i,r)}function Io(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function Lo(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:to(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:Uo(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:Uo(0,n),status:`uploading`,startedAt:e.startedAt}}function Ro(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function zo(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=Ho(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function Bo(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...Ho(r),status:`error`,error:t,completedAt:n}}function Vo(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...Ho(r),status:`cancelled`,error:n,completedAt:t}}function Ho(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Uo(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var Wo=Mo(`core:workspace.files`),Go=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??L,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??ro,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:Yo(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Fo(Wo,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(Ko(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Fo(Wo,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=Lo({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(Vo(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:Yo(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(Ro(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(zo(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof Qa)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(qo(t)){let e=Vo(n,this.now());return this.setUploadBatch(e),e}let r=Jo(t),i=Bo(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function Ko(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function qo(e){return e instanceof Za}function Jo(e){return e instanceof Error?e.message:String(e)}function Yo(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Xo=Mo(`core:workspace.git`),Zo=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=await L.gitStatus(e.id,t.id,R(this.getState()));this.setState({gitStatus:n,gitStale:!1,error:``});let r=this.getState().selectedDiffPath;r!==void 0&&(n.files.some(e=>e.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Fo(Xo,`diff`,void 0,{replace:!0})))}catch(e){this.setState({error:String(e)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),Fo(Xo,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0))try{let[r,i]=await Promise.all([L.gitDiff(t.id,n.id,{path:e},R(this.getState())),L.gitDiff(t.id,n.id,{path:e,staged:!0},R(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:i,error:``})}catch(e){this.setState({error:String(e)})}}updatePolling(){this.dispose();let e=this.getState();(e.workspaceTool===`core:workspace.git`||e.mainView===`core:workspace.git`)&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}},Qo=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await L.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:es(this.getState().machineActivities,r),machineRuntimes:es(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...yo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await L.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await L.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:$o(this.getState().machineStatuses,e.id),machineRuntimes:$o(this.getState().machineRuntimes,e.id),machineActivities:$o(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await L.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await L.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await L.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>L.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>L.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function $o(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function es(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var ts=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??L,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){R(this.getState())===e&&this.setState({error:String(t)})}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){R(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}};function ns(e,t){return t[e.path]}function rs(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function is(e,t,n){return ss(cs(e,t,n))}function as(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function os(e){return ss(Object.values(e??{}))}function ss(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function cs(e,t,n){return Object.values(n).filter(n=>as(e,t,n.cwd))}var ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??La,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!us(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!us(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(So).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function us(e,t,n){return e.some(e=>as(e,t[e.id]??[],n))}var ds=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Da,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),fs(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function fs(e){if(e.release.error!==void 0)throw Error(`PI WEB update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`)}var ps=`pi-web:cached-new-sessions:v1`,ms=`browserCachedNew`,hs=`local`;function gs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function _s(e,t=hs,n=gs()){if(e.messageCount!==0||e.archived===!0)return;let r=Cs(n).filter(n=>n.id!==e.id||n.machineId!==t);ws([vs(e,t),...r],n)}function vs(e,t=hs){return{...e,browserCachedNew:!0,machineId:t}}function ys(e,t=hs,n=gs()){ws(Cs(n).filter(n=>n.id!==e||n.machineId!==t),n)}function bs(e,t,n=hs,r=gs()){let i=new Set(t.map(e=>e.id)),a=Cs(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&ws(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function xs(e){return e!==void 0&&Es(e)&&e.browserCachedNew===!0}function Ss(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...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:hs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Cs(e=gs()){try{let t=e?.getItem(ps);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Ts(e)):[]}catch{return[]}}function ws(e,t=gs()){try{e.length===0?t?.removeItem(ps):t?.setItem(ps,JSON.stringify(e))}catch{}}function Ts(e){if(!Ds(e))return[];let t=Os(e,`id`),n=Os(e,`path`),r=Os(e,`cwd`),i=Os(e,`created`),a=Os(e,`modified`),o=Os(e,`firstMessage`),s=As(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=ks(e,`name`),l=ks(e,`parentSessionPath`),u=ks(e,`machineId`)??hs;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},machineId:u,browserCachedNew:!0}]}function Es(e){return ms in e}function Ds(e){return typeof e==`object`&&!!e}function Os(e,t){let n=e[t];return typeof n==`string`?n:void 0}function ks(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function As(e,t){let n=e[t];return typeof n==`number`?n:void 0}function js(e){return $s(e.flatMap(Is)).filter(e=>e.parts.length>0)}function Ms(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Ns(e,t){let n=Hs(t);return n===void 0?e:{...e,meta:n}}function Ps(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,Ms(t,n)]}function Fs(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function Is(e){if(Rs(e))return[e];if(z(e,`role`)===`bashExecution`)return[Ns(Gs(e),e)];let t=z(e,`role`),n=Ks(t),r=qs(sc(e,`content`),e),i=t===`toolResult`?Ys(z(e,`toolName`)??``,sc(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?zs(a):void 0;if(o!==void 0)return o.map(t=>Ns(t,e));let s=Vs(e);if(n===`tool`)return[Ns({role:n,parts:a,...s===void 0?{}:{source:s}},e)];let c=a.filter(e=>e.type!==`empty`),l=n===`assistant`&&c.length>0&&c.every(e=>e.type===`skillRead`)?`skill`:n,u=c.length>0?[Ns({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Ls(e);return d===void 0?u:[...u,Ns(d,e)]}function Ls(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return Ms(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Rs(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(sc(e,`parts`))}function zs(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Bs(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 Bs(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function Vs(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Hs(e){let t=Us(sc(e,`timestamp`)),n=Ws(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Us(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Ws(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function Gs(e){let t=z(e,`command`)??``,n=cc(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=sc(e,`output`);r!=null&&n.push(``,uc(r));let i=sc(e,`exitCode`);i!=null&&n.push(``,`exit ${uc(i)}`),cc(e,`cancelled`)===!0&&n.push(``,`cancelled`),cc(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
- `)}]}}function Ks(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function qs(e,t){let n=Js(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=sc(e,`arguments`),r=z(e,`id`),i=t===`read`?Qs(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:ic(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return rc(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Zs(e.text,t):e):rc(e):[n]}function Js(e){if(!(z(e,`role`)!==`custom`||z(e,`customType`)!==`pi-web.ask.answers`))return Xs(sc(e,`details`))}function Ys(e,t){if(e===`ask_user`)return Xs(sc(t,`superseded`))}function Xs(e){try{return{type:`askUserRecord`,outcome:bn(e)}}catch{return}}function Zs(e,t){let n=z(t,`toolCallId`),r=sc(t,`content`),i=sc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:cc(t,`isError`)===!0}}function Qs(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function $s(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&tc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function ec(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 tc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=nc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function nc(e){let t=sc(e,`preview`);if(!oc(t))return;let n=z(t,`diff`),r=z(t,`error`),i=lc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function rc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:ic(e)}]:[{type:`text`,text:uc(e)}]}function ic(e){if(!oc(e))return uc(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${ac(t)}`).join(` · `)}function ac(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?`object`:``}function oc(e){return typeof e==`object`&&!!e}function sc(e,t){return oc(e)?e[t]:void 0}function z(e,t){let n=sc(e,t);return typeof n==`string`?n:void 0}function cc(e,t){let n=sc(e,t);return typeof n==`boolean`?n:void 0}function lc(e,t){let n=sc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function uc(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var dc=`pi-web:prompt-draft:`;function fc(e){return`${dc}${e}`}function pc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function mc(e,t=pc()){try{return t?.getItem(fc(e))??``}catch{return``}}function hc(e,t,n=pc()){try{t?n?.setItem(fc(e),t):n?.removeItem(fc(e))}catch{}}function gc(e,t=pc()){try{t?.removeItem(fc(e))}catch{}}function _c(e,t,n=pc()){let r=mc(e,n);r!==``&&(hc(t,r,n),gc(e,n))}var vc=`pi-web:ask-draft:`;function yc(e,t){return`${vc}${e}:${t}`}function bc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function xc(e,t,n=bc()){try{let r=n?.getItem(yc(e,t));return r==null?{}:wc(r)}catch{return{}}}function Sc(e,t,n,r=bc()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(yc(e,t)):r?.setItem(yc(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function Cc(e,t,n=bc()){try{n?.removeItem(yc(e,t))}catch{}}function wc(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=Tc(r);t!==void 0&&(n[e]=t)}return n}function Tc(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={...e},n=t.values,r=t.otherText;if(!(!Array.isArray(n)||!n.every(e=>typeof e==`string`))&&!(r!==void 0&&typeof r!=`string`))return{values:[...n],...r===void 0?{}:{otherText:r}}}function Ec(e,t){return e.filter(e=>kc(e,t[e.id])!==void 0).length}function Dc(e,t){return e.filter(e=>kc(e,t[e.id])===void 0)}function Oc(e,t){let n=[];for(let r of e){let e=kc(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function kc(e,t){if(t===void 0)return;let n=new Set(e.options.map(e=>e.value)),r=[...new Set(t.values)].filter(e=>n.has(e)),i=Ac(t.otherText);if(e.multiple!==!0&&r.length+(i===void 0?0:1)>1){let t=r[0];return t===void 0?i===void 0?void 0:{id:e.id,values:[],otherText:i}:{id:e.id,values:[t]}}if(!(r.length===0&&i===void 0))return{id:e.id,values:r,...i===void 0?{}:{otherText:i}}}function Ac(e){if(e===void 0)return;let t=e.trim().slice(0,Dt);return t===``?void 0:t}function jc(e,t){return Ms(`bash`,`${t===!0?`excluded from context
3
+ \f\r]`,Be=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ve=/-->/g,He=/>/g,Ue=RegExp(`>|${ze}(?:([^\\s"'>=/]+)(${ze}*=${ze}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),We=/'/g,Ge=/"/g,Ke=/^(?:script|style|textarea|title)$/i,qe=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=qe(1),Je=qe(2),Ye=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Xe=new WeakMap,Ze=Pe.createTreeWalker(Pe,129);function Qe(e,t){if(!Le(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return ke===void 0?t:ke.createHTML(t)}var $e=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Be;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Be?c[1]===`!--`?o=Ve:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ue):(Ke.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ue):o=He:o===Ue?c[0]===`>`?(o=i??Be,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ue:c[3]===`"`?Ge:We):o===Ge||o===We?o=Ue:o===Ve||o===He?o=Be:(o=Ue,i=void 0);let d=o===Ue&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Be?n+Ne:l>=0?(r.push(s),n.slice(0,l)+Ae+n.slice(l)+je+d):n+je+(l===-2?t:d)}return[Qe(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},et=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=$e(t,n);if(this.el=e.createElement(l,r),Ze.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Ze.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Ae)){let t=u[o++],n=i.getAttribute(e).split(je),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?at:r[1]===`?`?ot:r[1]===`@`?st:it}),i.removeAttribute(e)}else e.startsWith(je)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ke.test(i.tagName)){let e=i.textContent.split(je),t=e.length-1;if(t>0){i.textContent=Oe?Oe.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Fe()),Ze.nextNode(),c.push({type:2,index:++a});i.append(e[t],Fe())}}}else if(i.nodeType===8)if(i.data===Me)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(je,e+1))!==-1;)c.push({type:7,index:a}),e+=je.length-1}a++}}static createElement(e,t){let n=Pe.createElement(`template`);return n.innerHTML=e,n}};function tt(e,t,n=e,r){if(t===Ye)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Ie(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=tt(e,i._$AS(e,t.values),i,r)),t}var nt=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Pe).importNode(t,!0);Ze.currentNode=r;let i=Ze.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new rt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ct(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Ze.nextNode(),a++)}return Ze.currentNode=Pe,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},rt=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=tt(this,e,t),Ie(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Ye&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Re(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==_&&Ie(this._$AH)?this._$AA.nextSibling.data=e:this.T(Pe.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=et.createElement(Qe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new nt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Xe.get(e.strings);return t===void 0&&Xe.set(e.strings,t=new et(e)),t}k(t){Le(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Fe()),this.O(Fe()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=De(e).nextSibling;De(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},it=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=_,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=_}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=tt(this,e,t,0),a=!Ie(e)||e!==this._$AH&&e!==Ye,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=tt(this,r[n+o],t,o),s===Ye&&(s=this._$AH[o]),a||=!Ie(s)||s!==this._$AH[o],s===_?e=_:e!==_&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},at=class extends it{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},ot=class extends it{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},st=class extends it{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=tt(this,e,t,0)??_)===Ye)return;let n=this._$AH,r=e===_&&n!==_||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==_&&(n===_||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ct=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){tt(this,e)}},lt={M:Ae,P:je,A:Me,C:1,L:$e,R:nt,D:Re,V:tt,I:rt,H:it,N:ot,U:st,B:at,F:ct},ut=Ee.litHtmlPolyfillSupport;ut?.(et,rt),(Ee.litHtmlVersions??=[]).push(`3.3.3`);var dt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new rt(t.insertBefore(Fe(),e),e,void 0,n??{})}return i._$AI(e),i},ft=globalThis,v=class extends Te{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=dt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ye}};v._$litElement$=!0,v.finalized=!0,ft.litElementHydrateSupport?.({LitElement:v});var pt=ft.litElementPolyfillSupport;pt?.({LitElement:v}),(ft.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},mt={attribute:!0,type:String,converter:Se,reflect:!1,hasChanged:Ce},ht=(e=mt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function b(e){return(t,n)=>typeof n==`object`?ht(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function x(e){return b({...e,state:!0,attribute:!1})}var gt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function S(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return gt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return gt(n,r,{get(){return a(this)}})}}function _t(e,t=yt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(bt(e),n).toString()}function vt(e,t=yt()){let n=new URL(_t(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function yt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function bt(e){return e.startsWith(`/`)?`.${e}`:e}async function C(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(_t(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(xt(e)??i.statusText)}return t(await i.json())}function xt(e){if(St(e))return typeof e.error==`string`?e.error:void 0}function St(e){return typeof e==`object`&&!!e}var Ct={},wt=1e3,Tt=32*1024,Et=8*1024,Dt=1e3,Ot=4e3,kt=1e3,At=4e3,jt=1e4;function Mt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Nt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Mt(e)}var Pt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Ft=/^sha256:[0-9a-f]{64}$/u,It=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Lt=new Set([`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Rt(e){if(!Ut(e)||Object.keys(e).some(e=>!Pt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Ft.test(n))&&!(typeof r!=`string`||!zt(r))&&!(typeof i!=`string`||!Bt(i))&&Ht(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEB_AGENT_SESSION_DIR`||a.some(e=>!Lt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function zt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Bt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):It.test(e)}function Bt(e){if(e===``||e!==e.trim()||Vt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Vt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Ht(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wt=Object.values(Ct),Gt=new Set(Wt);function Kt(e){return typeof e==`string`&&Gt.has(e)}function qt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Kt)}function Jt(e){return typeof e==`object`&&!!e}function w(e){if(!Jt(e))throw Error(`Expected object response`);return e}function T(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function E(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function D(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function O(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function k(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Yt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Xt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Zt(e){let t=w(e);return{messages:Yt(t.messages),start:D(t,`start`),total:D(t,`total`)}}function Qt(e){let t=w(e);return k($t)(t.machines)}function $t(e){let t=w(e),n=nn(t,`kind`),r=E(t,`baseUrl`),i=rn(t,`status`),a=E(t,`statusMessage`);return{id:T(t,`id`),name:T(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:T(t,`createdAt`),updatedAt:T(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function en(e){let t=w(e),n=rn(t,`status`),r=E(t,`error`);return{machineId:T(t,`machineId`),ok:O(t,`ok`),checkedAt:T(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:zi(t.web)},...t.sessiond===void 0?{}:{sessiond:zi(t.sessiond)},...r===void 0?{}:{error:r}}}function tn(e){let t=w(e),n=E(t,`error`);return{machineId:T(t,`machineId`),ok:O(t,`ok`),checkedAt:T(t,`checkedAt`),...M(`packageName`,E(t,`packageName`)),...M(`generatedAt`,E(t,`generatedAt`)),...t.components===void 0?{}:{components:Li(t.components)},...t.capabilities===void 0?{}:{capabilities:Gi(t.capabilities)},...n===void 0?{}:{error:n}}}function nn(e,t){let n=T(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function rn(e,t){let n=E(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function an(e){let t=w(e);return{id:T(t,`id`),name:T(t,`name`),path:T(t,`path`),createdAt:T(t,`createdAt`)}}function on(e){let t=w(e),n=E(t,`branch`);return{id:T(t,`id`),projectId:T(t,`projectId`),path:T(t,`path`),label:T(t,`label`),...n===void 0?{}:{branch:n},isMain:O(t,`isMain`),isGitRepo:O(t,`isGitRepo`),isGitWorktree:O(t,`isGitWorktree`),effectiveConfig:sn(t.effectiveConfig)}}function sn(e){if(!Jt(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);return{...M(`uploads`,_i(e.uploads))}}function cn(e){let t=w(e),n=E(t,`name`),r=Mi(t.persisted,`persisted`),i=E(t,`parentSessionPath`),a=E(t,`parentSessionCwd`),o=E(t,`parentSessionId`),s=Ni(t.childSessionsElsewhere,`childSessionsElsewhere`),c=E(t,`archivedAt`);return{id:T(t,`id`),path:T(t,`path`),cwd:T(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:T(t,`created`),modified:T(t,`modified`),messageCount:D(t,`messageCount`),firstMessage:T(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...a===void 0?{}:{parentSessionCwd:a},...o===void 0?{}:{parentSessionId:o},...s===void 0?{}:{childSessionsElsewhere:s},...t.archived===!0?{archived:!0}:{},...c===void 0?{}:{archivedAt:c}}}function ln(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function un(e){if(e!==void 0)return{id:T(w(e),`id`)}}function dn(e){let t=w(e),n=un(t.dismiss);return{severity:ln(t.severity),message:T(t,`message`),...M(`source`,E(t,`source`)),...M(`path`,E(t,`path`)),...n===void 0?{}:{dismiss:n}}}function fn(e){return e===void 0?{}:{warnings:k(dn)(e)}}function pn(e){let t=w(e);return{value:A(t,`value`,128),label:A(t,`label`,Dt),...M(`detail`,Qn(t,`detail`,Dt))}}function mn(e){let t=w(e),n=lr(t.options,pn,12,`options`);wn(n.map(e=>e.value),`ask option value`);let r=Mi(t.multiple,`multiple`);return{id:A(t,`id`,128),question:A(t,`question`,Dt),...M(`detail`,Qn(t,`detail`,Dt)),options:n,...r===void 0?{}:{multiple:r}}}function hn(e){let t=w(e),n=lr(t.questions,mn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return wn(n.map(e=>e.id),`ask question id`),{askId:A(t,`askId`,128),askedAt:j(t,`askedAt`),questions:n}}function gn(e){return e===void 0?{}:{pendingAsk:hn(e)}}function _n(e){let t=w(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:hn(t.ask)}}function vn(e){let t=w(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:A(t,`askId`,128),reason:yn(t.reason)}}function yn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function bn(e){let t=w(e),n=mn(t.question),r=lr(t.values,ur,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=Qn(t,`otherText`,Ot),o=O(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function xn(e){let t=w(e),n=lr(t.questions,bn,20,`questions`),r=dr(t,`answeredCount`),i=Xt(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:A(t,`askId`,128),reason:yn(t.reason),askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:j(t,`summary`)}}function Sn(e){let t=w(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:xn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Fn(t.sessionStatus)}}function Cn(e){let t=w(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Nn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Fn(t.sessionStatus)}}function wn(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Tn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function En(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function Dn(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function On(e){let t=ur(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function kn(e){let t=w(e),n=Tn(t.kind),r=t.options===void 0?void 0:lr(t.options,On,24,`options`);if(r!==void 0&&wn(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:A(t,`dialogId`,128),kind:n,title:A(t,`title`,kt),...M(`message`,Qn(t,`message`,kt)),...r===void 0?{}:{options:r},...M(`placeholder`,Qn(t,`placeholder`,kt)),askedAt:j(t,`askedAt`),...M(`timeoutAt`,Pn(t,`timeoutAt`)),runScoped:O(t,`runScoped`)}}function An(e){if(e===void 0)return{};let t=k(kn)(e);return wn(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function jn(e){let t=w(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:kn(t.dialog)}}function Mn(e){let t=w(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=En(t.reason),r=t.answer===void 0?void 0:Dn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:A(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Nn(e){let t=w(e),n=En(t.reason),r=t.answer===void 0?void 0:Dn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:A(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`)}}function Pn(e,t){let n=E(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function Fn(e){let t=w(e);return{sessionId:T(t,`sessionId`),...M(`persisted`,Mi(t.persisted,`persisted`)),isStreaming:O(t,`isStreaming`),isCompacting:O(t,`isCompacting`),isBashRunning:O(t,`isBashRunning`),pendingMessageCount:D(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:k(wr)(t.queuedMessages),...M(`messageCount`,ha(t,`messageCount`)),tokens:Tr(t.tokens),cost:D(t,`cost`),...Dr(t.model),...Gr(t.contextUsage),...M(`thinkingLevel`,E(t,`thinkingLevel`)),...fn(t.warnings),...gn(t.pendingAsk),...An(t.pendingDialogs)}}function In(e){let t=w(e);return{seq:D(t,`seq`),partial:t.partial??null}}function Ln(e){let t=w(e),n=dr(t,`catalogRevision`),r=lr(t.sessions,Yn,wt,`sessions`);if(Xn(r),Zn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:A(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Rn(e){let t=w(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=A(t,`sessionId`,512),r=A(t,`cwd`,Tt),i=$n(t,`catalogRevision`),a=t.unread===null?null:Yn(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:A(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function zn(e){let t=w(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=E(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:Bn(t.activity)}}function Bn(e){let t=w(e);return{sessionId:j(t,`sessionId`),phase:Hn(t,`phase`),label:j(t,`label`),...M(`detail`,E(t,`detail`)),at:j(t,`at`),...M(`startup`,Vn(t))}}function Vn(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function Hn(e,t){let n=T(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function Un(e){let t=w(e);switch(t.type){case`message.append`:return{type:`message.append`,message:Gn(t,`message`)};case`assistant.delta`:return{type:`assistant.delta`,text:T(t,`text`)};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:T(t,`text`)};case`tool.start`:return{type:`tool.start`,toolName:T(t,`toolName`),toolCallId:T(t,`toolCallId`),summary:T(t,`summary`),...M(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:T(t,`toolName`),toolCallId:T(t,`toolCallId`),text:T(t,`text`),...M(`content`,t.content),...M(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:T(t,`toolName`),toolCallId:T(t,`toolCallId`),text:T(t,`text`),isError:O(t,`isError`),...M(`content`,t.content),...M(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:T(t,`command`),...M(`excludeFromContext`,Mi(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:T(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...M(`output`,E(t,`output`)),...M(`exitCode`,Kn(t,`exitCode`)),...M(`cancelled`,Mi(t.cancelled,`cancelled`)),...M(`truncated`,Mi(t.truncated,`truncated`)),...M(`fullOutputPath`,E(t,`fullOutputPath`)),...M(`isError`,Mi(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...M(`message`,t.message)};case`status.update`:return{type:`status.update`,status:Fn(t.status)};case`activity.update`:return{type:`activity.update`,activity:Bn(t.activity)};case`command.output`:return qn(t);case`session.error`:return{type:`session.error`,message:T(t,`message`)};case`session.name`:return Jn(t);case`session.created`:return{type:`session.created`,session:cn(t.session)};case`pi.event`:return{type:`pi.event`,eventType:T(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function Wn(e){let t=w(e);switch(t.type){case`status.update`:return{type:`status.update`,status:Fn(t.status)};case`activity.update`:return{type:`activity.update`,activity:Bn(t.activity)};case`session.name`:return Jn(t);case`session.created`:return{type:`session.created`,session:cn(t.session)};case`terminal.created`:return{type:`terminal.created`,terminal:ai(t.terminal)};case`terminal.exited`:return{type:`terminal.exited`,terminal:ai(t.terminal)};case`terminal.closed`:return{type:`terminal.closed`,terminalId:j(t,`terminalId`),cwd:j(t,`cwd`)};case`workspace.activity`:return{type:`workspace.activity`,activity:li(t.activity)};default:throw Error(`Unsupported realtime stream event type`)}}function Gn(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function Kn(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function qn(e){let t=T(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:T(e,`message`)}}function Jn(e){return{type:`session.name`,sessionId:j(e,`sessionId`),...M(`name`,E(e,`name`))}}function Yn(e){let t=w(e),n=A(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:A(t,`sessionId`,512),cwd:A(t,`cwd`,Tt),completionOrder:$n(t,`completionOrder`),completedAt:n}}function Xn(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function Zn(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function A(e,t,n){let r=j(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Qn(e,t,n){let r=E(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function $n(e,t){let n=dr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function er(e){let t=w(e),n=nr(t.summary),r=lr(t.notifications,rr,100,`notifications`);if(fr(r),pr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==hr(r))throw Error(`Notification snapshot severity mismatch`);let i=ir(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:j(t,`daemonInstanceId`),catalogRevision:dr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function tr(e){let t=w(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=nr(t.summary),r=ir(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=ar(t.delta);if(i.kind===`cleared`&&!mr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:j(t,`daemonInstanceId`),catalogRevision:dr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function nr(e){let t=w(e),n=dr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=dr(t,`discardedCount`),i=sr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:j(t,`sessionId`),cwd:j(t,`cwd`),inboxRevision:dr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function rr(e){let t=w(e),n=T(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=T(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=dr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:j(t,`id`),message:n,truncated:O(t,`truncated`),severity:or(t.severity),receivedAt:r,order:i}}function ir(e){let t=w(e);return{order:dr(t,`order`),overflowWatermark:dr(t,`overflowWatermark`)}}function ar(e){let t=w(e);switch(t.kind){case`added`:{let e=E(t,`evictedNotificationId`);return{kind:`added`,notification:rr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=lr(t.notificationIds,ur,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:cr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function or(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function sr(e){return e===void 0?void 0:or(e)}function cr(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function lr(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function ur(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function j(e,t){let n=T(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function dr(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function fr(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function pr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function mr(e){return e.retainedCount===0&&e.discardedCount===0}function hr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function gr(e){let t=w(e),n=t.skippedBusySessionIds===void 0?void 0:Xt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:T(t,`generatedAt`),thresholds:xr(t.thresholds),projects:k(Sr)(t.projects),totals:Cr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function _r(e){let t=w(e);return{...gr(t),archivedSessionIds:Xt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Xt(t.deletedSessionIds,`deletedSessionIds`)}}function vr(e){let t=w(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Xt(t.archivedSessionIds,`archivedSessionIds`),failures:k(br)(t.failures),generatedAt:T(t,`generatedAt`)}}function yr(e){let t=w(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Xt(t.deletedSessionIds,`deletedSessionIds`),failures:k(br)(t.failures),generatedAt:T(t,`generatedAt`)}}function br(e){let t=w(e);return{sessionId:T(t,`sessionId`),error:T(t,`error`)}}function xr(e){let t=w(e);return{...M(`archiveIdleDays`,ha(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,ha(t,`deleteArchivedDays`))}}function Sr(e){let t=w(e);return{cwd:T(t,`cwd`),archiveCount:D(t,`archiveCount`),deleteCount:D(t,`deleteCount`)}}function Cr(e){let t=w(e);return{archiveCount:D(t,`archiveCount`),deleteCount:D(t,`deleteCount`)}}function wr(e){let t=w(e),n=T(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:T(t,`text`)}}function Tr(e){let t=w(e);return{input:D(t,`input`),output:D(t,`output`),cacheRead:D(t,`cacheRead`),cacheWrite:D(t,`cacheWrite`),total:D(t,`total`)}}function Er(e){let t=w(e);return{...M(`provider`,E(t,`provider`)),...M(`id`,E(t,`id`)),...M(`name`,E(t,`name`)),...M(`contextWindow`,ha(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Dr(e){return e===void 0?{}:{model:Er(e)}}function Or(e){let t=w(e);return{models:k(Er)(t.models)}}function kr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ar(e){let t=w(e);return{levels:k(kr)(t.levels)}}function jr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Mr(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Nr(e){let t=w(e),n=t.source===void 0?void 0:Mr(t.source);return{configured:O(t,`configured`),...M(`source`,n),...M(`label`,E(t,`label`))}}function Pr(e){let t=w(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:T(t,`id`),name:T(t,`name`),authType:jr(t.authType),status:Nr(t.status),...n===void 0?{}:{loginFlow:n}}}function Fr(e){let t=w(e);return{providers:k(Pr)(t.providers)}}function Ir(e){let t=w(e);return{flowId:T(t,`flowId`),providerId:T(t,`providerId`),providerName:T(t,`providerName`),status:Lr(t.status),progress:k(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,E(t,`error`)),...M(`auth`,Rr(t.auth)),...M(`prompt`,Br(t.prompt)),...M(`select`,Hr(t.select)),...M(`info`,Ur(t.info))}}function Lr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Rr(e){if(e===void 0)return;let t=w(e);return{url:T(t,`url`),...M(`instructions`,E(t,`instructions`)),...M(`deviceCode`,zr(t.deviceCode))}}function zr(e){if(e===void 0)return;let t=w(e);return{userCode:T(t,`userCode`),...M(`intervalSeconds`,ha(t,`intervalSeconds`)),...M(`expiresInSeconds`,ha(t,`expiresInSeconds`))}}function Br(e){if(e===void 0)return;let t=w(e);return{requestId:T(t,`requestId`),message:T(t,`message`),promptType:Vr(t.promptType),...M(`placeholder`,E(t,`placeholder`)),...M(`allowEmpty`,ma(t,`allowEmpty`))}}function Vr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Hr(e){if(e===void 0)return;let t=w(e);return{requestId:T(t,`requestId`),message:T(t,`message`),options:k(na)(t.options)}}function Ur(e){if(e!==void 0)return k(e=>{let t=w(e);return{message:T(t,`message`),...M(`links`,t.links===void 0?void 0:k(Wr)(t.links))}})(e)}function Wr(e){let t=w(e);return{url:T(t,`url`),...M(`label`,E(t,`label`))}}function Gr(e){if(e===void 0)return{};let t=w(e);return{contextUsage:{tokens:ga(t,`tokens`),contextWindow:D(t,`contextWindow`),percent:ga(t,`percent`)}}}function Kr(e){let t=w(e),n=T(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:T(t,`name`),source:n,...M(`description`,E(t,`description`))}}function qr(e){let t=w(e),n=T(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:T(t,`path`),kind:n}}function Jr(e){let t=w(e);return{path:T(t,`path`),entries:k(Yr)(t.entries),scannedAt:T(t,`scannedAt`),truncated:O(t,`truncated`)}}function Yr(e){let t=w(e),n=T(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:T(t,`name`),path:T(t,`path`),type:n,...M(`size`,ha(t,`size`)),...M(`modifiedAt`,E(t,`modifiedAt`))}}function Xr(e){let t=w(e),n=T(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:T(t,`path`),...M(`language`,E(t,`language`)),...M(`mediaType`,ei(t.mediaType)),...M(`mimeType`,E(t,`mimeType`)),encoding:n,size:D(t,`size`),modifiedAt:T(t,`modifiedAt`),content:T(t,`content`),truncated:O(t,`truncated`),binary:O(t,`binary`)}}function Zr(e){let t=w(e);return{path:T(t,`path`),size:D(t,`size`),modifiedAt:T(t,`modifiedAt`),created:O(t,`created`)}}function Qr(e){let t=w(e);return{path:T(t,`path`),existed:O(t,`existed`)}}function $r(e){let t=w(e);return{fromPath:T(t,`fromPath`),toPath:T(t,`toPath`),size:D(t,`size`),modifiedAt:T(t,`modifiedAt`)}}function ei(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function ti(e){let t=w(e);return{isGitRepo:O(t,`isGitRepo`),hash:T(t,`hash`),...M(`branch`,E(t,`branch`)),...M(`upstream`,E(t,`upstream`)),...M(`ahead`,ha(t,`ahead`)),...M(`behind`,ha(t,`behind`)),files:k(ni)(t.files),submodules:t.submodules===void 0?[]:Xt(t.submodules,`submodules`)}}function ni(e){let t=w(e);return{path:T(t,`path`),...M(`oldPath`,E(t,`oldPath`)),index:ri(t.index),workingTree:ri(t.workingTree),...M(`submoduleFromCommit`,E(t,`submoduleFromCommit`)),...M(`submoduleToCommit`,E(t,`submoduleToCommit`))}}function ri(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 Error(`Invalid git file state`)}}function ii(e){let t=w(e);return{...M(`path`,E(t,`path`)),staged:O(t,`staged`),hash:T(t,`hash`),diff:T(t,`diff`),truncated:O(t,`truncated`)}}function ai(e){let t=w(e);return{id:T(t,`id`),cwd:T(t,`cwd`),name:T(t,`name`),createdAt:T(t,`createdAt`),exited:O(t,`exited`),...M(`exitCode`,ha(t,`exitCode`)),...M(`commandRunId`,E(t,`commandRunId`))}}function oi(e){let t=w(e);return{id:T(t,`id`),origin:T(t,`origin`),projectId:T(t,`projectId`),workspaceId:T(t,`workspaceId`),terminalId:T(t,`terminalId`),title:T(t,`title`),command:T(t,`command`),status:si(t.status),...M(`exitCode`,ha(t,`exitCode`)),createdAt:T(t,`createdAt`),...M(`startedAt`,E(t,`startedAt`)),...M(`completedAt`,E(t,`completedAt`)),metadata:ci(t.metadata,`metadata`)}}function si(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ci(e,t){let n=w(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function li(e){let t=w(e);return{cwd:T(t,`cwd`),hasSessionActivity:O(t,`hasSessionActivity`),hasTerminalActivity:O(t,`hasTerminalActivity`),updatedAt:T(t,`updatedAt`)}}function ui(e){let t=w(e);return{workspaces:k(li)(t.workspaces),generatedAt:T(t,`generatedAt`)}}function di(e){let t=w(e);return{path:T(t,`path`),exists:O(t,`exists`),config:fi(t.config),effectiveConfig:fi(t.effectiveConfig),envOverrides:Si(t.envOverrides)}}function fi(e){let t=w(e);return{...M(`host`,E(t,`host`)),...M(`port`,ha(t,`port`)),...M(`allowedHosts`,mi(t.allowedHosts)),...M(`shortcuts`,bi(t.shortcuts)),...M(`plugins`,xi(t.plugins)),...M(`pathAccess`,hi(t.pathAccess)),...M(`uploads`,_i(t.uploads)),...M(`maxUploadBytes`,ha(t,`maxUploadBytes`)),...M(`agent`,pi(t.agent)),...M(`spawnSessions`,ma(t,`spawnSessions`)),...M(`subsessions`,ma(t,`subsessions`)),...M(`askUser`,ma(t,`askUser`))}}function pi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,E(e,`command`)),...M(`dir`,E(e,`dir`))}}}function mi(e){if(e!==void 0){if(e===!0)return!0;if(vi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function hi(e){if(e===void 0)return;if(!Jt(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,gi(t,`pathAccess.allowedPaths`))}}function gi(e,t){if(e!==void 0){if(yi(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function _i(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,E(e,`defaultFolder`))}}}function vi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function yi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function bi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function xi(e){if(e!==void 0){if(!Jt(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!Jt(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!Jt(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Si(e){let t=w(e);return{host:O(t,`host`),port:O(t,`port`),allowedHosts:O(t,`allowedHosts`),spawnSessions:O(t,`spawnSessions`),subsessions:O(t,`subsessions`),askUser:O(t,`askUser`),agentCommand:O(t,`agentCommand`),agentDir:O(t,`agentDir`),...Ci(t),agentSessionDir:O(t,`agentSessionDir`)}}function Ci(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function wi(e){let t=w(e);return{packages:k(Ei)(t.packages)}}function Ti(e){let t=w(e),n=E(t,`source`),r=t.scope===void 0?void 0:Di(t.scope),i=Mi(t.removed,`removed`);return{action:Oi(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:k(Ei)(t.packages)}}function Ei(e){let t=w(e);return{source:T(t,`source`),scope:Di(t.scope),filtered:O(t,`filtered`),...M(`installedPath`,E(t,`installedPath`))}}function Di(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Oi(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function ki(e){let t=w(e);return{plugins:k(Ai)(t.plugins)}}function Ai(e){let t=w(e);return{id:T(t,`id`),module:T(t,`module`),source:T(t,`source`),scope:ji(t.scope),machineSpecific:Mi(t.machineSpecific,`machineSpecific`)??!1,enabled:O(t,`enabled`)}}function ji(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function Mi(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Ni(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`Expected optional count field: ${t}`);return e===0?void 0:e}}function Pi(e){let t=w(e);return{packageName:T(t,`packageName`),generatedAt:T(t,`generatedAt`),components:Ii(t.components),release:Vi(t.release),commands:Hi(t.commands),messages:k(Ui)(t.messages)}}function Fi(e){let t=w(e);return{packageName:T(t,`packageName`),generatedAt:T(t,`generatedAt`),components:Li(t.components),capabilities:Gi(t.capabilities)}}function Ii(e){let t=w(e);return{web:zi(t.web),sessiond:zi(t.sessiond)}}function Li(e){let t=w(e);return{web:Ri(t.web),sessiond:Ri(t.sessiond)}}function Ri(e){let t=w(e),n=Wi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Rt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:T(t,`label`),...M(`runtimeVersion`,E(t,`runtimeVersion`)),available:O(t,`available`),capabilities:Gi(t.capabilities),...M(`activeAgentProfile`,i),...M(`error`,E(t,`error`))}}function zi(e){let t=w(e);return{component:Wi(t.component),label:T(t,`label`),...M(`runtimeVersion`,E(t,`runtimeVersion`)),...M(`installedVersion`,E(t,`installedVersion`)),stale:O(t,`stale`),available:O(t,`available`),...M(`installation`,Bi(t.installation)),...M(`error`,E(t,`error`))}}function Bi(e){if(e===void 0)return;let t=w(e),n=T(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...M(`path`,E(t,`path`)),...M(`source`,E(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,E(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Vi(e){let t=w(e);return{packageName:T(t,`packageName`),...M(`latestVersion`,E(t,`latestVersion`)),updateAvailable:O(t,`updateAvailable`),...M(`checkedAt`,E(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,E(t,`error`))}}function Hi(e){let t=w(e);return{...M(`update`,E(t,`update`)),...M(`restart`,E(t,`restart`)),...M(`restartWeb`,E(t,`restartWeb`)),...M(`restartSessiond`,E(t,`restartSessiond`)),...M(`status`,E(t,`status`))}}function Ui(e){let t=w(e);return{id:T(t,`id`),severity:Ki(t.severity),title:T(t,`title`),body:T(t,`body`),...M(`command`,E(t,`command`))}}function Wi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function Gi(e){let t=qt(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Ki(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function qi(e){let t=w(e),n=T(t,`type`);if(n===`unsupported`)return{type:n,message:T(t,`message`)};if(n===`select`)return{type:n,requestId:T(t,`requestId`),title:T(t,`title`),options:k(na)(t.options)};if(n===`tree`)return{type:n,tree:Ji(t.tree)};if(n===`done`)return{type:n,...M(`message`,E(t,`message`)),...ra(t.session),...M(`promptDraft`,E(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Ji(e){let t=w(e),n=k(Yi)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=$i(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:ta(t.activePathIds,`activePathIds`)}}function Yi(e){let t=w(e);return{id:ea(t,`id`),parentId:$i(t,`parentId`),kind:Xi(t.kind),summary:T(t,`summary`),...M(`timestamp`,E(t,`timestamp`)),...M(`label`,E(t,`label`))}}function Xi(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Zi(e){let t=w(e),n=O(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Qi(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return Qi(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,E(t,`editorText`))}}function Qi(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function $i(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function ea(e,t){let n=T(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function ta(e,t){let n=Xt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function na(e){let t=w(e);return{value:T(t,`value`),label:T(t,`label`),...M(`description`,E(t,`description`))}}function ra(e){return e===void 0?{}:{session:cn(e)}}function ia(e){if(w(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function aa(e){let t=w(e);return k(oa)(t.attachments)}function oa(e){let t=w(e);return{path:T(t,`path`),mimeType:T(t,`mimeType`),size:D(t,`size`)}}function sa(e){if(w(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function ca(e){if(w(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function la(e){if(w(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ua(e){let t=w(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Xt(t.sessionIds,`sessionIds`),r=ha(t,`archivedCount`),i=ha(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function da(e){if(w(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function fa(e){if(w(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function pa(e){if(w(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function ma(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function ha(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function ga(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function M(e,t){return t===void 0?{}:{[e]:t}}function _a(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function va(e,t,n=`local`){let r=new URLSearchParams;return r.set(`cwd`,e.cwd),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before)),`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(e.id)}/messages?${r.toString()}`}function ya(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),_t(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function ba(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),_t(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function xa(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(e.id)}`}function P(e,t,n=`local`){return`${xa(e,n)}/${t}`}function Sa(e,t,n=`local`){return`${P(e,t,n)}${Ca(e)}`}function Ca(e){return`?${new URLSearchParams({cwd:e.cwd}).toString()}`}function F(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function wa(e){return JSON.stringify({sessions:e.map(Ta)})}function Ta(e){return{id:e.id,cwd:e.cwd}}function Ea(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var Da={piWebStatus:(e=`local`)=>C(Ea(e),Pi),checkForUpdates:(e=`local`)=>C(`${Ea(e)}?refresh=1`,Pi,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,Fi)},Oa={machines:()=>C(`api/machines`,Qt),addMachine:e=>C(`api/machines`,$t,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,en),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,tn,t?{cache:`no-store`}:{})};function ka(e){return e===void 0?`api/config`:`${N(e)}/config`}function Aa(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var ja={config:e=>C(ka(e),di),saveConfig:(e,t)=>C(ka(t),di,{method:`PUT`,body:JSON.stringify({config:e})})},Ma={plugins:e=>C(Aa(e),ki)};function Na(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Pa={packages:e=>C(Na(``,e),wi),install:(e,t)=>{let n={source:e};return C(Na(`install`,t),Ti,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(Na(`remove`,n),Ti,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(Na(`update`,t),Ti,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Fa={workspaceActivity:(e=`local`)=>C(`${N(e)}/activity`,ui)},Ia={projects:(e=`local`)=>C(`${N(e)}/projects`,k(an)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,an,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,sa,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,k(qr))},La={workspaces:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,k(on)),deleteWorkspace:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,oi,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Jr),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Xr),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Zr,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Qr,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,$r,{method:`POST`})}},Ra={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,k(cn)),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,Ln,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return C(P(e,`unread/acknowledge`,r),Ln,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(Sa(e,`notifications`,t),er),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),er,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),er,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,cn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,gr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,_r,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,vr,{method:`POST`,body:wa(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,yr,{method:`POST`,body:wa(e)}),messages:(e,t,n=`local`)=>C(va(e,t,n),Zt),status:(e,t=`local`)=>C(Sa(e,`status`,t),Fn),streamSnapshot:(e,t=`local`)=>C(Sa(e,`stream-snapshot`,t),In),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),Fn,{method:`POST`,body:F(e)}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),Fn,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Sn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Sn,{method:`POST`,body:F(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(P(e,`dialogs/answer`,r),Cn,{method:`POST`,body:F(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(P(e,`dialogs/cancel`,n),Cn,{method:`POST`,body:F(e,{dialogId:t})}),models:(e,t=`local`)=>C(Sa(e,`models`,t),Or),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),Fn,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),Fn,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(Sa(e,`thinking-levels`,t),Ar),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),Fn,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),Fn,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(Sa(e,`commands`,t),k(Kr)),prompt:(e,t,n,r=`local`,i)=>C(P(e,`prompt`,r),ia,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),aa,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),ia,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),qi,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),qi,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),Zi,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),abort:(e,t=`local`)=>C(P(e,`abort`,t),ca,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),la,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),ua,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),ua,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),da,{method:`POST`,body:F(e)}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),fa,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),pa,{method:`POST`,body:F(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return C(`${N(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Fr)},startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${N(t)}/auth/api-key/interactive`,Ir,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${N(t)}/auth/logout`,ia,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${N(t)}/auth/oauth`,Ir,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}`,Ir),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${N(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,Ir,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Ir,{method:`POST`})},za={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,k(ai)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ai,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,sa,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,sa,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ai,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,oi,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs${Va(e)}`,k(oi)),getCommandRun:(e,t=`local`)=>Ba(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,oi,{method:`POST`})};async function Ba(e,t){let n=await fetch(_t(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(Ha(e)??n.statusText)}return oi(await n.json())}}function Va(e){if(e===void 0)return``;let 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));let n=t.toString();return n===``?``:`?${n}`}function Ha(e){if(!Ua(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Ua(e){return typeof e==`object`&&!!e}var Wa={files:(e,t)=>{let n=new URLSearchParams({q:e});return t.kind!==void 0&&n.set(`kind`,t.kind),t.mode!==void 0&&n.set(`mode`,t.mode),t.scope!==void 0&&n.set(`scope`,t.scope),C(`${N(t.machineId)}/projects/${encodeURIComponent(t.projectId)}/workspaces/${encodeURIComponent(t.workspaceId)}/files?${n.toString()}`,k(qr))}},Ga={gitStatus:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,ti),gitDiff:(e,t,n,r=`local`)=>C(_a(r,e,t,n),ii)},I={...Da,...Oa,...ja,...Ma,...Pa,...Fa,...Ia,...La,...Ra,...za,...Wa,...Ga};function Ka(e,t=`local`){let n=`?${new URLSearchParams({cwd:e.cwd}).toString()}`;return new WebSocket(vt(`${Ya(t)}/sessions/${encodeURIComponent(e.id)}/events${n}`))}function qa(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(vt(`${Ya(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Ja(e=`local`){return new WebSocket(vt(`${Ya(e)}/events`))}function Ya(e){return`api/machines/${encodeURIComponent(e)}`}var Xa=`.pi-web/uploads`,Za=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Qa=class extends Error{constructor(e,t){super(lo(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function $a(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function eo(e,t){return e.uploads?.defaultFolder??t}function to(e,t){let n=po(e,`upload destination`,{allowEmpty:!0}),r=po(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function no(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,ya(e,t,n.path,ao(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(oo(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(Zr(ho(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(go(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Za(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function ro(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:to(i,e.name),loaded:0,total:e.size,percent:co(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(so(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new Za;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=no(e,t,{path:p.path,file:f},{...io(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(fo(e,c))throw e;let t=uo(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new Qa(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function io(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function ao(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function oo(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:co(e.loaded,n),lengthComputable:e.lengthComputable}}function so(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:co(i,r),done:n}}function co(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function lo(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function uo(e){return e instanceof Error?e.message:String(e)}function fo(e,t){return t.requested||e instanceof Za}function po(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(mo(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function mo(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function ho(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function go(e){let t=_o(e);return vo(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function _o(e){try{return ho(e)}catch{return}}function vo(e){return typeof e==`object`&&!!e}function yo(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,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 bo(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog: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,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function xo(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function So(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Co(e,t){return`${e}:${t}`}function wo(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var To=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Eo=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new To,this.api=n.api??Fa,this.onActivityApplied=n.onActivityApplied}refresh(e=L(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Do(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=L(this.getState())){let n=this.getState(),r=L(n)===t,i=Oo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...L(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Do(e){let t={};for(let n of e.workspaces)So(n)&&(t[n.cwd]=n);return t}function Oo(e,t){let n={...e};return So(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var ko=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=jo(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:L(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`)&&await this.startLoginFlow(r)}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:L(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,L(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Ao(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Ao(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:L(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;(r.authType===`oauth`||r.loginFlow===`interactive`)&&await this.startLoginFlow(r)}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=L(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEB instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Ao(n.flow):void 0,a=Ao(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=Ao(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||Ao(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Ao(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=L(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(L(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Ao(e){return e.prompt?.requestId??e.select?.requestId}function jo(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function Mo(e){return e.replaceAll(`:`,`.`)}function No(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function Po(e,t){let n=No(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Fo(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));Io(i,r)}function Io(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function Lo(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:to(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:Uo(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:Uo(0,n),status:`uploading`,startedAt:e.startedAt}}function Ro(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function zo(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=Ho(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function Bo(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...Ho(r),status:`error`,error:t,completedAt:n}}function Vo(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...Ho(r),status:`cancelled`,error:n,completedAt:t}}function Ho(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Uo(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var Wo=Mo(`core:workspace.files`),Go=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??ro,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=L(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:Yo(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,L(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Fo(Wo,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,L(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(Ko(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Fo(Wo,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=Lo({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(Vo(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:Yo(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(Ro(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(zo(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof Qa)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(qo(t)){let e=Vo(n,this.now());return this.setUploadBatch(e),e}let r=Jo(t),i=Bo(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function Ko(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function qo(e){return e instanceof Za}function Jo(e){return e instanceof Error?e.message:String(e)}function Yo(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Xo=Mo(`core:workspace.git`),Zo=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=await I.gitStatus(e.id,t.id,L(this.getState()));this.setState({gitStatus:n,gitStale:!1,error:``});let r=this.getState().selectedDiffPath;r!==void 0&&(n.files.some(e=>e.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Fo(Xo,`diff`,void 0,{replace:!0})))}catch(e){this.setState({error:String(e)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),Fo(Xo,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0))try{let[r,i]=await Promise.all([I.gitDiff(t.id,n.id,{path:e},L(this.getState())),I.gitDiff(t.id,n.id,{path:e,staged:!0},L(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:i,error:``})}catch(e){this.setState({error:String(e)})}}updatePolling(){this.dispose();let e=this.getState();(e.workspaceTool===`core:workspace.git`||e.mainView===`core:workspace.git`)&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}},Qo=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await I.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:es(this.getState().machineActivities,r),machineRuntimes:es(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...yo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await I.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await I.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:$o(this.getState().machineStatuses,e.id),machineRuntimes:$o(this.getState().machineRuntimes,e.id),machineActivities:$o(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await I.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await I.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await I.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>I.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>I.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function $o(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function es(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var ts=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=L(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(L(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=L(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(L(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){L(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=L(this.getState());try{if(await this.api.closeProject(e,t),L(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}};function ns(e,t){return t[e.path]}function rs(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function is(e,t,n){return ss(cs(e,t,n))}function as(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function os(e){return ss(Object.values(e??{}))}function ss(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function cs(e,t,n){return Object.values(n).filter(n=>as(e,t,n.cwd))}var ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??La,this.onError=n.onError}handleActivityApplied(e){return L(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return L(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(L(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!us(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!us(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(L(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&L(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(So).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function us(e,t,n){return e.some(e=>as(e,t[e.id]??[],n))}var ds=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Da,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=L(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=L(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),fs(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return L(this.getState())===e&&t===this.requestSequence}};function fs(e){if(e.release.error!==void 0)throw Error(`PI WEB update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`)}var ps=`pi-web:cached-new-sessions:v1`,ms=`browserCachedNew`,hs=`local`;function gs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function _s(e,t=hs,n=gs()){if(e.messageCount!==0||e.archived===!0)return;let r=Cs(n).filter(n=>n.id!==e.id||n.machineId!==t);ws([vs(e,t),...r],n)}function vs(e,t=hs){return{...e,browserCachedNew:!0,machineId:t}}function ys(e,t=hs,n=gs()){ws(Cs(n).filter(n=>n.id!==e||n.machineId!==t),n)}function bs(e,t,n=hs,r=gs()){let i=new Set(t.map(e=>e.id)),a=Cs(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&ws(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function xs(e){return e!==void 0&&Es(e)&&e.browserCachedNew===!0}function Ss(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...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:hs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Cs(e=gs()){try{let t=e?.getItem(ps);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Ts(e)):[]}catch{return[]}}function ws(e,t=gs()){try{e.length===0?t?.removeItem(ps):t?.setItem(ps,JSON.stringify(e))}catch{}}function Ts(e){if(!Ds(e))return[];let t=Os(e,`id`),n=Os(e,`path`),r=Os(e,`cwd`),i=Os(e,`created`),a=Os(e,`modified`),o=Os(e,`firstMessage`),s=As(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=ks(e,`name`),l=ks(e,`parentSessionPath`),u=ks(e,`machineId`)??hs;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},machineId:u,browserCachedNew:!0}]}function Es(e){return ms in e}function Ds(e){return typeof e==`object`&&!!e}function Os(e,t){let n=e[t];return typeof n==`string`?n:void 0}function ks(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function As(e,t){let n=e[t];return typeof n==`number`?n:void 0}function js(e){return $s(e.flatMap(Is)).filter(e=>e.parts.length>0)}function Ms(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Ns(e,t){let n=Hs(t);return n===void 0?e:{...e,meta:n}}function Ps(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,Ms(t,n)]}function Fs(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function Is(e){if(Rs(e))return[e];if(R(e,`role`)===`bashExecution`)return[Ns(Gs(e),e)];let t=R(e,`role`),n=Ks(t),r=qs(sc(e,`content`),e),i=t===`toolResult`?Ys(R(e,`toolName`)??``,sc(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?zs(a):void 0;if(o!==void 0)return o.map(t=>Ns(t,e));let s=Vs(e);if(n===`tool`)return[Ns({role:n,parts:a,...s===void 0?{}:{source:s}},e)];let c=a.filter(e=>e.type!==`empty`),l=n===`assistant`&&c.length>0&&c.every(e=>e.type===`skillRead`)?`skill`:n,u=c.length>0?[Ns({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Ls(e);return d===void 0?u:[...u,Ns(d,e)]}function Ls(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return Ms(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Rs(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(sc(e,`parts`))}function zs(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Bs(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 Bs(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function Vs(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Hs(e){let t=Us(sc(e,`timestamp`)),n=Ws(e),r=R(e,`thinkingLevel`);if(!(t===void 0&&n===void 0&&(r===void 0||r===``)))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function Us(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Ws(e){if(R(e,`role`)!==`assistant`)return;let t=R(e,`provider`),n=R(e,`model`),r=R(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function Gs(e){let t=R(e,`command`)??``,n=cc(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=sc(e,`output`);r!=null&&n.push(``,uc(r));let i=sc(e,`exitCode`);i!=null&&n.push(``,`exit ${uc(i)}`),cc(e,`cancelled`)===!0&&n.push(``,`cancelled`),cc(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
+ `)}]}}function Ks(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function qs(e,t){let n=Js(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=R(e,`type`),n=R(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=R(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=R(e,`name`)??`tool`,n=sc(e,`arguments`),r=R(e,`id`),i=t===`read`?Qs(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:ic(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=R(e,`data`),n=R(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return rc(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?Zs(e.text,t):e):rc(e):[n]}function Js(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return Xs(sc(e,`details`))}function Ys(e,t){if(e===`ask_user`)return Xs(sc(t,`superseded`))}function Xs(e){try{return{type:`askUserRecord`,outcome:xn(e)}}catch{return}}function Zs(e,t){let n=R(t,`toolCallId`),r=sc(t,`content`),i=sc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:R(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:cc(t,`isError`)===!0}}function Qs(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function $s(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&tc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function ec(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 tc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=nc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function nc(e){let t=sc(e,`preview`);if(!oc(t))return;let n=R(t,`diff`),r=R(t,`error`),i=lc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function rc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:ic(e)}]:[{type:`text`,text:uc(e)}]}function ic(e){if(!oc(e))return uc(e);let t=R(e,`command`);if(t!==void 0)return t;let n=R(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${ac(t)}`).join(` · `)}function ac(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?`object`:``}function oc(e){return typeof e==`object`&&!!e}function sc(e,t){return oc(e)?e[t]:void 0}function R(e,t){let n=sc(e,t);return typeof n==`string`?n:void 0}function cc(e,t){let n=sc(e,t);return typeof n==`boolean`?n:void 0}function lc(e,t){let n=sc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function uc(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var dc=`pi-web:prompt-draft:`;function fc(e){return`${dc}${e}`}function pc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function mc(e,t=pc()){try{return t?.getItem(fc(e))??``}catch{return``}}function hc(e,t,n=pc()){try{t?n?.setItem(fc(e),t):n?.removeItem(fc(e))}catch{}}function gc(e,t=pc()){try{t?.removeItem(fc(e))}catch{}}function _c(e,t,n=pc()){let r=mc(e,n);r!==``&&(hc(t,r,n),gc(e,n))}var vc=`pi-web:ask-draft:`;function yc(e,t){return`${vc}${e}:${t}`}function bc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function xc(e,t,n=bc()){try{let r=n?.getItem(yc(e,t));return r==null?{}:wc(r)}catch{return{}}}function Sc(e,t,n,r=bc()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(yc(e,t)):r?.setItem(yc(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function Cc(e,t,n=bc()){try{n?.removeItem(yc(e,t))}catch{}}function wc(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=Tc(r);t!==void 0&&(n[e]=t)}return n}function Tc(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={...e},n=t.values,r=t.otherText;if(!(!Array.isArray(n)||!n.every(e=>typeof e==`string`))&&!(r!==void 0&&typeof r!=`string`))return{values:[...n],...r===void 0?{}:{otherText:r}}}function Ec(e,t){return e.filter(e=>kc(e,t[e.id])!==void 0).length}function Dc(e,t){return e.filter(e=>kc(e,t[e.id])===void 0)}function Oc(e,t){let n=[];for(let r of e){let e=kc(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function kc(e,t){if(t===void 0)return;let n=new Set(e.options.map(e=>e.value)),r=[...new Set(t.values)].filter(e=>n.has(e)),i=Ac(t.otherText);if(e.multiple!==!0&&r.length+(i===void 0?0:1)>1){let t=r[0];return t===void 0?i===void 0?void 0:{id:e.id,values:[],otherText:i}:{id:e.id,values:[t]}}if(!(r.length===0&&i===void 0))return{id:e.id,values:r,...i===void 0?{}:{otherText:i}}}function Ac(e){if(e===void 0)return;let t=e.trim().slice(0,Ot);return t===``?void 0:t}function jc(e,t){return Ms(`bash`,`${t===!0?`excluded from context
5
5
 
6
6
  `:``}$ ${e}`)}function Mc(e,t){let n=e.at(-1),r=n?.parts.at(-1);if(n?.role!==`bash`||r?.type!==`text`)return[...e,Ms(`bash`,t)];let i=Pc(r.text)?``:`
7
7
 
@@ -13,10 +13,10 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
13
13
  `)>e.lastIndexOf(`$ `)}function Fc(e,t){if(t==null)return e;let n=js([t]);return n.length===0?e:[...e,...n]}function Ic(e,t){if(t.type===`message.append`)return cl(e,t.message);if(t.type===`assistant.delta`)return Ps(e,`assistant`,t.text);if(t.type===`assistant.thinking.delta`)return Fs(e,t.text);if(t.type===`tool.start`)return Hc(e,t);if(t.type===`tool.update`)return qc(e,t.toolCallId,e=>Uc(e,t));if(t.type===`tool.end`)return Wc(e,{toolCallId:t.toolCallId,toolName:t.toolName,text:t.text,isError:t.isError,content:t.content,details:t.details,presentation:Yc({role:`toolResult`,content:t.content})});if(t.type===`shell.start`)return[...e,jc(t.command,t.excludeFromContext)];if(t.type===`shell.chunk`)return Mc(e,t.chunk);if(t.type===`shell.end`)return Nc(e,t);if(t.type===`command.output`)return[...e,Ms(t.level===`error`?`system`:`tool`,t.message)];if(t.type===`session.error`)return[...e,Ms(`system`,t.message)];if(t.type===`message.end`)return t.message===void 0?void 0:Lc(e,t.message)}function Lc(e,t){let n=Xc(t);if(n!==void 0)return Wc(e,n);let r=Is(t);if(r.length===0)return;let i=r.map(e=>e.role===`assistant`?Bc(e):e).filter(e=>e.parts.length>0);return i.length===0?e:i.reduce((e,t)=>Rc(e,t),e)}function Rc(e,t){let n=Qc(e,t);if(n.length>0)return $c(e,n,t);let r=t.parts.find(e=>e.type===`askUserRecord`);if(r!==void 0)return zc(e,t,r);let i=e.at(-1);return i?.role===t.role&&(t.role===`assistant`||ol(i,t))?[...e.slice(0,-1),t]:[...e,t]}function zc(e,t,n){for(let r=e.length-1;r>=0;r--)if(Kc(e[r],n))return[...e.slice(0,r),t,...e.slice(r+1)];return[...e,t]}function Bc(e){return{...e,parts:e.parts.filter(e=>e.type!==`toolCall`)}}function Vc(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Hc(e,t){let n=t.toolName===`read`?Vc(hl(t.args,`path`)):void 0;if(n!==void 0)return ll(e,{role:`skill`,parts:[{type:`skillRead`,...n,...t.toolCallId===``?{}:{toolCallId:t.toolCallId}}]});let r={type:`toolExecution`,...t.toolCallId===``?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||ic(t.args),...t.args===void 0?{}:{args:t.args},status:`running`};return[...e,{role:`tool`,parts:[r]}]}function Uc(e,t){let n=nc(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},...n===void 0?{}:{preview:n}}}function Wc(e,t){let{toolCallId:n,toolName:r,text:i,isError:a,content:o,details:s,presentation:c}=t,l=qc(e,n,e=>{let t=nc(s)??e.preview;return{...e,status:a?`error`:`success`,resultText:i,...o===void 0?{}:{content:o},...s===void 0?{}:{details:s},...t===void 0?{}:{preview:t}}},e=>Jc(e,c)),u=l;if(l===e){let t=nc(s),l={type:`toolExecution`,...n===void 0||n===``?{}:{toolCallId:n},toolName:r,summary:ic(o),status:a?`error`:`success`,resultText:i,...o===void 0?{}:{content:o},...s===void 0?{}:{details:s},...t===void 0?{}:{preview:t}};u=[...e,Jc({role:`tool`,parts:[l]},c)]}return Gc(u,r,s,c.meta)}function Gc(e,t,n,r){let i=Ys(t,n);if(i===void 0)return e;for(let t=e.length-1;t>=0;t--){let n=e[t];if(Kc(n,i))return r===void 0||n===void 0?e:[...e.slice(0,t),{...n,meta:r},...e.slice(t+1)]}return[...e,{role:`tool`,parts:[i],...r===void 0?{}:{meta:r}}]}function Kc(e,t){return e?.parts.some(e=>e.type===`askUserRecord`&&e.outcome.askId===t.outcome.askId&&e.outcome.reason===t.outcome.reason)===!0}function qc(e,t,n,r=e=>e){if(t===void 0||t===``)return e;for(let i=e.length-1;i>=0;i--){let a=e[i];if(a===void 0)continue;let o=a.parts.findIndex(e=>e.type===`toolExecution`&&e.toolCallId===t);if(o<0)continue;let s=a.parts[o];if(s?.type!==`toolExecution`)continue;let c=r({...a,parts:[...a.parts.slice(0,o),n(s),...a.parts.slice(o+1)]});return[...e.slice(0,i),c,...e.slice(i+1)]}return e}function Jc(e,t){let n={...e,parts:[...e.parts.filter(e=>e.type!==`image`),...t.images]};return t.meta===void 0?n:{...n,meta:t.meta}}function Yc(e){let t=Is(e),n=t.flatMap(e=>e.parts.filter(e=>e.type===`image`)),r=t.find(e=>e.meta!==void 0)?.meta;return{images:n,...r===void 0?{}:{meta:r}}}function Xc(e){if(hl(e,`role`)!==`toolResult`)return;let t=hl(e,`toolCallId`),n=ml(e,`content`);return{...t===void 0?{}:{toolCallId:t},toolName:hl(e,`toolName`)??`tool`,text:Zc(n),isError:gl(e,`isError`)===!0,content:n,details:ml(e,`details`),presentation:Yc(e)}}function Zc(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(Zc).filter(e=>e!==``).join(`
14
14
  `);if(typeof e==`object`&&e){let t=hl(e,`text`)??hl(e,`content`)??hl(e,`output`);if(t!==void 0)return t}return``}function Qc(e,t){let n=nl(t);if(n.length===0)return[];let r=[],i=n.length,a=fl(e)+1;for(let t=e.length-1;t>=a;t--){let a=nl(e[t]);if(a.length===0)continue;let o=i-a.length;if(!(o<0)&&rl(a,n.slice(o,i))&&(r.unshift(t),i=o,i===0))return r}return[]}function $c(e,t,n){let r=el(e,t,n),i=r[0];if(i===void 0)return e;let a=new Set(r),o=[];for(let t=0;t<e.length;t++){t===i&&o.push(n);let r=e[t];r!==void 0&&!a.has(t)&&o.push(r)}return o}function el(e,t,n){let r=t[0];if(n.role!==`assistant`||r===void 0)return t;let i=r-1;return tl(e[i])?[i,...t]:t}function tl(e){return e?.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`text`||e.type===`thinking`)}function nl(e){return e===void 0?[]:e.parts.filter(e=>e.type===`skillRead`)}function rl(e,t){return e.length===t.length&&e.every((e,n)=>il(e,t[n]))}function il(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:al(e.path)===al(t.path)||e.name===t.name}function al(e){return e.replace(/\\/g,`/`)}function ol(e,t){return sl(e)===sl(t)}function sl(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
15
15
 
16
- `)}function cl(e,t){let n=Is(t);return n.length===0?e:[...e,...n]}function ll(e,t){let n=e.at(-1);return ul(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function ul(e,t){let n=nl(t);if(t.role!==`skill`||n.length===0)return!1;let r=fl(e)+1;return n.every(t=>dl(e,t,r))}function dl(e,t,n){for(let r=e.length-1;r>=n;r--)if(nl(e[r]).some(e=>il(e,t)))return!0;return!1}function fl(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function pl(e){return typeof e==`object`&&!!e}function ml(e,t){return pl(e)?e[t]:void 0}function hl(e,t){let n=ml(e,t);return typeof n==`string`?n:void 0}function gl(e,t){let n=ml(e,t);return typeof n==`boolean`?n:void 0}var _l=`pi-web:chat-history:v2:`,vl=1800*1e3;function yl(e){try{let t=sessionStorage.getItem(El(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!Dl(n))return;if(Date.now()-n.savedAt>vl){sessionStorage.removeItem(El(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function bl(e,t){try{sessionStorage.setItem(El(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function xl(e){try{sessionStorage.removeItem(El(e))}catch{}}function Sl(e,t){if(e===void 0||!Ol(e))return t;if(!Ol(t))return e;if(Cl(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return Tl(i,n,e),Tl(i,n,t),wl(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function Cl(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function wl(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Tl(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function El(e){return`${_l}${e}`}function Dl(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&Ol({messages:t,start:n,total:r})}function Ol(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(kl)}function kl(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var Al={read:yl,write:bl,remove:xl},jl=class{constructor(e=Al){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return Ml(this.rawHistoryPage(e))}mergeHistory(e,t){let n=Sl(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.cache.write(e,n),Ml(n)}applyLiveEvent(e,t){return Ic(e,t)}seedStreamingPartial(e,t){return Fc(e,t)}discard(e){this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function Ml(e){let t=e?.start??0;return{messages:js(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Nl(e,t=e.length){let n=e.slice(0,t),r=Fl(n,t);if(r!==void 0)return r;let i=Il(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
17
- `))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`}}function Pl(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function Fl(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function Il(e,t){let n=e.lastIndexOf(`
18
- `)+1,r=e.slice(n),i=Ll(r,`@ `),a=Ll(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function Ll(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Rl(e[n-1]))return n;return-1}function Rl(e){return e===` `||e===` `}function zl(e){let t=e.trimStart();return t.startsWith(`!@`)?{kind:`file`}:t.startsWith(`!`)?{kind:`shell`,excludeFromContext:t.startsWith(`!!`)}:Hl(e).startsWith(`/`)?{kind:`command`}:Nl(e)?.kind===`file`?{kind:`file`}:{kind:`normal`}}function Bl(e){return zl(e).kind===`shell`}function Vl(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Hl(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
19
- `))+1;return e.slice(t)}var Ul=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),eu(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Ka(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Gl(await $l(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Wl=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),eu(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Ja(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=Kl(await $l(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Gl(e){let t=Ql(e);return t===`notifications.inbox`?Xl(()=>Jn(e)):t===`ask.opened`?Zl(()=>gn(e)):t===`ask.closed`?Zl(()=>_n(e)):t===`dialog.opened`?Zl(()=>An(e)):t===`dialog.closed`?Zl(()=>jn(e)):ql(e)?e:void 0}function Kl(e){if(Ql(e)===`sessions.unread`)return Zl(()=>Ln(e));if(Ql(e)===`session.startup`)return Zl(()=>Rn(e));if(Jl(e)||Yl(e))return e}function ql(e){return[`message.append`,`assistant.delta`,`assistant.thinking.delta`,`tool.start`,`tool.update`,`tool.end`,`shell.start`,`shell.chunk`,`shell.end`,`agent.start`,`agent.end`,`message.end`,`status.update`,`activity.update`,`command.output`,`session.error`,`session.name`,`session.created`,`pi.event`].includes(Ql(e))}function Jl(e){let t=Ql(e);return t===`status.update`||t===`activity.update`||t===`session.name`||t===`session.created`}function Yl(e){let t=Ql(e);return t===`terminal.created`||t===`terminal.exited`||t===`terminal.closed`||t===`workspace.activity`}function Xl(e){return Zl(e)}function Zl(e){try{return e()}catch{return}}function Ql(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function $l(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 eu(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 tu(e){return e?.ok===!0&&T(e,w.sessionsPersistedState)}function nu(e){return{authoritative:tu(e)}}function ru(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||xs(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function iu(e,t,n){return e!==void 0&&e.archived!==!0&&ru(e,t,n)===`persisted`}function au(e,t,n){return e!==void 0&&e.archived!==!0&&ru(e,t,n)===`transient`}function ou(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var su=class{constructor(e,t,n=ou()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of lu(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function cu(e){return typeof e==`string`&&e!==``?e:void 0}function lu(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!uu(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function uu(e){return!du(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function du(e){return typeof e==`object`&&!!e}var fu=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},pu=`pi-web:session-selection:v1`,mu=class{constructor(e=ou()){this.sessionIdsByCwd=new su(pu,cu,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function hu(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return _u(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function gu(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function _u(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function vu(e,t,n){return yu(e,[t],n)}function yu(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function bu(e,t,n){return xu(e,t,[n])}function xu(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}function Su(e){return e.replace(/[/\\]+$/u,``)}function Cu(e,t){return Su(e)===Su(t)}var wu=100,Tu=4,Eu=class{constructor(e,t,n,r=new fu,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new To,this.socket=i.socket??new Ul,this.api=i.api??L,this.transcripts=i.transcripts??new jl,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();gu(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=R(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}preferredSession(e,t,n){return hu(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(Mu(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let r=R(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.selectedPendingAsk(this.getState().sessionStatuses[e.id],r),pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:wu},R(this.getState()));if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a=[];if(o=a,this.socket.connect(e,e=>a.push(e),()=>{this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh({session:e,machineId:r,selectionSeq:n}),!this.isCurrentRefreshTarget({session:e,machineId:r,selectionSeq:n}))return;this.refreshAvailableThinkingLevels();for(let e of a)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(xs(e)&&Xu(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{let n=await this.api.messages(t,{before:e.messagePageStart,limit:wu},R(this.getState()));if(this.getState().selectedSession?.id!==t.id)return;let r=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),n);this.setState(r)}catch(e){this.setState({error:String(e)})}finally{this.getState().selectedSession?.id===t.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,t,n,r=`inline`){let i=this.getState().selectedSession;if(!i||i.archived===!0)return;let a=e.trim(),o=n!==void 0&&n.length>0;if(Mu(i)){!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&Bl(e)?this.enqueuePendingSessionSend(i,{type:`shell`,text:e}):this.enqueuePendingSessionSend(i,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r});return}if(!o&&a.startsWith(`/`))return this.runCommand(e);if(!o&&Bl(e))return this.runShell(e);await this.deliverPromptToSession(i,e,t,n,r,R(this.getState()),{markSending:o})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:Ou(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(Mu(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,R(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(Mu(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,R(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`});return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=Pu(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Iu(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>Pl(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a)}else await this.api.prompt(e,t,n,a,r);return this.markCachedNewSessionPersisted(e),!0}catch(e){return this.setState({error:String(e)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Ou(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,R(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||Mu(r))throw Error(`The session tree navigator is no longer available`);let a=R(n),o=this.selectionSeq,s=wo(a,r.id),c;try{c=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}if(c.cancelled)return c;let l=c.editorText??``;if(hc(s,l),this.transcripts.discard(s),!this.isSelectedSessionIdentity(r.id,a))return c;this.clearPendingUpdates();let u;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){u={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return c;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:l})}catch(e){throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(e)}),e}if(u!==void 0)throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(u.error)}),u.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),c}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||Mu(t))return;let n=R(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(au(e,t,n)){await this.deleteCachedNewSession(e);return}if(iu(e,t,n))try{await this.api.archive(e,R(this.getState()));let t=this.getState(),n=vu(t.sessions,e.id,new Date().toISOString()),r=bu(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!iu(e,this.statusForSession(e),this.sessionPersistenceOptions())))try{let t=await this.api.archiveWithDescendants(e,R(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=yu(r.sessions,n,new Date().toISOString()),a=xu(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=zu(e).filter(e=>iu(e,this.statusForSession(e),t));if(n.length!==0)try{let e=R(this.getState()),{succeededIds:t,failures:r,generatedAt:i}=await this.archiveSessionBatch(n,e);if(t.length>0){let e=this.getState(),n=yu(e.sessions,t,i??new Date().toISOString()),r=xu(n,e.selectedSession?.id,t);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${Ku(e)}`})}}async deleteArchivedSessions(e){let t=zu(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=R(this.getState()),r=this.getState().machineRuntimes[n];if(r?.ok===!0&&!T(r,w.sessionsDeleteArchived)){this.setState({error:`Deleting archived sessions requires an updated Pi-Web runtime on this machine.`});return}try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${Ku(e)}`})}}async archiveSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&T(n,w.sessionsBulkMutations)){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:Vu(n.failures),generatedAt:n.generatedAt}}let r=await Uu(e,Tu,async e=>(await this.api.archive(e,t),e.id));return{succeededIds:Bu(r),failures:Hu(e,r)}}async deleteArchivedSessionBatch(e,t){let n=this.getState().machineRuntimes[t];if(n?.ok===!0&&T(n,w.sessionsBulkMutations)){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:Vu(n.failures)}}let r=await Uu(e,Tu,async e=>(await this.api.deleteArchived(e,t),e.id));return{succeededIds:Bu(r),failures:Hu(e,r)}}async applySessionCleanupResult(e,t=R(this.getState())){if(R(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=yu(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:ku(t.sessionStatuses,a),sessionActivities:ku(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=xu(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=R(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=bs(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(R(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){R(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!au(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=Mu(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,R(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),ys(e.id,R(this.getState())),gc(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:Ou(n.sessionStatuses,e.id),sessionActivities:Du(n.sessionActivities,e.id),sendingPrompts:Ou(n.sendingPrompts,e.id),clientQueuedSessionMessages:Ou(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,R(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!iu(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=R(this.getState()),n=this.getState().machineRuntimes[t];if(n?.ok!==!0||!T(n,w.sessionsReload)){this.setState({error:`Reloading sessions from disk requires an updated Pi-Web runtime on this machine.`});return}try{await this.api.reloadSession(e.id,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,R(this.getState()));let t={...e};delete t.parentSessionPath,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,R(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,R(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,R(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,R(this.getState())))}catch(e){this.setState({error:String(e)})}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||Mu(t))return;let n=R(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||Mu(n))return;let r=R(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(Mu(r)){await this.closePendingStartDialog(r,e,t);return}let i=R(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;let n=e.outcome;if(n!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===n.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:n.reason,...n.answer===void 0?{}:{answer:n.answer}})}this.applyStatus(e.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=t.outcome;if(o!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===o.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:o.reason,...o.answer===void 0?{}:{answer:o.answer}})}this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){a===this.selectionSeq&&this.getState().selectedSession?.id===e.id&&this.setState({error:String(t)})}}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||Mu(r))return;let i=R(n),a=this.selectionSeq;try{let n=await t(r,i);Cc(wo(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(e)try{await this.api.abort(e,R(this.getState()))}catch(e){this.setState({error:String(e)})}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.getState().selectedSession;if(e===void 0||t?.id!==e||t.archived===!0||Mu(t))return Promise.resolve();let n={session:t,machineId:R(this.getState()),selectionSeq:this.selectionSeq};return this.requestSelectedSessionRefresh(n).catch(e=>{this.isCurrentRefreshTarget(n)&&this.setState({error:String(e)})})}requestSelectedSessionRefresh(e){let t=wo(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:wu},e.machineId),this.api.status(e.session,e.machineId),this.api.streamSnapshot(e.session,e.machineId).catch(()=>({seq:0,partial:null})),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r)})}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return R(n)===t&&r?.id===e&&r.archived!==!0&&!Mu(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return wo(R(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return nu(e.machineRuntimes[R(e)])}workspaceSelectionKey(e){return`${R(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`New session`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:Pu(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:Pu(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){gc(wo(n.machineId,e)),this.setState({clientQueuedSessionMessages:Ou(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}_s(t,n.machineId),_c(wo(n.machineId,e),wo(n.machineId,t.id));let a=vs(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:Ou(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:ju(o.sessions,e,a),sessionActivities:Du(o.sessionActivities,e),sendingPrompts:Au(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:Au(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:this.selectedPendingAsk(o.sessionStatuses[a.id],n.machineId),pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r||!a){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=this.getState(),s=Ku(t),c=Fu(e,s,n.queuedSends.length),l=o.sessions.some(t=>t.id===e);this.setState({sessions:l?o.sessions:[n.session,...o.sessions],sessionActivities:{...o.sessionActivities,[e]:c},activity:o.selectedSession?.id===e?c:o.activity,...o.selectedSession?.id===e?{pendingDialogs:[]}:{},error:`Failed to start session: ${s}`}),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return R(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||R(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>Mu(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=R(this.getState()),r=await this.api.startSession(e.cwd,n);_s(r,n),_c(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),ys(e.id,n);let i=vs(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!xs(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Ss(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,Ms(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&hc(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd){let n=qu(t,e);n!==void 0&&this.setState(n);return}if(t.sessions.some(t=>t.id===e.id))return;let n=R(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!xo(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Ju(t,e.sessionId,e.messageCount),...r?{sessionActivities:Du(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingAsk:this.selectedPendingAsk(e,R(t))}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession!==void 0&&(t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]}))}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){let t=this.getState();t.selectedSession!==void 0&&this.setState({pendingAsk:this.selectedPendingAsk({pendingAsk:e},R(t))})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}selectedPendingAsk(e,t){if(e?.pendingAsk===void 0)return;let n=this.getState().machineRuntimes[t];if(!(n?.ok===!0&&!T(n,w.sessionsAskUser)))return e.pendingAsk}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(R(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(R(this.getState()),e.notificationId)===!0||this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(Yu(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?Pu(t.tempId,t.queuedSends.length):Nu(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function Du(e,t){return Ou(e,t)}function Ou(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ku(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function Au(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...Ou(e,t),[n]:r}}function ju(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function Mu(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function Nu(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function Pu(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function Fu(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function Iu(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Lu(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function Lu(e,t){let n=Ru(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Ru(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function zu(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Bu(e){return e.filter(Wu).map(e=>e.value)}function Vu(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Hu(e,t){return t.flatMap((t,n)=>Gu(t)?[`${e[n]?.id??`unknown`}: ${Ku(t.reason)}`]:[])}async function Uu(e,t,n){let r=e.map((e,t)=>({item:e,index:t})),i=[],a=0;async function o(){for(;a<r.length;){let e=r[a];if(e===void 0)return;a+=1;try{i[e.index]={status:`fulfilled`,value:await n(e.item)}}catch(t){i[e.index]={status:`rejected`,reason:t}}}}let s=Math.min(Math.max(1,t),r.length);return await Promise.all(Array.from({length:s},()=>o())),i}function Wu(e){return e.status===`fulfilled`}function Gu(e){return e.status===`rejected`}function Ku(e){return e instanceof Error?e.message:String(e)}function qu(e,t){let n=t.parentSessionPath;if(n===void 0||n===``)return;let r=e=>Cu(e.path,n);if(e.sessions.some(r))return{sessions:e.sessions.map(e=>r(e)?{...e,childSessionsElsewhere:(e.childSessionsElsewhere??0)+1}:e)}}function Ju(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function Yu(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Xu(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var Zu={order:0,overflowWatermark:0};function Qu(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Zu,optimisticDismissedIds:[],announcements:[]}}function $u(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&pd(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function ed(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Qu(t),needsRefresh:!1,changed:!1};if(e===void 0||!pd(e,t))return{value:hd(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:hd(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!gd(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function td(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=vd(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...yd(_d(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function nd(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function rd(e){return`${nd(e.severity)} notification received.`}function id(e){return e.retainedCount+e.discardedCount}function ad(e){return`Notifications (${String(id(e))})`}function od(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${nd(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function sd(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function cd(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function ld(e,t){return e.has(cd(t))}function ud(e,t,n){let r=new Set(e),i=cd(t);return n?r.add(i):r.delete(i),r}function dd(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function fd(e){if(!e.truncated)return;let t=Tt/1024;return`Message truncated at ${String(t)} KiB.`}function pd(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function md(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function hd(e){return{...Qu(e),status:`stale`}}function gd(e,t){return e.length===t.retainedCount&&_d(e)===t.highestSeverity}function _d(e){let t;for(let n of e)t=md(t,n.severity);return t}function vd(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function yd(e){return e===void 0?{}:{highestSeverity:e}}var bd=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??L,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:Qu(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=ed(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);if(!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=td(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=xd(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${Cd(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=td(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=xd(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${Cd(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||Sd(i,t,r)?$u(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=ed(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&pd(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!pd(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=Sd(r,e,t)?$u(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!pd(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!pd(t,e))&&this.setState({selectedNotificationInbox:Qu(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&pd(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!pd(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&pd(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0&&T(e.machineRuntimes[t],w.sessionsNotifications)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function xd(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function Sd(e,t,n){return!pd(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function Cd(e){return e instanceof Error?e.message:String(e)}var wd=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},Td=`pi-web:workspace-selection:v1`,Ed=class{constructor(e=ou()){this.workspaceIdsByProject=new su(Td,cu,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function Dd(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var Od=class{constructor(e,t,n,r,i=new wd,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.topologyRefreshes=new To,this.api=a.api??L,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)})}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...yo()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Co(R(this.getState()),e));let t=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:t})}async selectProject(e,t){let n=R(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...yo()});try{let r=await this.api.workspaces(e.id,n);if(R(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=Dd(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Co(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){R(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({error:String(t),isLoadingWorkspaces:!1})}}async selectWorkspace(e,t){let n=R(this.getState());this.workspaceSelection.rememberWorkspace({...e,projectId:Co(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...yo()});try{let r=bs(e.path,await this.api.sessions(e.path,n),n);if(R(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){R(this.getState())===n&&this.getState().selectedWorkspace?.id===e.id&&this.setState({error:String(t)})}}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`Project not found`);let n=await this.api.workspaces(t.id,R(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=R(e);await this.topologyRefreshes.request(Co(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(R(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=Ad(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||jd(e,n)))return{selectedWorkspace:n}}};function kd(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Ad(e){return e.find(e=>e.isMain)??e[0]}function jd(e,t){return e.path===t.path&&e.label===t.label&&e.branch===t.branch&&e.isMain===t.isMain&&e.isGitRepo===t.isGitRepo&&e.isGitWorktree===t.isGitWorktree}var Md=`pi-web:machine-navigation:v1`,Nd=class{constructor(e=ou()){this.snapshotsByMachine=new su(Md,Rd,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Ld(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Ld(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Pd(e){return{machineId:e,surface:{}}}function Fd(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,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 Id(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 Ld(e){return{...e,surface:{...e.surface}}}function Rd(e){if(!Wd(e))return;let t=Ud(e,`machineId`);if(t===void 0)return;let n=Vd(Ud(e,`tool`)),r=Bd(Ud(e,`view`));return{machineId:t,projectId:Ud(e,`projectId`),workspaceId:Ud(e,`workspaceId`),sessionId:Ud(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:zd(e.surface)}}function zd(e){return Wd(e)?{selectedFilePath:Ud(e,`selectedFilePath`),selectedDiffPath:Ud(e,`selectedDiffPath`),selectedTerminalId:Ud(e,`selectedTerminalId`)}:{}}function Bd(e){return e===`navigation`||e===`chat`?e:Vd(e)}function Vd(e){return Hd(e)?e:void 0}function Hd(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ud(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Wd(e){return typeof e==`object`&&!!e}var Gd=`pi-web:terminal-selection:v1`,Kd=class{constructor(e=ou()){this.terminalIdsByCwd=new su(Gd,cu,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function qd(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function Jd(e){return e.find(e=>!e.exited)??e[0]}var Yd=1200,Xd=[`mod`,`alt`,`shift`],Zd=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=nf(e);if(r===void 0)return!1;let i=Qd(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!rf(r))return!1}else if(!rf(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>xf(t.tokens,e));return n===void 0?t.some(t=>Sf(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Yd)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function Qd(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=af(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(lf)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(uf),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=df(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:cf(t),i=n?[...s.get(e)??[]].sort(lf).map(cf):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function $d(e){return mf(e,{requireFirstChordActivator:!0})}function ef(e){let t=mf(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function tf(e){return ef(e).map(e=>e.split(`+`).map(bf).join(`+`)).join(` `)}function nf(e){if(e.isComposing)return;let t=vf(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function rf(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function af(e,t,n){let r=of(e.id,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=ef(i),o=a[0];if(!(o===void 0||!rf(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:sf(a),order:n}}function of(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function sf(e){return e.join(`\0`)}function cf(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function lf(e,t){return ff(e.source)-ff(t.source)||pf(e.action.id,t.action.id)||pf(e.action.title,t.action.title)||e.order-t.order}function uf(e,t){return e.tokens.length-t.tokens.length||lf(e,t)}function df(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&Sf(e.tokens,t.tokens))}function ff(e){switch(e){case`custom`:return 0;case`default`:return 1}}function pf(e,t){return e<t?-1:+(e>t)}function mf(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`Enter a shortcut, choose None, or reset to the default.`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=hf(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!rf(i.token))return{ok:!1,message:`Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured.`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function hf(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`Shortcut chords must include a key.`};let n=new Set,r;for(let e of t){let t=gf(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${bf(t)} modifiers.`};n.add(t);continue}let i=_f(e);if(i===void 0)return{ok:!1,message:`Unsupported shortcut key: ${e}`};if(r!==void 0)return{ok:!1,message:`Each shortcut chord can include only one non-modifier key.`};r=i}return r===void 0?{ok:!1,message:`Shortcut chords must include a key.`}:{ok:!0,token:[...Xd.filter(e=>n.has(e)),r].join(`+`)}}function gf(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function _f(e){let t=yf(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function vf(e){return e===` `?`space`:_f(e.toLowerCase())}function yf(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function bf(e){return e===`mod`?Cf()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?Cf()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function xf(e,t){return e.length===t.length&&Sf(e,t)}function Sf(e,t){return t.every((t,n)=>e[n]===t)}function Cf(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function wf(e,t){let n=e.parentSessionCwd;if(n===void 0||n===``)return{kind:`unknown`};let r=Of(t.workspaces,n);if(r!==void 0)return Df(r,e.parentSessionId,void 0);for(let[r,i]of Object.entries(t.workspacesByProjectId)){let a=Of(i,n);if(a===void 0)continue;let o=t.projects.find(e=>e.id===r)?.name;return Df(a,e.parentSessionId,o)}return{kind:`path`,label:kf(n),cwd:n}}function Tf(e){return e.kind===`unknown`?`parent unavailable`:`parent in ${e.label}`}function Ef(e){switch(e.kind){case`workspace`:return`Parent session is in ${e.label} (${e.cwd})`;case`path`:return`Parent session is in ${e.cwd}`;case`unknown`:return`Parent session is not available in this workspace`}}function Df(e,t,n){let r=e.branch??e.label;return{kind:`workspace`,label:n===void 0?r:`${n} · ${r}`,projectId:e.projectId,workspaceId:e.id,sessionId:t,cwd:e.path}}function Of(e,t){let n=Su(t);return e.find(e=>Su(e.path)===n)}function kf(e){let t=Su(e).split(/[/\\]/u).filter(e=>e!==``),n=t.slice(-2);return n.length===0?e:t.length>n.length?`…/${n.join(`/`)}`:n.join(`/`)}var Af={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function jf(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`Enable at least one cleanup action.`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=Bf(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=Bf(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Mf(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Nf(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=jf(e.draft);return!t.ok||Mf(t.request)!==Mf(e.previewRequest)?!1:Pf(e.preview)}function Pf(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Ff(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function If(e,t){let n=new Set(Ff(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function Lf(e,t){return t(Rf(e))}function Rf(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`archive ${String(t)} idle ${t===1?`session`:`sessions`}`),n>0&&r.push(`permanently delete ${String(n)} archived ${n===1?`session`:`sessions`}`),`Run cleanup and ${r.length===0?`run cleanup`:r.join(` and `)}?\n\nPermanent deletion only applies to archived sessions and cannot be undone.`}function zf(e){return`Update and restart Pi-Web on ${e??`this machine`} to clean up sessions.`}function Bf(e,t){let n=e.trim();if(n===``)return`${t} must be set.`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t} must be a non-negative whole number of days.`:r}var Vf=new Set,Hf=Ct+1,Uf={unreadCatalog:e=>Ra.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Ra.acknowledgeUnread(e,t,n,r)},Wf=class{constructor(e={}){this.machines=new Map,this.api=e.api??Uf,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}setCapability(e,t){let n=this.machine(e),r=n.capability;if(r===t)return!1;if(n.capability=t,t===`unsupported`){let t=n.projection!==void 0;return n.generation+=1,n.projection=void 0,t&&(n.projectionVersion+=1),n.status=`stale`,n.refreshPromise=void 0,n.refreshQueued=!1,n.observers.clear(),n.acknowledgements.clear(),t&&this.onChange(e),!1}return t===`unknown`?(n.projection!==void 0&&n.status!==`stale`&&(n.status=`stale`,this.onChange(e)),!1):r!==`supported`}capability(e){return this.machines.get(e)?.capability??`unknown`}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return Vf;let r=new Set;for(let e of t)n.summariesByIdentity.has(Xf(e))&&r.add(e.id);return r.size===0?Vf:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(Xf(t))===!0}applyEvent(e,t){let n=this.machine(e);if(n.capability!==`supported`)return;this.recordObservedEvent(n,t);let r=Gf(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.capability!==`supported`)return Promise.resolve();if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued&&t.capability===`supported`;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].filter(e=>e.capability===`supported`).map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n?.capability!==`supported`||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(Xf(t));if(i===void 0)return Promise.resolve();let a=Zf(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrentSupported(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrentSupported(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=qf(t),a=`fresh`,o=!1;for(let e of n.events){let t=Gf(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=Hf?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!Yf(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,capability:`unknown`,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}isCurrentSupported(e,t){return this.isCurrent(e,t)&&e.capability===`supported`}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function Gf(e,t,n){if(e===void 0){let e=Jf(n.catalogId);return n.catalogRevision===1?Kf(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=Jf(n.catalogId);return n.catalogRevision===1?Kf(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?Kf(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function Kf(e,t,n){let r=new Map(e.summariesByIdentity),i=Xf(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function qf(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[Xf(e),{...e}]))}}function Jf(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function Yf(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function Xf(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function Zf(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var Qf={machines:new Set,projects:new Set,workspaces:new Set};function $f(e){let t=tp(e.projectionFor(e.selectedMachineId));return{machines:np(e.machineIds,e.projectionFor),projects:ip(e.projects,e.workspacesByProjectId,t),workspaces:rp(e.workspaces,t)}}function ep(e){return e!==void 0&&e.sessions.length>0}function tp(e){return e===void 0||e.sessions.length===0?op:new Set(e.sessions.map(e=>e.cwd))}function np(e,t){let n=new Set;for(let r of e)ep(t(r))&&n.add(r);return n}function rp(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function ip(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function ap(e,t){return sp(e.machines,t.machines)&&sp(e.projects,t.projects)&&sp(e.workspaces,t.workspaces)}var op=new Set;function sp(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function cp(){return{selectedSessionKey:void 0,warningSetSignature:lp(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function lp(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function up(e,t,n){let r=lp(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function dp(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function fp(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function pp(e){return e.collapsed?fp(e):dp(e)}var mp=`themes:classic`,hp={themeId:`themes:pi-web-dark`,auto:!0},gp=`pi-web-app-theme`,_p=`--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`.split(`.`),vp=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function yp(){try{let e=window.localStorage.getItem(gp);return e===null?void 0:Tp(e)}catch{return}}function bp(e){try{window.localStorage.setItem(gp,JSON.stringify(e))}catch{}}function xp(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of _p){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function Sp(e){let t=Cp(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=wp(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function Cp(e,t=mp){return e.find(e=>e.id===t)??e[0]}function wp(e,t){return e.find(e=>e.light===t||e.dark===t)}function Tp(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return Ep(e)?e:void 0}catch{return}}function Ep(e){if(!Dp(e))return!1;let t=e.themeId,n=e.auto;return Op(t)&&typeof n==`boolean`}function Dp(e){return typeof e==`object`&&!!e}function Op(e){return typeof e==`string`&&vp.test(e)}var kp=`workspace.delete`,Ap=`pi.operation`,jp=`target.workspaceId`;function Mp(e){return{...e===void 0?{}:{projectId:e},metadata:{[Ap]:kp}}}function Np(e){let t={};for(let n of e){let e=Ip(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Pp(e){return Object.entries(e).filter(([,e])=>Lp(e)).map(([e])=>e)}function Fp(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Lp(n)}function Ip(e){return e.metadata[jp]}function Lp(e){return e.status===`queued`||e.status===`running`}function Rp(){return[{id:`actions.show`,title:`Show Actions`,description:`Open the command palette`,shortcut:`mod+k`,group:`General`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`Focus Prompt`,description:`Move keyboard focus to the message composer`,shortcut:`mod+g c`,group:`General`,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`Add Machine`,description:`Register another PI WEB runtime reachable from this gateway`,group:`Machine`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`Refresh Selected Machine`,description:`Check whether the selected PI WEB runtime is online`,group:`Machine`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`Open Selected Machine PI WEB`,description:`Open the selected remote PI WEB directly in a new tab`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`Remove Selected Machine`,description:`Remove the selected remote machine from this gateway`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`Add Project`,group:`Project`,run:e=>e.addProject()},{id:`auth.login`,title:`Configure Provider Authentication`,description:`Run /login without tying authentication to a session`,group:`General`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`Remove Provider Authentication`,description:`Run /logout for stored pi credentials`,group:`General`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`Select Theme`,description:`Choose the PI WEB color theme`,group:`Preferences`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`Open Settings`,description:`Manage PI WEB configuration and keyboard shortcuts`,shortcut:`mod+,`,group:`Preferences`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`Full Page Reload`,description:`Reload the PI WEB browser page`,group:`General`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`Go to Chat`,shortcut:`mod+1`,group:`Navigation`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`Go to Files`,shortcut:`mod+2`,group:`Navigation`,enabled:zp,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.git`,title:`Go to Git`,shortcut:`mod+3`,group:`Navigation`,enabled:Bp,run:e=>{e.selectMainView(`core:workspace.git`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+4`,group:`Navigation`,enabled:zp,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:zp,run:e=>e.refreshFiles()},{id:`workspace.refresh-git`,title:`Refresh Git`,shortcut:`mod+shift+g`,group:`Workspace`,enabled:Bp,run:e=>e.refreshGit()},{id:`workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:zp,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:Vp,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:zp,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:Hp,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:Hp,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:Up,run:e=>e.archiveSession()},{id:`session.reload`,title:`Reload Session from Disk`,description:`Close and re-open the selected session from its session file. Use /reload in the prompt for Pi runtime resources.`,group:`Session`,enabled:Gp,disabledReason:Kp,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:Wp,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&xo(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function zp(e){return e.state.selectedWorkspace!==void 0}function Bp(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Vp(e){let t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Fp(e.state,t)}function Hp(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Up(e){return iu(e.state.selectedSession,e.state.status,qp(e.state))}function Wp(e){return au(e.state.selectedSession,e.state.status,qp(e.state))}function Gp(e){return!iu(e.state.selectedSession,e.state.status,qp(e.state))||Kp(e)!==void 0?!1:!xo(e.state.status,e.state.activity)}function Kp(e){if(iu(e.state.selectedSession,e.state.status,qp(e.state))&&!xo(e.state.status,e.state.activity))return Jp(e.state,w.sessionsReload,`reload sessions from disk`)}function qp(e){return nu(e.machineRuntimes[R(e)])}function Jp(e,t,n){let r=e.machineRuntimes[R(e)];if(!(r?.ok===!0&&T(r,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??`this machine`} to ${n}.`}function Yp(e){return typeof e==`string`?Xp(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function Xp(e){switch(e){case`navigation`:return Je`
16
+ `)}function cl(e,t){let n=Is(t);return n.length===0?e:[...e,...n]}function ll(e,t){let n=e.at(-1);return ul(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function ul(e,t){let n=nl(t);if(t.role!==`skill`||n.length===0)return!1;let r=fl(e)+1;return n.every(t=>dl(e,t,r))}function dl(e,t,n){for(let r=e.length-1;r>=n;r--)if(nl(e[r]).some(e=>il(e,t)))return!0;return!1}function fl(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function pl(e){return typeof e==`object`&&!!e}function ml(e,t){return pl(e)?e[t]:void 0}function hl(e,t){let n=ml(e,t);return typeof n==`string`?n:void 0}function gl(e,t){let n=ml(e,t);return typeof n==`boolean`?n:void 0}var _l=`pi-web:chat-history:v2:`,vl=1800*1e3;function yl(e){try{let t=sessionStorage.getItem(El(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!Dl(n))return;if(Date.now()-n.savedAt>vl){sessionStorage.removeItem(El(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function bl(e,t){try{sessionStorage.setItem(El(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function xl(e){try{sessionStorage.removeItem(El(e))}catch{}}function Sl(e,t){if(e===void 0||!Ol(e))return t;if(!Ol(t))return e;if(Cl(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return Tl(i,n,e),Tl(i,n,t),wl(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function Cl(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function wl(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Tl(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function El(e){return`${_l}${e}`}function Dl(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&Ol({messages:t,start:n,total:r})}function Ol(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(kl)}function kl(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var Al={read:yl,write:bl,remove:xl},jl=class{constructor(e=Al){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return Ml(this.rawHistoryPage(e))}mergeHistory(e,t){let n=Sl(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.cache.write(e,n),Ml(n)}applyLiveEvent(e,t){return Ic(e,t)}seedStreamingPartial(e,t){return Fc(e,t)}discard(e){this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function Ml(e){let t=e?.start??0;return{messages:js(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Nl(e,t=e.length){let n=e.slice(0,t),r=zl(n,t);if(r!==void 0)return r;let i=Bl(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
17
+ `))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`};if(o.startsWith(`#`))return{kind:`model`,query:o.slice(1),from:a,to:t}}var Pl=12;function Fl(e,t){let n=t.toLowerCase(),r=[];for(let t of e)if(Il(t)&&Ll(t,n)&&(r.push({insertText:`#${t.provider}/${t.id}`,detail:t.provider,...t.name!==void 0&&t.name!==``&&t.name!==t.id?{description:t.name}:{}}),r.length>=Pl))break;return r}function Il(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function Ll(e,t){return`${e.provider}/${e.id}`.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||(e.name?.toLowerCase().includes(t)??!1)}function Rl(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function zl(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function Bl(e,t){let n=e.lastIndexOf(`
18
+ `)+1,r=e.slice(n),i=Vl(r,`@ `),a=Vl(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function Vl(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Hl(e[n-1]))return n;return-1}function Hl(e){return e===` `||e===` `}function Ul(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(Kl(e).startsWith(`/`))return{kind:`command`};let n=Nl(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function Wl(e){return Ul(e).kind===`shell`}function Gl(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Kl(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
19
+ `))+1;return e.slice(t)}var ql=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),tu(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Ka(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Yl(await eu(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Jl=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),tu(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Ja(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=Xl(await eu(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Yl(e){let t=$l(e);if(t===`notifications.inbox`)return Ql(()=>tr(e));if(t===`ask.opened`)return Ql(()=>_n(e));if(t===`ask.closed`)return Ql(()=>vn(e));if(t===`dialog.opened`)return Ql(()=>jn(e));if(t===`dialog.closed`)return Ql(()=>Mn(e));let n=Ql(()=>Un(e));return n===void 0?void 0:Zl(n,e)}function Xl(e){let t=$l(e);return Ql(t===`sessions.unread`?()=>Rn(e):t===`session.startup`?()=>zn(e):()=>Wn(e))}function Zl(e,t){if(typeof t!=`object`||!t||!(`seq`in t))return e;let n=t.seq;return typeof n==`number`?{...e,seq:n}:e}function Ql(e){try{return e()}catch{return}}function $l(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function eu(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 tu(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 nu(e,t){if(e===void 0)return`unknown`;let n=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return n===!0?`persisted`:n===!1||xs(e)?`transient`:`unknown`}function ru(e,t){return e!==void 0&&e.archived!==!0&&nu(e,t)===`persisted`}function iu(e,t){return e!==void 0&&e.archived!==!0&&nu(e,t)===`transient`}function au(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var ou=class{constructor(e,t,n=au()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of cu(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function su(e){return typeof e==`string`&&e!==``?e:void 0}function cu(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!lu(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function lu(e){return!uu(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function uu(e){return typeof e==`object`&&!!e}var du=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},fu=`pi-web:session-selection:v1`,pu=class{constructor(e=au()){this.sessionIdsByCwd=new ou(fu,su,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function mu(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return gu(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function hu(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function gu(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function _u(e,t,n){return vu(e,[t],n)}function vu(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function yu(e,t,n){return bu(e,t,[n])}function bu(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}function z(e){return e.replace(/[/\\]+$/u,``)}function xu(e,t){return z(e)===z(t)}var Su=100,Cu=class{constructor(e,t,n,r=new du,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new To,this.socket=i.socket??new ql,this.api=i.api??I,this.transcripts=i.transcripts??new jl,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();hu(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=L(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}preferredSession(e,t,n){return mu(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(ku(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let r=L(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.getState().sessionStatuses[e.id]?.pendingAsk,pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:Su},L(this.getState()));if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a=[];if(o=a,this.socket.connect(e,e=>a.push(e),()=>{this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh({session:e,machineId:r,selectionSeq:n}),!this.isCurrentRefreshTarget({session:e,machineId:r,selectionSeq:n}))return;this.refreshAvailableThinkingLevels();for(let e of a)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(xs(e)&&Hu(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{let n=await this.api.messages(t,{before:e.messagePageStart,limit:Su},L(this.getState()));if(this.getState().selectedSession?.id!==t.id)return;let r=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),n);this.setState(r)}catch(e){this.setState({error:String(e)})}finally{this.getState().selectedSession?.id===t.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,t,n,r=`inline`){let i=this.getState().selectedSession;if(!i||i.archived===!0)return;let a=e.trim(),o=n!==void 0&&n.length>0;if(ku(i)){!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&Wl(e)?this.enqueuePendingSessionSend(i,{type:`shell`,text:e}):this.enqueuePendingSessionSend(i,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r});return}if(!o&&a.startsWith(`/`))return this.runCommand(e);if(!o&&Wl(e))return this.runShell(e);await this.deliverPromptToSession(i,e,t,n,r,L(this.getState()),{markSending:o})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:Tu(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(ku(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,L(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(ku(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,L(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`});return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=ju(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Nu(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>Rl(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a)}else await this.api.prompt(e,t,n,a,r);return this.markCachedNewSessionPersisted(e),!0}catch(e){return this.setState({error:String(e)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Ms(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Tu(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,L(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||ku(r))throw Error(`The session tree navigator is no longer available`);let a=L(n),o=this.selectionSeq,s=wo(a,r.id),c;try{c=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}if(c.cancelled)return c;let l=c.editorText??``;if(hc(s,l),this.transcripts.discard(s),!this.isSelectedSessionIdentity(r.id,a))return c;this.clearPendingUpdates();let u;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){u={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return c;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:l})}catch(e){throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(e)}),e}if(u!==void 0)throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(u.error)}),u.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),c}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||ku(t))return;let n=L(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e);if(iu(e,t)){await this.deleteCachedNewSession(e);return}if(ru(e,t))try{await this.api.archive(e,L(this.getState()));let t=this.getState(),n=_u(t.sessions,e.id,new Date().toISOString()),r=yu(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!ru(e,this.statusForSession(e))))try{let t=await this.api.archiveWithDescendants(e,L(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=vu(r.sessions,n,new Date().toISOString()),a=bu(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=Iu(e).filter(e=>ru(e,this.statusForSession(e)));if(t.length!==0)try{let e=L(this.getState()),{succeededIds:n,failures:r,generatedAt:i}=await this.archiveSessionBatch(t,e);if(n.length>0){let e=this.getState(),t=vu(e.sessions,n,i??new Date().toISOString()),r=bu(t,e.selectedSession?.id,n);this.setState({sessions:t}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${Ru(e)}`})}}async deleteArchivedSessions(e){let t=Iu(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=L(this.getState());try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${Ru(e)}`})}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:Lu(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:Lu(n.failures)}}async applySessionCleanupResult(e,t=L(this.getState())){if(L(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=vu(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:Eu(t.sessionStatuses,a),sessionActivities:Eu(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=bu(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=L(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=bs(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(L(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){L(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!iu(e,this.statusForSession(e)))return;let t=ku(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,L(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),ys(e.id,L(this.getState())),gc(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:Tu(n.sessionStatuses,e.id),sessionActivities:wu(n.sessionActivities,e.id),sendingPrompts:Tu(n.sendingPrompts,e.id),clientQueuedSessionMessages:Tu(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,L(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!ru(e,this.statusForSession(e)))return;let t=L(this.getState());try{await this.api.reloadSession(e,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,L(this.getState()));let t={...e};delete t.parentSessionPath,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,L(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,L(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||ku(t))return;let n=L(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||ku(n))return;let r=L(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(ku(r)){await this.closePendingStartDialog(r,e,t);return}let i=L(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;let n=e.outcome;if(n!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===n.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:n.reason,...n.answer===void 0?{}:{answer:n.answer}})}this.applyStatus(e.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=t.outcome;if(o!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===o.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:o.reason,...o.answer===void 0?{}:{answer:o.answer}})}this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){a===this.selectionSeq&&this.getState().selectedSession?.id===e.id&&this.setState({error:String(t)})}}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||ku(r))return;let i=L(n),a=this.selectionSeq;try{let n=await t(r,i);Cc(wo(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(e)try{await this.api.abort(e,L(this.getState()))}catch(e){this.setState({error:String(e)})}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.getState().selectedSession;if(e===void 0||t?.id!==e||t.archived===!0||ku(t))return Promise.resolve();let n={session:t,machineId:L(this.getState()),selectionSeq:this.selectionSeq};return this.requestSelectedSessionRefresh(n).catch(e=>{this.isCurrentRefreshTarget(n)&&this.setState({error:String(e)})})}requestSelectedSessionRefresh(e){let t=wo(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:Su},e.machineId),this.api.status(e.session,e.machineId),this.api.streamSnapshot(e.session,e.machineId),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r)})}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return L(n)===t&&r?.id===e&&r.archived!==!0&&!ku(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return wo(L(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}workspaceSelectionKey(e){return`${L(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`New session`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:ju(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:ju(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){gc(wo(n.machineId,e)),this.setState({clientQueuedSessionMessages:Tu(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}_s(t,n.machineId),_c(wo(n.machineId,e),wo(n.machineId,t.id));let a=vs(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:Tu(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:Ou(o.sessions,e,a),sessionActivities:wu(o.sessionActivities,e),sendingPrompts:Du(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:Du(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:o.sessionStatuses[a.id]?.pendingAsk,pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r||!a){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=this.getState(),s=Ru(t),c=Mu(e,s,n.queuedSends.length),l=o.sessions.some(t=>t.id===e);this.setState({sessions:l?o.sessions:[n.session,...o.sessions],sessionActivities:{...o.sessionActivities,[e]:c},activity:o.selectedSession?.id===e?c:o.activity,...o.selectedSession?.id===e?{pendingDialogs:[]}:{},error:`Failed to start session: ${s}`}),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return L(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||L(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>ku(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=L(this.getState()),r=await this.api.startSession(e.cwd,n);_s(r,n),_c(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),ys(e.id,n);let i=vs(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!xs(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Ss(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,Ms(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&hc(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd){let n=zu(t,e);n!==void 0&&this.setState(n);return}if(t.sessions.some(t=>t.id===e.id))return;let n=L(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!xo(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Bu(t,e.sessionId,e.messageCount),...r?{sessionActivities:wu(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingAsk:e.pendingAsk}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession!==void 0&&(t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]}))}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){this.getState().selectedSession!==void 0&&this.setState({pendingAsk:e})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(L(this.getState()),e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(Vu(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?ju(t.tempId,t.queuedSends.length):Au(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function wu(e,t){return Tu(e,t)}function Tu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Eu(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function Du(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...Tu(e,t),[n]:r}}function Ou(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function ku(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function Au(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function ju(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function Mu(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function Nu(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Pu(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function Pu(e,t){let n=Fu(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Fu(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function Iu(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Lu(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Ru(e){return e instanceof Error?e.message:String(e)}function zu(e,t){let n=t.parentSessionPath;if(n===void 0||n===``)return;let r=e=>xu(e.path,n);if(e.sessions.some(r))return{sessions:e.sessions.map(e=>r(e)?{...e,childSessionsElsewhere:(e.childSessionsElsewhere??0)+1}:e)}}function Bu(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function Vu(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Hu(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var Uu={order:0,overflowWatermark:0};function Wu(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Uu,optimisticDismissedIds:[],announcements:[]}}function Gu(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&ad(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function Ku(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Wu(t),needsRefresh:!1,changed:!1};if(e===void 0||!ad(e,t))return{value:sd(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:sd(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!cd(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function qu(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=ud(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...dd(ld(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Ju(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function Yu(e){return`${Ju(e.severity)} notification received.`}function Xu(e){return e.retainedCount+e.discardedCount}function Zu(e){return`Notifications (${String(Xu(e))})`}function Qu(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${Ju(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function $u(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function ed(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function td(e,t){return e.has(ed(t))}function nd(e,t,n){let r=new Set(e),i=ed(t);return n?r.add(i):r.delete(i),r}function rd(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function id(e){if(!e.truncated)return;let t=Et/1024;return`Message truncated at ${String(t)} KiB.`}function ad(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function od(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function sd(e){return{...Wu(e),status:`stale`}}function cd(e,t){return e.length===t.retainedCount&&ld(e)===t.highestSeverity}function ld(e){let t;for(let n of e)t=od(t,n.severity);return t}function ud(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function dd(e){return e===void 0?{}:{highestSeverity:e}}var fd=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??I,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:Wu(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=Ku(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineIsReachableInState(e,r.machineId);if(!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=qu(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=pd(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${hd(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=qu(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=pd(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${hd(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}let i=this.getState().selectedNotificationInbox,a=i===void 0||md(i,t,r)?Gu(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Ku(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&ad(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!ad(r,e))return;if(!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=md(r,e,t)?Gu(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!ad(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!ad(t,e))&&this.setState({selectedNotificationInbox:Wu(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&ad(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!ad(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&ad(this.selectedTarget,e)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function pd(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function md(e,t,n){return!ad(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function hd(e){return e instanceof Error?e.message:String(e)}var gd=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},_d=`pi-web:workspace-selection:v1`,vd=class{constructor(e=au()){this.workspaceIdsByProject=new ou(_d,su,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function yd(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var bd=class{constructor(e,t,n,r,i=new gd,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.topologyRefreshes=new To,this.api=a.api??I,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)})}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...yo()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Co(L(this.getState()),e));let t=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:t})}async selectProject(e,t){let n=L(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...yo()});try{let r=await this.api.workspaces(e.id,n);if(L(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=yd(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Co(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({error:String(t),isLoadingWorkspaces:!1})}}async selectWorkspace(e,t){let n=L(this.getState());this.workspaceSelection.rememberWorkspace({...e,projectId:Co(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...yo()});try{let r=bs(e.path,await this.api.sessions(e.path,n),n);if(L(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedWorkspace?.id===e.id&&this.setState({error:String(t)})}}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`Project not found`);let n=await this.api.workspaces(t.id,L(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=L(e);await this.topologyRefreshes.request(Co(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(L(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=Sd(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||Cd(e,n)))return{selectedWorkspace:n}}};function xd(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Sd(e){return e.find(e=>e.isMain)??e[0]}function Cd(e,t){return e.path===t.path&&e.label===t.label&&e.branch===t.branch&&e.isMain===t.isMain&&e.isGitRepo===t.isGitRepo&&e.isGitWorktree===t.isGitWorktree}var wd=`pi-web:machine-navigation:v1`,Td=class{constructor(e=au()){this.snapshotsByMachine=new ou(wd,Ad,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?kd(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,kd(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Ed(e){return{machineId:e,surface:{}}}function Dd(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,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 Od(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 kd(e){return{...e,surface:{...e.surface}}}function Ad(e){if(!Id(e))return;let t=Fd(e,`machineId`);if(t===void 0)return;let n=Nd(Fd(e,`tool`)),r=Md(Fd(e,`view`));return{machineId:t,projectId:Fd(e,`projectId`),workspaceId:Fd(e,`workspaceId`),sessionId:Fd(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:jd(e.surface)}}function jd(e){return Id(e)?{selectedFilePath:Fd(e,`selectedFilePath`),selectedDiffPath:Fd(e,`selectedDiffPath`),selectedTerminalId:Fd(e,`selectedTerminalId`)}:{}}function Md(e){return e===`navigation`||e===`chat`?e:Nd(e)}function Nd(e){return Pd(e)?e:void 0}function Pd(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fd(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Id(e){return typeof e==`object`&&!!e}var Ld=`pi-web:terminal-selection:v1`,Rd=class{constructor(e=au()){this.terminalIdsByCwd=new ou(Ld,su,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function zd(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function Bd(e){return e.find(e=>!e.exited)??e[0]}var Vd=1200,Hd=[`mod`,`alt`,`shift`],Ud=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Jd(e);if(r===void 0)return!1;let i=Wd(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!Yd(r))return!1}else if(!Yd(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>pf(t.tokens,e));return n===void 0?t.some(t=>mf(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Vd)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function Wd(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Xd(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(ef)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(tf),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=nf(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:$d(t),i=n?[...s.get(e)??[]].sort(ef).map($d):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Gd(e){return of(e,{requireFirstChordActivator:!0})}function Kd(e){let t=of(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function qd(e){return Kd(e).map(e=>e.split(`+`).map(ff).join(`+`)).join(` `)}function Jd(e){if(e.isComposing)return;let t=uf(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function Yd(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Xd(e,t,n){let r=Zd(e.id,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Kd(i),o=a[0];if(!(o===void 0||!Yd(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:Qd(a),order:n}}function Zd(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Qd(e){return e.join(`\0`)}function $d(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ef(e,t){return rf(e.source)-rf(t.source)||af(e.action.id,t.action.id)||af(e.action.title,t.action.title)||e.order-t.order}function tf(e,t){return e.tokens.length-t.tokens.length||ef(e,t)}function nf(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&mf(e.tokens,t.tokens))}function rf(e){switch(e){case`custom`:return 0;case`default`:return 1}}function af(e,t){return e<t?-1:+(e>t)}function of(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`Enter a shortcut, choose None, or reset to the default.`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=sf(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Yd(i.token))return{ok:!1,message:`Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured.`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function sf(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`Shortcut chords must include a key.`};let n=new Set,r;for(let e of t){let t=cf(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${ff(t)} modifiers.`};n.add(t);continue}let i=lf(e);if(i===void 0)return{ok:!1,message:`Unsupported shortcut key: ${e}`};if(r!==void 0)return{ok:!1,message:`Each shortcut chord can include only one non-modifier key.`};r=i}return r===void 0?{ok:!1,message:`Shortcut chords must include a key.`}:{ok:!0,token:[...Hd.filter(e=>n.has(e)),r].join(`+`)}}function cf(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function lf(e){let t=df(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function uf(e){return e===` `?`space`:lf(e.toLowerCase())}function df(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function ff(e){return e===`mod`?hf()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?hf()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function pf(e,t){return e.length===t.length&&mf(e,t)}function mf(e,t){return t.every((t,n)=>e[n]===t)}function hf(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function gf(e,t){let n=e.parentSessionCwd;if(n===void 0||n===``)return{kind:`unknown`};let r=bf(t.workspaces,n);if(r!==void 0)return yf(r,e.parentSessionId,void 0);for(let[r,i]of Object.entries(t.workspacesByProjectId)){let a=bf(i,n);if(a===void 0)continue;let o=t.projects.find(e=>e.id===r)?.name;return yf(a,e.parentSessionId,o)}return{kind:`path`,label:xf(n),cwd:n}}function _f(e){return e.kind===`unknown`?`parent unavailable`:`parent in ${e.label}`}function vf(e){switch(e.kind){case`workspace`:return`Parent session is in ${e.label} (${e.cwd})`;case`path`:return`Parent session is in ${e.cwd}`;case`unknown`:return`Parent session is not available in this workspace`}}function yf(e,t,n){let r=e.branch??e.label;return{kind:`workspace`,label:n===void 0?r:`${n} · ${r}`,projectId:e.projectId,workspaceId:e.id,sessionId:t,cwd:e.path}}function bf(e,t){let n=z(t);return e.find(e=>z(e.path)===n)}function xf(e){let t=z(e).split(/[/\\]/u).filter(e=>e!==``),n=t.slice(-2);return n.length===0?e:t.length>n.length?`…/${n.join(`/`)}`:n.join(`/`)}var Sf={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Cf(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`Enable at least one cleanup action.`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=jf(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=jf(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function wf(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Tf(e){if(e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Cf(e.draft);return!t.ok||wf(t.request)!==wf(e.previewRequest)?!1:Ef(e.preview)}function Ef(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Df(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function Of(e,t){let n=new Set(Df(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function kf(e,t){return t(Af(e))}function Af(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`archive ${String(t)} idle ${t===1?`session`:`sessions`}`),n>0&&r.push(`permanently delete ${String(n)} archived ${n===1?`session`:`sessions`}`),`Run cleanup and ${r.length===0?`run cleanup`:r.join(` and `)}?\n\nPermanent deletion only applies to archived sessions and cannot be undone.`}function jf(e,t){let n=e.trim();if(n===``)return`${t} must be set.`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t} must be a non-negative whole number of days.`:r}var Mf=new Set,Nf=wt+1,Pf={unreadCatalog:e=>Ra.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Ra.acknowledgeUnread(e,t,n,r)},Ff=class{constructor(e={}){this.machines=new Map,this.api=e.api??Pf,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return Mf;let r=new Set;for(let e of t)n.summariesByIdentity.has(Vf(e))&&r.add(e.id);return r.size===0?Mf:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(Vf(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=If(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(Vf(t));if(i===void 0)return Promise.resolve();let a=Hf(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=Rf(t),a=`fresh`,o=!1;for(let e of n.events){let t=If(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=Nf?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!Bf(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function If(e,t,n){if(e===void 0){let e=zf(n.catalogId);return n.catalogRevision===1?Lf(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=zf(n.catalogId);return n.catalogRevision===1?Lf(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?Lf(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function Lf(e,t,n){let r=new Map(e.summariesByIdentity),i=Vf(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function Rf(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[Vf(e),{...e}]))}}function zf(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function Bf(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function Vf(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function Hf(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var Uf={machines:new Set,projects:new Set,workspaces:new Set};function Wf(e){let t=Kf(e.projectionFor(e.selectedMachineId));return{machines:qf(e.machineIds,e.projectionFor),projects:Yf(e.projects,e.workspacesByProjectId,t),workspaces:Jf(e.workspaces,t)}}function Gf(e){return e!==void 0&&e.sessions.length>0}function Kf(e){return e===void 0||e.sessions.length===0?Zf:new Set(e.sessions.map(e=>e.cwd))}function qf(e,t){let n=new Set;for(let r of e)Gf(t(r))&&n.add(r);return n}function Jf(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function Yf(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function Xf(e,t){return Qf(e.machines,t.machines)&&Qf(e.projects,t.projects)&&Qf(e.workspaces,t.workspaces)}var Zf=new Set;function Qf(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function $f(){return{selectedSessionKey:void 0,warningSetSignature:ep(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function ep(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function tp(e,t,n){let r=ep(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function np(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function rp(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function ip(e){return e.collapsed?rp(e):np(e)}var ap=`themes:classic`,op={themeId:`themes:pi-web-dark`,auto:!0},sp=`pi-web-app-theme`,cp=`--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`.split(`.`),lp=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function up(){try{let e=window.localStorage.getItem(sp);return e===null?void 0:gp(e)}catch{return}}function dp(e){try{window.localStorage.setItem(sp,JSON.stringify(e))}catch{}}function fp(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of cp){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function pp(e){let t=mp(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=hp(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function mp(e,t=ap){return e.find(e=>e.id===t)??e[0]}function hp(e,t){return e.find(e=>e.light===t||e.dark===t)}function gp(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return _p(e)?e:void 0}catch{return}}function _p(e){if(!vp(e))return!1;let t=e.themeId,n=e.auto;return yp(t)&&typeof n==`boolean`}function vp(e){return typeof e==`object`&&!!e}function yp(e){return typeof e==`string`&&lp.test(e)}var bp=`workspace.delete`,xp=`pi.operation`,Sp=`target.workspaceId`;function Cp(e){return{...e===void 0?{}:{projectId:e},metadata:{[xp]:bp}}}function wp(e){let t={};for(let n of e){let e=Dp(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Tp(e){return Object.entries(e).filter(([,e])=>Op(e)).map(([e])=>e)}function Ep(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Op(n)}function Dp(e){return e.metadata[Sp]}function Op(e){return e.status===`queued`||e.status===`running`}function kp(){return[{id:`actions.show`,title:`Show Actions`,description:`Open the command palette`,shortcut:`mod+k`,group:`General`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`Focus Prompt`,description:`Move keyboard focus to the message composer`,shortcut:`mod+g c`,group:`General`,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`Add Machine`,description:`Register another PI WEB runtime reachable from this gateway`,group:`Machine`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`Refresh Selected Machine`,description:`Check whether the selected PI WEB runtime is online`,group:`Machine`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`Open Selected Machine PI WEB`,description:`Open the selected remote PI WEB directly in a new tab`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`Remove Selected Machine`,description:`Remove the selected remote machine from this gateway`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`Add Project`,group:`Project`,run:e=>e.addProject()},{id:`auth.login`,title:`Configure Provider Authentication`,description:`Run /login without tying authentication to a session`,group:`General`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`Remove Provider Authentication`,description:`Run /logout for stored pi credentials`,group:`General`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`Select Theme`,description:`Choose the PI WEB color theme`,group:`Preferences`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`Open Settings`,description:`Manage PI WEB configuration and keyboard shortcuts`,shortcut:`mod+,`,group:`Preferences`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`Full Page Reload`,description:`Reload the PI WEB browser page`,group:`General`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`Go to Chat`,shortcut:`mod+1`,group:`Navigation`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`Go to Files`,shortcut:`mod+2`,group:`Navigation`,enabled:Ap,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.git`,title:`Go to Git`,shortcut:`mod+3`,group:`Navigation`,enabled:jp,run:e=>{e.selectMainView(`core:workspace.git`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+4`,group:`Navigation`,enabled:Ap,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:Ap,run:e=>e.refreshFiles()},{id:`workspace.refresh-git`,title:`Refresh Git`,shortcut:`mod+shift+g`,group:`Workspace`,enabled:jp,run:e=>e.refreshGit()},{id:`workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:Ap,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:Mp,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:Ap,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:Np,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:Np,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:Pp,run:e=>e.archiveSession()},{id:`session.reload`,title:`Reload Session from Disk`,description:`Close and re-open the selected session from its session file. Use /reload in the prompt for Pi runtime resources.`,group:`Session`,enabled:Ip,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:Fp,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&xo(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Ap(e){return e.state.selectedWorkspace!==void 0}function jp(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Mp(e){let t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Ep(e.state,t)}function Np(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Pp(e){return ru(e.state.selectedSession,e.state.status)}function Fp(e){return iu(e.state.selectedSession,e.state.status)}function Ip(e){return ru(e.state.selectedSession,e.state.status)?!xo(e.state.status,e.state.activity):!1}function Lp(e){return typeof e==`string`?Rp(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function Rp(e){switch(e){case`navigation`:return Je`
20
20
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
21
21
  <circle cx="6" cy="7" r="1.5"></circle>
22
22
  <path d="M10 7h8"></path>
@@ -50,7 +50,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
50
50
  <path d="m7 10 3 3-3 3"></path>
51
51
  <path d="M12 16h5"></path>
52
52
  </svg>
53
- `}}var Zp=`10 MB`;function Qp(e,t){return e===`error`?Je`
53
+ `}}var zp=`10 MB`;function Bp(e,t){return e===`error`?Je`
54
54
  <svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
55
55
  <circle cx="12" cy="12" r="10"></circle>
56
56
  <path d="m15 9-6 6"></path>
@@ -68,7 +68,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
68
68
  <path d="M12 9v4"></path>
69
69
  <path d="M12 17h.01"></path>
70
70
  </svg>
71
- `}var $p=h`
71
+ `}var Vp=h`
72
72
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
73
73
  :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; }
74
74
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -80,8 +80,6 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
80
80
  aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
81
81
  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); }
82
82
  .header-actions { display: flex; align-items: center; gap: 8px; }
83
- project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
84
- session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
85
83
  main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
86
84
  .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); }
87
85
  .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; }
@@ -153,12 +151,6 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
153
151
  main.navigation-view .empty { display: none; }
154
152
  main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
155
153
  main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
156
- main.navigation-view .mobile-navigation-panel project-list,
157
- main.navigation-view .mobile-navigation-panel workspace-list,
158
- main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
159
- main.navigation-view .mobile-navigation-panel project-list[collapsed],
160
- main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
161
- main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
162
154
  }
163
155
  status-bar { flex: 0 0 auto; }
164
156
  chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
@@ -166,7 +158,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
166
158
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
167
159
  .empty { margin: auto; color: var(--pi-muted); }
168
160
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
169
- `,em=h`
161
+ `,Hp=h`
170
162
  :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; }
171
163
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
172
164
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -221,7 +213,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
221
213
  .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); }
222
214
  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; }
223
215
  p { margin: 10px; }
224
- `,tm=h`
216
+ `,Up=h`
225
217
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
226
218
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
227
219
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -290,7 +282,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
290
282
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
291
283
  .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; }
292
284
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
293
- `,nm=h`
285
+ `,Wp=h`
294
286
  :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; }
295
287
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
296
288
  .top-notices { box-sizing: border-box; flex: 0 0 auto; max-height: 40%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg-overlay); }
@@ -451,7 +443,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
451
443
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
452
444
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; direction: ltr; text-align: left; unicode-bidi: isolate; }
453
445
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
454
- `,rm=h`
446
+ `,Gp=h`
455
447
  :host { display: block; }
456
448
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; text-align: start; unicode-bidi: plaintext; }
457
449
  p, ul, ol, pre, blockquote, .table-scroll, .code-block-wrapper { margin: 0 0 10px; }
@@ -478,7 +470,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
478
470
  table { border-collapse: collapse; width: max-content; min-width: 100%; max-width: none; }
479
471
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; max-width: 48ch; overflow-wrap: anywhere; }
480
472
  th { background: var(--pi-surface); }
481
- `,im=h`
473
+ `,Kp=h`
482
474
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
483
475
  .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
484
476
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -491,7 +483,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
491
483
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
492
484
  .muted { color: var(--pi-dim); }
493
485
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
494
- `,am=h`
486
+ `,qp=h`
495
487
  :host { display: block; }
496
488
  .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); }
497
489
  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; }
@@ -499,7 +491,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
499
491
  button.selected, button:hover { background: var(--pi-selection-bg); }
500
492
  span { color: var(--pi-muted); font-size: 12px; }
501
493
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
502
- `,om=h`
494
+ `,Jp=h`
503
495
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
504
496
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
505
497
  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; }
@@ -513,7 +505,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
513
505
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
514
506
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
515
507
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
516
- `,sm=h`
508
+ `,Yp=h`
517
509
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
518
510
  .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; }
519
511
  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; }
@@ -534,7 +526,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
534
526
  .group { grid-column: 1 / -1; font-size: 12px; }
535
527
  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; }
536
528
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
537
- `,cm=h`
529
+ `,Xp=h`
538
530
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
539
531
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
540
532
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -585,7 +577,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
585
577
  button { padding: 5px 7px; }
586
578
  .icon-button { width: 34px; height: 34px; }
587
579
  }
588
- `;function B(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var lm=`modulepreload`,um=function(e,t){return new URL(e,t).href},dm={},fm=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=um(t,n),t=s(t),t in dm)return;dm[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:lm,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},pm=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=bm(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{xm(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{xm(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{xm(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!xm(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=bm(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&vm(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&ym(t)!==ym(this.context)&&this.resetPendingUpload()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
580
+ `;function B(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Zp=`modulepreload`,Qp=function(e,t){return new URL(e,t).href},$p={},em=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Qp(t,n),t=s(t),t in $p)return;$p[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Zp,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},tm=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=cm(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{lm(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{lm(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{lm(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!lm(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=cm(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&om(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&sm(t)!==sm(this.context)&&this.resetPendingUpload()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
589
581
  <section
590
582
  class=${this.dragActive?`files-panel dragging`:`files-panel`}
591
583
  @dragenter=${this.handleDragEnter}
@@ -625,22 +617,22 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
625
617
  <span>${t.name}</span>
626
618
  </button>
627
619
  ${i?r.map(t=>this.renderTreeEntry(e,t,n+1)):null}
628
- `}selectTreeEntry(e,t){t.type===`directory`?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderFileViewer(e){let t=_m(e);if(t!==void 0)return g`<p class="muted">${t}</p>`;let n=e.selectedFileContent;return n===void 0?g`<p class="muted">Select a file.</p>`:n.mediaType===`image`?this.renderImageViewer(e,n):(km(),g`
620
+ `}selectTreeEntry(e,t){t.type===`directory`?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderFileViewer(e){let t=am(e);if(t!==void 0)return g`<p class="muted">${t}</p>`;let n=e.selectedFileContent;return n===void 0?g`<p class="muted">Select a file.</p>`:n.mediaType===`image`?this.renderImageViewer(e,n):(_m(),g`
629
621
  <div class="viewer-header"><strong>${n.path}</strong><small>${n.language??`text`}${n.truncated?` · truncated`:``}</small></div>
630
622
  <code-viewer .content=${n.content} .language=${n.language}></code-viewer>
631
- `)}renderImageViewer(e,t){let n=`${t.mimeType??`image`} · ${Am(t.size)}`;if(t.size>10485760)return g`
623
+ `)}renderImageViewer(e,t){let n=`${t.mimeType??`image`} · ${vm(t.size)}`;if(t.size>10485760)return g`
632
624
  <div class="viewer-header"><strong>${t.path}</strong><small>${n}</small></div>
633
- <p class="muted">Image too large to preview: ${Am(t.size)} · limit ${Zp}</p>
634
- `;let r=_a(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return g`
625
+ <p class="muted">Image too large to preview: ${vm(t.size)} · limit ${zp}</p>
626
+ `;let r=ba(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return g`
635
627
  <div class="viewer-header"><strong>${t.path}</strong><small>${n}</small></div>
636
628
  <div class="image-preview">
637
629
  <img src=${r} alt=${t.path} decoding="async" />
638
630
  </div>
639
- `}renderUploadProgress(e){let t=mm(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:g`
631
+ `}renderUploadProgress(e){let t=nm(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:g`
640
632
  <section class="upload-progress" aria-label="Workspace uploads">
641
633
  <div class="upload-progress-header">
642
634
  <strong>Uploads</strong>
643
- <small>${Sm(t)}</small>
635
+ <small>${um(t)}</small>
644
636
  </div>
645
637
  ${t.map(t=>this.renderUploadBatch(e,t))}
646
638
  </section>
@@ -648,12 +640,12 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
648
640
  <article class=${`upload-batch ${t.status}`}>
649
641
  <div class="upload-batch-heading">
650
642
  <div>
651
- <strong>${Cm(t)}</strong>
643
+ <strong>${dm(t)}</strong>
652
644
  <small>${t.destinationFolder===``?`workspace root`:t.destinationFolder}</small>
653
645
  </div>
654
- <span>${wm(t)}</span>
646
+ <span>${fm(t)}</span>
655
647
  </div>
656
- <progress max="1" .value=${Tm(t)}></progress>
648
+ <progress max="1" .value=${pm(t)}></progress>
657
649
  <div class="upload-file-list">
658
650
  ${t.files.map(e=>this.renderUploadFile(e))}
659
651
  </div>
@@ -661,13 +653,13 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
661
653
  ${t.status===`uploading`?g`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>Cancel</button>`:g`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>Dismiss</button>`}
662
654
  </div>
663
655
  </article>
664
- `}renderUploadFile(e){let t=Dm(e);return g`
656
+ `}renderUploadFile(e){let t=hm(e);return g`
665
657
  <div class=${`upload-file ${e.status}`}>
666
658
  <div class="upload-file-main">
667
659
  <span>${e.name}</span>
668
660
  <small>${t}</small>
669
661
  </div>
670
- <span class="upload-file-status">${Em(e)}</span>
662
+ <span class="upload-file-status">${mm(e)}</span>
671
663
  </div>
672
664
  `}renderUploadDialog(e,t){let n=t.files.length;return g`
673
665
  <div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
@@ -700,7 +692,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
700
692
  ${t.files.map(e=>g`
701
693
  <div class="review-file">
702
694
  <span>${e.name}</span>
703
- <small>${Am(e.size)}</small>
695
+ <small>${vm(e.size)}</small>
704
696
  </div>
705
697
  `)}
706
698
  </section>
@@ -712,7 +704,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
712
704
  </form>
713
705
  </section>
714
706
  </div>
715
- `}openUploadReview(e){let t=this.context,n=gm(t?.workspaceUploadDefaultFolder??``);this.pendingUpload={files:e},this.destinationFolder=n.destinationFolder,this.overwrite=n.overwrite,this.createDirs=n.createDirs,this.formError=``}submitUploadReview(e,t,n){e.preventDefault();let r=hm(n.files,this.destinationFolder);if(r!==void 0){this.formError=r;return}t.onStartWorkspaceUpload(n.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=``}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}static{this.styles=[em,h`
707
+ `}openUploadReview(e){let t=this.context,n=im(t?.workspaceUploadDefaultFolder??``);this.pendingUpload={files:e},this.destinationFolder=n.destinationFolder,this.overwrite=n.overwrite,this.createDirs=n.createDirs,this.formError=``}submitUploadReview(e,t,n){e.preventDefault();let r=rm(n.files,this.destinationFolder);if(r!==void 0){this.formError=r;return}t.onStartWorkspaceUpload(n.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=``}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}static{this.styles=[Hp,h`
716
708
  :host { flex: 1 1 auto; }
717
709
  .files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
718
710
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
@@ -758,7 +750,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
758
750
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
759
751
  .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; overflow-wrap: anywhere; }
760
752
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
761
- `]}};B([b({attribute:!1})],pm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],pm.prototype,`uploadInput`,void 0),B([x()],pm.prototype,`pendingUpload`,void 0),B([x()],pm.prototype,`destinationFolder`,void 0),B([x()],pm.prototype,`overwrite`,void 0),B([x()],pm.prototype,`createDirs`,void 0),B([x()],pm.prototype,`formError`,void 0),B([x()],pm.prototype,`dragActive`,void 0),pm=B([y(`workspace-files-panel`)],pm);function mm(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function hm(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{to(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function gm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function _m(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Am(t.size)}`}function vm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function ym(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function bm(e){return e==null?[]:Array.from(e)}function xm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Sm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Cm(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function wm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Om(e.percent)}}function Tm(e){return e.status===`uploading`?e.percent:1}function Em(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Om(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Dm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Am(e.loaded)} / ${Am(e.total)}`:`Wrote ${e.response.path}`:e.error}function Om(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function km(){fm(()=>import(`./CodeViewer-CDVbMiN9.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Am(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${jm(t)} KB`;let n=t/1024;return n<1024?`${jm(n)} MB`:`${jm(n/1024)} GB`}function jm(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function Mm(e){let t=e.submoduleFromCommit,n=e.submoduleToCommit;return t!==void 0&&n!==void 0?`${t} → ${n}`:`commit`}function Nm(e){let t=e.split(`/`);return t[t.length-1]??e}function Pm(e,t=[]){let n=Im(``),r=new Set(t);for(let e of t)Rm(n,e).isSubmodule=!0;for(let t of e){if(r.has(t.path)){let e=Rm(n,t.path);e.isSubmodule=!0,e.pointer={kind:`file`,name:Mm(t),path:t.path,file:t,isSubmodulePointer:!0};continue}let e=t.path.split(`/`).filter(e=>e.length>0),i=e[e.length-1];if(i===void 0)continue;let a=n;for(let t=0;t<e.length-1;t+=1){let n=e[t];n!==void 0&&(a=Lm(a,n))}a.files.push({kind:`file`,name:i,path:t.path,file:t})}return zm(n)}function Fm(e){let t=[];for(let n of e)n.kind===`directory`&&(t.push(n.path),t.push(...Fm(n.children)));return t}function Im(e){return{path:e,directories:new Map,files:[],isSubmodule:!1}}function Lm(e,t){let n=e.path.length===0?t:`${e.path}/${t}`,r=e.directories.get(n);if(r!==void 0)return r;let i=Im(n);return e.directories.set(n,i),i}function Rm(e,t){let n=e;for(let e of t.split(`/`).filter(e=>e.length>0))n=Lm(n,e);return n}function zm(e){let t=[...e.directories.values()].map(e=>({kind:`directory`,name:Nm(e.path),path:e.path,...e.isSubmodule?{isSubmodule:!0}:{},children:zm(e)})).sort((e,t)=>e.name.localeCompare(t.name)),n=[...e.files].sort((e,t)=>e.name.localeCompare(t.name));return[...e.pointer===void 0?[]:[e.pointer],...t,...n]}function Bm(e,t=[]){let n=new Set(t),r=new Map,i=new Map;for(let e of t)i.set(e,[]);let a=[];for(let o of e){if(n.has(o.path)){r.set(o.path,{name:Mm(o),file:o});continue}let e=Vm(o.path,t);if(e!==void 0){i.get(e)?.push({path:o.path,relativePath:o.path.slice(e.length+1),file:o});continue}a.push(o)}return{submodules:t.map(e=>{let t=r.get(e),n=i.get(e)??[];return{path:e,name:Nm(e),...t===void 0?{}:{pointer:t},files:[...n].sort((e,t)=>e.relativePath.localeCompare(t.relativePath))}}).sort((e,t)=>e.name.localeCompare(t.name)),files:a}}function Vm(e,t){let n;for(let r of t)r!==``&&e.startsWith(`${r}/`)&&(n===void 0||r.length>n.length)&&(n=r);return n}var Hm=`pi-web.gitFileView`;function Um(e){return e===`tree`?`tree`:`list`}function Wm(e=Km()){if(e===void 0)return`list`;try{return Um(e.getItem(Hm))}catch{return`list`}}function Gm(e,t=Km()){if(t!==void 0)try{t.setItem(Hm,e)}catch{}}function Km(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var qm={submodules:[],files:[]},Jm={nodes:[],listModel:qm,expandablePaths:[]},Ym=class extends v{constructor(...e){super(...e),this.view=Wm(),this.expandedDirectories=new Set}static{this.styles=[em,h`
753
+ `]}};B([b({attribute:!1})],tm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],tm.prototype,`uploadInput`,void 0),B([x()],tm.prototype,`pendingUpload`,void 0),B([x()],tm.prototype,`destinationFolder`,void 0),B([x()],tm.prototype,`overwrite`,void 0),B([x()],tm.prototype,`createDirs`,void 0),B([x()],tm.prototype,`formError`,void 0),B([x()],tm.prototype,`dragActive`,void 0),tm=B([y(`workspace-files-panel`)],tm);function nm(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function rm(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{to(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function im(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function am(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${vm(t.size)}`}function om(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function sm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function cm(e){return e==null?[]:Array.from(e)}function lm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function um(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function dm(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function fm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return gm(e.percent)}}function pm(e){return e.status===`uploading`?e.percent:1}function mm(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return gm(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function hm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${vm(e.loaded)} / ${vm(e.total)}`:`Wrote ${e.response.path}`:e.error}function gm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function _m(){em(()=>import(`./CodeViewer-D91Sp61M.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function vm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${ym(t)} KB`;let n=t/1024;return n<1024?`${ym(n)} MB`:`${ym(n/1024)} GB`}function ym(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function bm(e){let t=e.submoduleFromCommit,n=e.submoduleToCommit;return t!==void 0&&n!==void 0?`${t} → ${n}`:`commit`}function xm(e){let t=e.split(`/`);return t[t.length-1]??e}function Sm(e,t=[]){let n=wm(``),r=new Set(t);for(let e of t)Em(n,e).isSubmodule=!0;for(let t of e){if(r.has(t.path)){let e=Em(n,t.path);e.isSubmodule=!0,e.pointer={kind:`file`,name:bm(t),path:t.path,file:t,isSubmodulePointer:!0};continue}let e=t.path.split(`/`).filter(e=>e.length>0),i=e[e.length-1];if(i===void 0)continue;let a=n;for(let t=0;t<e.length-1;t+=1){let n=e[t];n!==void 0&&(a=Tm(a,n))}a.files.push({kind:`file`,name:i,path:t.path,file:t})}return Dm(n)}function Cm(e){let t=[];for(let n of e)n.kind===`directory`&&(t.push(n.path),t.push(...Cm(n.children)));return t}function wm(e){return{path:e,directories:new Map,files:[],isSubmodule:!1}}function Tm(e,t){let n=e.path.length===0?t:`${e.path}/${t}`,r=e.directories.get(n);if(r!==void 0)return r;let i=wm(n);return e.directories.set(n,i),i}function Em(e,t){let n=e;for(let e of t.split(`/`).filter(e=>e.length>0))n=Tm(n,e);return n}function Dm(e){let t=[...e.directories.values()].map(e=>({kind:`directory`,name:xm(e.path),path:e.path,...e.isSubmodule?{isSubmodule:!0}:{},children:Dm(e)})).sort((e,t)=>e.name.localeCompare(t.name)),n=[...e.files].sort((e,t)=>e.name.localeCompare(t.name));return[...e.pointer===void 0?[]:[e.pointer],...t,...n]}function Om(e,t=[]){let n=new Set(t),r=new Map,i=new Map;for(let e of t)i.set(e,[]);let a=[];for(let o of e){if(n.has(o.path)){r.set(o.path,{name:bm(o),file:o});continue}let e=km(o.path,t);if(e!==void 0){i.get(e)?.push({path:o.path,relativePath:o.path.slice(e.length+1),file:o});continue}a.push(o)}return{submodules:t.map(e=>{let t=r.get(e),n=i.get(e)??[];return{path:e,name:xm(e),...t===void 0?{}:{pointer:t},files:[...n].sort((e,t)=>e.relativePath.localeCompare(t.relativePath))}}).sort((e,t)=>e.name.localeCompare(t.name)),files:a}}function km(e,t){let n;for(let r of t)r!==``&&e.startsWith(`${r}/`)&&(n===void 0||r.length>n.length)&&(n=r);return n}var Am=`pi-web.gitFileView`;function jm(e){return e===`tree`?`tree`:`list`}function Mm(e=Pm()){if(e===void 0)return`list`;try{return jm(e.getItem(Am))}catch{return`list`}}function Nm(e,t=Pm()){if(t!==void 0)try{t.setItem(Am,e)}catch{}}function Pm(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var Fm={submodules:[],files:[]},Im={nodes:[],listModel:Fm,expandablePaths:[]},Lm=class extends v{constructor(...e){super(...e),this.view=Mm(),this.expandedDirectories=new Set}static{this.styles=[Hp,h`
762
754
  :host { flex: 1 1 auto; }
763
755
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
764
756
  .toolbar .toolbar-actions button { margin-left: 0; }
@@ -769,7 +761,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
769
761
  .view-toggle button.selected { position: relative; z-index: 1; }
770
762
  .row .twisty { color: var(--pi-dim, var(--pi-muted)); }
771
763
  .submodule-badge { display: inline-block; margin-left: 6px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; vertical-align: baseline; }
772
- `]}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&nh(t)!==nh(this.context)&&(this.expandedDirectories=new Set)}render(){let e=this.context;if(e===void 0)return g`<p class="muted">Git unavailable.</p>`;let t=e.gitStatus,n=this.computeViewState(t);return g`
764
+ `]}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&Wm(t)!==Wm(this.context)&&(this.expandedDirectories=new Set)}render(){let e=this.context;if(e===void 0)return g`<p class="muted">Git unavailable.</p>`;let t=e.gitStatus,n=this.computeViewState(t);return g`
773
765
  <section class="toolbar">
774
766
  <strong>Git</strong>
775
767
  ${e.gitStale?g`<span class="stale">stale</span>`:null}
@@ -783,7 +775,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
783
775
  <div class="list">
784
776
  ${this.renderFileList(e,t,n)}
785
777
  </div>
786
- <div class="viewer">${Zm(e)}</div>
778
+ <div class="viewer">${zm(e)}</div>
787
779
  </section>
788
780
  `}renderViewToggle(){return g`
789
781
  <div class="view-toggle" role="group" aria-label="Changed files view">
@@ -794,13 +786,13 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
794
786
  <button type="button" class=${n?`selected`:``} aria-pressed=${n?`true`:`false`} @click=${()=>{this.setView(e)}}>${t}</button>
795
787
  `}renderExpandCollapseAll(e){let t=e.every(e=>this.expandedDirectories.has(e));return g`
796
788
  <button type="button" @click=${()=>{this.toggleExpandAll(e,t)}}>${t?`Collapse all`:`Expand all`}</button>
797
- `}renderFileList(e,t,n){if(t===void 0)return g`<p class="muted">No status loaded.</p>`;if(!t.isGitRepo)return g`<p class="muted">Not a git repository.</p>`;let r=g`<p class="summary">${eh(t)}</p>`;return t.files.length===0?g`${r}<p class="muted">No changes.</p>`:g`${r}${this.view===`tree`?n.nodes.map(t=>this.renderTreeNode(e,t,0)):this.renderListBody(e,n.listModel)}`}renderListBody(e,t){return g`
789
+ `}renderFileList(e,t,n){if(t===void 0)return g`<p class="muted">No status loaded.</p>`;if(!t.isGitRepo)return g`<p class="muted">Not a git repository.</p>`;let r=g`<p class="summary">${Hm(t)}</p>`;return t.files.length===0?g`${r}<p class="muted">No changes.</p>`:g`${r}${this.view===`tree`?n.nodes.map(t=>this.renderTreeNode(e,t,0)):this.renderListBody(e,n.listModel)}`}renderListBody(e,t){return g`
798
790
  ${t.submodules.map(t=>this.renderSubmoduleGroup(e,t))}
799
791
  ${t.files.map(t=>this.renderFileRow(e,t))}
800
792
  `}renderSubmoduleGroup(e,t){let n=this.expandedDirectories.has(t.path);return g`
801
793
  <button type="button" class="row" style="--depth:0" aria-expanded=${n?`true`:`false`} @click=${()=>{this.toggleDirectory(t.path)}}>
802
794
  <span class="twisty">${n?`▾`:`▸`}</span>
803
- <span>${t.name}${Xm()}</span>
795
+ <span>${t.name}${Rm()}</span>
804
796
  </button>
805
797
  ${n?g`
806
798
  ${t.pointer===void 0?null:this.renderSelectableRow(e,t.path,t.pointer.name,t.pointer.file,1)}
@@ -809,24 +801,24 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
809
801
  `}renderSubmoduleFileRow(e,t){return this.renderSelectableRow(e,t.path,t.relativePath,t.file,1)}renderTreeNode(e,t,n){if(t.kind===`directory`){let r=this.expandedDirectories.has(t.path);return g`
810
802
  <button type="button" class="row" style=${`--depth:${String(n)}`} aria-expanded=${r?`true`:`false`} @click=${()=>{this.toggleDirectory(t.path)}}>
811
803
  <span class="twisty">${r?`▾`:`▸`}</span>
812
- <span>${t.name}${t.isSubmodule===!0?Xm():null}</span>
804
+ <span>${t.name}${t.isSubmodule===!0?Rm():null}</span>
813
805
  </button>
814
806
  ${r?t.children.map(t=>this.renderTreeNode(e,t,n+1)):null}
815
807
  `}return this.renderSelectableRow(e,t.path,t.name,t.file,n)}renderFileRow(e,t){return this.renderSelectableRow(e,t.path,t.path,t,0)}renderSelectableRow(e,t,n,r,i){return g`
816
808
  <button type="button" class=${e.selectedDiffPath===t?`row selected`:`row`} style=${`--depth:${String(i)}`} @click=${()=>{e.onSelectDiff(t)}}>
817
- <span>${th(r.index,r.workingTree)}</span>
809
+ <span>${Um(r.index,r.workingTree)}</span>
818
810
  <span>${n}</span>
819
811
  </button>
820
- `}computeViewState(e){let t=this.viewStateCache;if(t!==void 0&&t.status===e&&t.view===this.view)return t.viewState;let n=this.buildViewState(e);return this.viewStateCache={status:e,view:this.view,viewState:n},n}buildViewState(e){if(e===void 0||!e.isGitRepo||e.files.length===0)return Jm;if(this.view===`tree`){let t=Pm(e.files,e.submodules);return{nodes:t,listModel:qm,expandablePaths:Fm(t)}}let t=Bm(e.files,e.submodules);return{nodes:[],listModel:t,expandablePaths:t.submodules.map(e=>e.path)}}setView(e){this.view!==e&&(this.view=e,Gm(e),this.expandedDirectories=new Set)}toggleDirectory(e){let t=new Set(this.expandedDirectories);t.has(e)?t.delete(e):t.add(e),this.expandedDirectories=t}toggleExpandAll(e,t){this.expandedDirectories=t?new Set:new Set(e)}};B([b({attribute:!1})],Ym.prototype,`context`,void 0),B([x()],Ym.prototype,`view`,void 0),B([x()],Ym.prototype,`expandedDirectories`,void 0),Ym=B([y(`workspace-git-panel`)],Ym);function Xm(){return g`<span class="submodule-badge">submodule</span>`}function Zm(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath===``)return g`<p class="muted">Select a changed file.</p>`;let t=e.selectedDiff,n=e.selectedStagedDiff;if(t===void 0||n===void 0)return g`<p class="muted">Loading diff…</p>`;let r=[n,t].filter(e=>e.diff!==``);return r.length===0?g`<p class="muted">No staged or unstaged diff.</p>`:g`
812
+ `}computeViewState(e){let t=this.viewStateCache;if(t!==void 0&&t.status===e&&t.view===this.view)return t.viewState;let n=this.buildViewState(e);return this.viewStateCache={status:e,view:this.view,viewState:n},n}buildViewState(e){if(e===void 0||!e.isGitRepo||e.files.length===0)return Im;if(this.view===`tree`){let t=Sm(e.files,e.submodules);return{nodes:t,listModel:Fm,expandablePaths:Cm(t)}}let t=Om(e.files,e.submodules);return{nodes:[],listModel:t,expandablePaths:t.submodules.map(e=>e.path)}}setView(e){this.view!==e&&(this.view=e,Nm(e),this.expandedDirectories=new Set)}toggleDirectory(e){let t=new Set(this.expandedDirectories);t.has(e)?t.delete(e):t.add(e),this.expandedDirectories=t}toggleExpandAll(e,t){this.expandedDirectories=t?new Set:new Set(e)}};B([b({attribute:!1})],Lm.prototype,`context`,void 0),B([x()],Lm.prototype,`view`,void 0),B([x()],Lm.prototype,`expandedDirectories`,void 0),Lm=B([y(`workspace-git-panel`)],Lm);function Rm(){return g`<span class="submodule-badge">submodule</span>`}function zm(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath===``)return g`<p class="muted">Select a changed file.</p>`;let t=e.selectedDiff,n=e.selectedStagedDiff;if(t===void 0||n===void 0)return g`<p class="muted">Loading diff…</p>`;let r=[n,t].filter(e=>e.diff!==``);return r.length===0?g`<p class="muted">No staged or unstaged diff.</p>`:g`
821
813
  <div class=${r.length===1?`diffs single`:`diffs`}>
822
- ${r.map(e=>Qm(e))}
814
+ ${r.map(e=>Bm(e))}
823
815
  </div>
824
- `}function Qm(e){return $m(),g`
816
+ `}function Bm(e){return Vm(),g`
825
817
  <section class="diff-section">
826
818
  <div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
827
819
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
828
820
  </section>
829
- `}function $m(){fm(()=>import(`./UnifiedDiffViewer-Cqke12ZX.js`),[],import.meta.url)}function eh(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function th(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function nh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function rh(){return[{id:`workspace.files`,title:`Files`,icon:Xp(`files`),order:10,render:ih},{id:`workspace.git`,title:`Git`,icon:Xp(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:oh},{id:`workspace.terminal`,title:`Terminal`,icon:Xp(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:ah}]}function ih(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function ah(e){return sh(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function oh(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function sh(){fm(()=>import(`./TerminalPanel-CTS1CgqF.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var ch={apiVersion:1,name:`PI WEB Core`,activate:()=>({contributions:{actions:Rp(),workspacePanels:rh()}})},lh={"--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`},uh={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},dh={"--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`},fh={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:uh},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:dh},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:lh}],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`}]}})},ph=/^[a-z][a-z0-9.-]*$/u;function mh(e){return ph.test(e)}var hh=`machine.`;function gh(e,t){if(e===``)throw Error(`Machine id is required`);if(!mh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${hh}${_h(e)}.${t}`}function _h(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function vh(e=`pi-web-plugins/manifest.json`,t={}){let n=_t(e),r=await xh(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=yh(e.module,n),a=wh(await(t.moduleLoader??bh)(r),r);i.push({id:t.machineId===void 0?e.id:gh(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function yh(e,t,n){return e.startsWith(`/`)?n===void 0?_t(e):_t(e,n):new URL(e,t).toString()}async function bh(e){return fm(()=>import(e),[],import.meta.url)}async function xh(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return Sh(await t.json())}}function Sh(e){if(!Eh(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!Eh(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:Ch(e.machineSpecific)}})}}function Ch(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function wh(e,t){if(!Eh(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!Th(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function Th(e){return Eh(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function Eh(e){return typeof e==`object`&&!!e}var Dh=/^[a-z][a-z0-9.-]*$/u,Oh=/^[a-z][a-z0-9.-]*$/u,kh=new WeakMap,Ah=new WeakMap,jh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&Ih(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Rh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Mh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(Nh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(Nh(t,e)):void 0},render:n=>t.render(Nh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!Dh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Oh.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Lh(t)}`);return t}};function Mh(e,t){return kh.get(e)?.(t)??e}function Nh(e,t){return Ah.get(e)?.(t)??e}function Ph(e,t){return kh.set(e,t),e}function Fh(e,t){return Ah.set(e,t),e}function Ih(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Lh(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Rh(e){return e.state.selectedMachine?.id??`local`}function zh(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Bh=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function Vh(){return typeof window>`u`||!(`matchMedia`in window)?[]:Bh.map(e=>window.matchMedia(e))}function Hh(e,t=Uh()){return e.some(e=>e.matches)||Wh(t)}function Uh(){return typeof navigator>`u`?void 0:navigator}function Wh(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Gh=class{constructor(e=Kh()){this.scheduler=e}repair(e){if(!e){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()},250)}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);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Kh(){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}}}var qh=`(max-width: 760px)`,Jh=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=Hh(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Yh(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??Vh(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Gh,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Hh(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.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 Yh(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(qh)}var Xh=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new To,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Zh(),this.documentTarget=t.documentTarget??Qh(),this.isDocumentVisible=t.isDocumentVisible??$h,this.scheduleFrame=t.scheduleFrame??eg}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function Zh(){return typeof window>`u`?void 0:window}function Qh(){return typeof document>`u`?void 0:document}function $h(){return typeof document>`u`||document.visibilityState===`visible`}function eg(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var tg=[`machines`,`projects`,`workspaces`,`sessions`];function ng(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function rg(e,t){if(e!==`none`)return e??ng(t)}function ig(e,t){return t.isMobileLayout?rg(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function ag(e,t,n){return n.isMobileLayout?rg(e,n.state)===t?`none`:t:e}function og(e,t,n){return n?t:e}function sg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),ug(n)}function cg(e){return tg[tg.indexOf(e)+1]}var lg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return rg(this.expanded,this.getState())}isCollapsed(e){return ig(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(ag(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(sg(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(og(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=cg(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){dg(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function ug(e){let t=new Set(e);return tg.filter(e=>t.has(e))}function dg(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var fg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,pg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function pg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var mg=`pi-web:panel-sizes:v1`,hg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},gg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Ag(),this.panelSizes=Sg(this.storage)}hostConnected(){}constraints(e){return _g(e)}panelWidth(e,t){return xg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=xg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Eg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Dg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Cg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${kg(xg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${kg(xg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function _g(e){return hg[e]}function vg(e,t,n){return e===`navigation`?n-t:t-n}function yg(e,t,n,r,i=_g(e)){return xg(e,t+vg(e,n,r),i)}function bg(e,t,n,r={}){let i=r.constraints??_g(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Og(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return xg(e,t+a,i)}function xg(e,t,n=_g(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Sg(e=Ag()){try{let t=e?.getItem(mg);return t==null||t===``?{}:wg(JSON.parse(t))}catch{return{}}}function Cg(e,t=Ag()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(mg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=xg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=xg(`workspace`,e.workspacePanelWidth)),t.setItem(mg,JSON.stringify(n))}catch{}}function wg(e){if(!jg(e)||e.version!==1)return{};let t={},n=Tg(e.navigationPanelWidth),r=Tg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=xg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=xg(`workspace`,r)),t}function Tg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Eg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Dg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Og(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function kg(e){return`${String(Math.round(e))}px`}function Ag(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function jg(e){return typeof e==`object`&&!!e}function Mg(){let 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:Pg(e.get(`tool`)),view:Fg(e.get(`view`))}}function Ng(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Pg(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:Ig(e)?e:void 0}function Fg(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:Ig(e)?e:void 0}function Ig(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Lg(){return zg(new URLSearchParams(window.location.search).get(`settings`))}function Rg(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function zg(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Bg(e,t){return t===void 0?e:e.map(e=>Hg(e,t))}function Vg(e,t){let n=new Set(Qd(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Bg(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Ug(e):e)}function Hg(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?Ug(e):{...e,shortcut:n}}function Ug(e){let t={...e};return delete t.shortcut,t}function Wg(e,t){let n=t.api??za,r=t.pollIntervalMs??1e3,i=t.setTimeout??qg(),a=t.clearTimeout??Jg();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Gg(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Gg(e,t,n,r,i){return Kg(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Kg(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Kg(e){return e.status===`succeeded`||e.status===`failed`}function qg(){return(e,t)=>globalThis.setTimeout(e,t)}function Jg(){return e=>{globalThis.clearTimeout(e)}}var Yg=0,Xg=120;function Zg(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?$g():Qg(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Yg,f=n.top-c-Yg;return[...d<Xg&&f>d?[`bottom: ${e_(a-n.top+Yg)};`,`max-height: ${e_(Math.max(0,f))};`]:[`top: ${e_(n.bottom+Yg)};`,`max-height: ${e_(Math.max(0,d))};`],`right: ${e_(Math.max(0,i-u))};`,`max-width: ${e_(Math.max(0,u-o))};`].join(` `)}function Qg(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():$g()}function $g(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function e_(e){return`${String(Math.round(e))}px`}function t_(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function n_(e,t=`Active`,n){let r=t_(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var r_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function i_(e){return e.composedPath().some(e=>a_(e,r_))}function a_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function o_(e,t){i_(e)||t()}function s_(e,t){return i_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?l_(e,()=>{u_(e.currentTarget,-1)}):e.key===`ArrowDown`?l_(e,()=>{u_(e.currentTarget,1)}):e.key===`Home`?l_(e,()=>{d_(e.currentTarget,0)}):e.key===`End`?l_(e,()=>{d_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?l_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?l_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&l_(e,t.cancel)}function c_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function l_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function u_(e,t){let n=p_(e),r=h_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||f_(n,i+t)}function d_(e,t){let n=p_(e);n.length!==0&&f_(n,t<0?n.length-1:t)}function f_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function p_(e){let t=h_(e)?.getRootNode();return t===void 0||!m_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function m_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function h_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var V=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,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(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,c_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
821
+ `}function Vm(){em(()=>import(`./UnifiedDiffViewer-BafLWGtF.js`),[],import.meta.url)}function Hm(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function Um(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function Wm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Gm(){return[{id:`workspace.files`,title:`Files`,icon:Rp(`files`),order:10,render:Km},{id:`workspace.git`,title:`Git`,icon:Rp(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:Jm},{id:`workspace.terminal`,title:`Terminal`,icon:Rp(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:qm}]}function Km(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function qm(e){return Ym(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Jm(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function Ym(){em(()=>import(`./TerminalPanel-fYrKc3jh.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Xm={apiVersion:1,name:`PI WEB Core`,activate:()=>({contributions:{actions:kp(),workspacePanels:Gm()}})},Zm={"--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`},Qm={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},$m={"--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`},eh={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:Qm},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:$m},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Zm}],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`}]}})},th=/^[a-z][a-z0-9.-]*$/u;function nh(e){return th.test(e)}var rh=`machine.`;function ih(e,t){if(e===``)throw Error(`Machine id is required`);if(!nh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${rh}${ah(e)}.${t}`}function ah(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function oh(e=`pi-web-plugins/manifest.json`,t={}){let n=_t(e),r=await lh(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=sh(e.module,n),a=fh(await(t.moduleLoader??ch)(r),r);i.push({id:t.machineId===void 0?e.id:ih(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function sh(e,t,n){return e.startsWith(`/`)?n===void 0?_t(e):_t(e,n):new URL(e,t).toString()}async function ch(e){return em(()=>import(e),[],import.meta.url)}async function lh(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return uh(await t.json())}}function uh(e){if(!mh(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!mh(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:dh(e.machineSpecific)}})}}function dh(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function fh(e,t){if(!mh(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!ph(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ph(e){return mh(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function mh(e){return typeof e==`object`&&!!e}var hh=/^[a-z][a-z0-9.-]*$/u,gh=/^[a-z][a-z0-9.-]*$/u,_h=new WeakMap,vh=new WeakMap,yh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&wh(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Eh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=bh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(xh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(xh(t,e)):void 0},render:n=>t.render(xh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!hh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!gh.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Th(t)}`);return t}};function bh(e,t){return _h.get(e)?.(t)??e}function xh(e,t){return vh.get(e)?.(t)??e}function Sh(e,t){return _h.set(e,t),e}function Ch(e,t){return vh.set(e,t),e}function wh(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Th(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Eh(e){return e.state.selectedMachine?.id??`local`}function Dh(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Oh=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function kh(){return typeof window>`u`||!(`matchMedia`in window)?[]:Oh.map(e=>window.matchMedia(e))}function Ah(e,t=jh()){return e.some(e=>e.matches)||Mh(t)}function jh(){return typeof navigator>`u`?void 0:navigator}function Mh(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Nh=class{constructor(e=Ph()){this.scheduler=e}repair(e){if(!e){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()},250)}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);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Ph(){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}}}var Fh=`(max-width: 760px)`,Ih=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=Ah(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Lh(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??kh(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Nh,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Ah(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.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 Lh(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Fh)}var Rh=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new To,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??zh(),this.documentTarget=t.documentTarget??Bh(),this.isDocumentVisible=t.isDocumentVisible??Vh,this.scheduleFrame=t.scheduleFrame??Hh}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function zh(){return typeof window>`u`?void 0:window}function Bh(){return typeof document>`u`?void 0:document}function Vh(){return typeof document>`u`||document.visibilityState===`visible`}function Hh(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Uh=[`machines`,`projects`,`workspaces`,`sessions`];function Wh(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Gh(e,t){if(e!==`none`)return e??Wh(t)}function Kh(e,t){return t.isMobileLayout?Gh(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function qh(e,t,n){return n.isMobileLayout?Gh(e,n.state)===t?`none`:t:e}function Jh(e,t,n){return n?t:e}function Yh(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Qh(n)}function Xh(e){return Uh[Uh.indexOf(e)+1]}var Zh=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Gh(this.expanded,this.getState())}isCollapsed(e){return Kh(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(qh(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Yh(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Jh(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Xh(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){$h(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Qh(e){let t=new Set(e);return Uh.filter(e=>t.has(e))}function $h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var eg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,tg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function tg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var ng=`pi-web:panel-sizes:v1`,rg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},ig=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??vg(),this.panelSizes=ug(this.storage)}hostConnected(){}constraints(e){return ag(e)}panelWidth(e,t){return lg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=lg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=mg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=hg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){dg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${_g(lg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${_g(lg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function ag(e){return rg[e]}function og(e,t,n){return e===`navigation`?n-t:t-n}function sg(e,t,n,r,i=ag(e)){return lg(e,t+og(e,n,r),i)}function cg(e,t,n,r={}){let i=r.constraints??ag(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=gg(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return lg(e,t+a,i)}function lg(e,t,n=ag(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ug(e=vg()){try{let t=e?.getItem(ng);return t==null||t===``?{}:fg(JSON.parse(t))}catch{return{}}}function dg(e,t=vg()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ng);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=lg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=lg(`workspace`,e.workspacePanelWidth)),t.setItem(ng,JSON.stringify(n))}catch{}}function fg(e){if(!yg(e)||e.version!==1)return{};let t={},n=pg(e.navigationPanelWidth),r=pg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=lg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=lg(`workspace`,r)),t}function pg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function mg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function hg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function gg(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function _g(e){return`${String(Math.round(e))}px`}function vg(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function yg(e){return typeof e==`object`&&!!e}function bg(){let 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:Sg(e.get(`tool`)),view:Cg(e.get(`view`))}}function xg(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Sg(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:wg(e)?e:void 0}function Cg(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:wg(e)?e:void 0}function wg(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Tg(){return Dg(new URLSearchParams(window.location.search).get(`settings`))}function Eg(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function Dg(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Og(e,t){return t===void 0?e:e.map(e=>Ag(e,t))}function kg(e,t){let n=new Set(Wd(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Og(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?jg(e):e)}function Ag(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?jg(e):{...e,shortcut:n}}function jg(e){let t={...e};return delete t.shortcut,t}function Mg(e,t){let n=t.api??za,r=t.pollIntervalMs??1e3,i=t.setTimeout??Fg(),a=t.clearTimeout??Ig();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Ng(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ng(e,t,n,r,i){return Pg(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Pg(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Pg(e){return e.status===`succeeded`||e.status===`failed`}function Fg(){return(e,t)=>globalThis.setTimeout(e,t)}function Ig(){return e=>{globalThis.clearTimeout(e)}}var Lg=0,Rg=120;function zg(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Vg():Bg(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Lg,f=n.top-c-Lg;return[...d<Rg&&f>d?[`bottom: ${Hg(a-n.top+Lg)};`,`max-height: ${Hg(Math.max(0,f))};`]:[`top: ${Hg(n.bottom+Lg)};`,`max-height: ${Hg(Math.max(0,d))};`],`right: ${Hg(Math.max(0,i-u))};`,`max-width: ${Hg(Math.max(0,u-o))};`].join(` `)}function Bg(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vg()}function Vg(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Hg(e){return`${String(Math.round(e))}px`}function Ug(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function Wg(e,t=`Active`,n){let r=Ug(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var Gg=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Kg(e){return e.composedPath().some(e=>qg(e,Gg))}function qg(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function Jg(e,t){Kg(e)||t()}function Yg(e,t){return Kg(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?Zg(e,()=>{Qg(e.currentTarget,-1)}):e.key===`ArrowDown`?Zg(e,()=>{Qg(e.currentTarget,1)}):e.key===`Home`?Zg(e,()=>{$g(e.currentTarget,0)}):e.key===`End`?Zg(e,()=>{$g(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?Zg(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?Zg(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&Zg(e,t.cancel)}function Xg(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function Zg(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Qg(e,t){let n=t_(e),r=r_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||e_(n,i+t)}function $g(e,t){let n=t_(e);n.length!==0&&e_(n,t<0?n.length-1:t)}function e_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function t_(e){let t=r_(e)?.getRootNode();return t===void 0||!n_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function n_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function r_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var V=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,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(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Xg(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
830
822
  <section>
831
823
  <h2>${this.renderHeading()}</h2>
832
824
  ${this.collapsed?null:g`
@@ -835,12 +827,12 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
835
827
  </div>
836
828
  `}
837
829
  </section>
838
- `}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=g_(e)&&this.onRemove!==void 0;return g`
830
+ `}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=i_(e)&&this.onRemove!==void 0;return g`
839
831
  <div
840
832
  class=${`action-row machine-row ${this.selected?.id===e.id?`selected`:``} ${r?``:`no-actions`}`}
841
833
  tabindex="0"
842
834
  title=${e.baseUrl??e.name}
843
- @click=${t=>{o_(t,()=>this.onSelect?.(e))}}
835
+ @click=${t=>{Jg(t,()=>this.onSelect?.(e))}}
844
836
  @keydown=${t=>{this.handleMachineKeydown(t,e)}}
845
837
  >
846
838
  <div class="action-main">
@@ -849,7 +841,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
849
841
  </div>
850
842
  ${r?this.renderMachineMenu(e):null}
851
843
  </div>
852
- `}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=t===`offline`||t===`error`?void 0:os(this.activities[e.id]),r=this.unreadMachineIds.has(e.id)?`Unread sessions on this machine`:void 0;return n_(n,n===`terminal`?`Machine terminal active`:`Machine active`,r)}renderMachineMenu(e){let t=this.openMenuMachineId===e.id,n=__(e.id);return g`
844
+ `}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=t===`offline`||t===`error`?void 0:os(this.activities[e.id]),r=this.unreadMachineIds.has(e.id)?`Unread sessions on this machine`:void 0;return Wg(n,n===`terminal`?`Machine terminal active`:`Machine active`,r)}renderMachineMenu(e){let t=this.openMenuMachineId===e.id,n=a_(e.id);return g`
853
845
  <div class="action-menu">
854
846
  <button
855
847
  class="action-menu-toggle"
@@ -865,13 +857,13 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
865
857
  </div>
866
858
  `:null}
867
859
  </div>
868
- `}renderHeading(){if(!this.collapsible)return g`<span>Machines</span>`;let e=this.selected?.name??`No machine selected`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Machines</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Zg(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key===`Escape`&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}s_(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}static{this.styles=[tm,h`
860
+ `}renderHeading(){if(!this.collapsible)return g`<span>Machines</span>`;let e=this.selected?.name??`No machine selected`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Machines</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=zg(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key===`Escape`&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Yg(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}static{this.styles=[Up,h`
869
861
  .machine-row.no-actions .action-main { border-radius: 8px; }
870
862
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
871
863
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
872
864
  .machine-menu-panel button.danger { color: var(--pi-danger); }
873
865
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
874
- `]}};B([b({attribute:!1})],V.prototype,`machines`,void 0),B([b({attribute:!1})],V.prototype,`selected`,void 0),B([b({attribute:!1})],V.prototype,`statuses`,void 0),B([b({attribute:!1})],V.prototype,`activities`,void 0),B([b({attribute:!1})],V.prototype,`unreadMachineIds`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([b({attribute:!1})],V.prototype,`onSelect`,void 0),B([b({attribute:!1})],V.prototype,`onRemove`,void 0),B([b({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],V.prototype,`openMenuMachineId`,void 0),B([x()],V.prototype,`menuStyle`,void 0),V=B([y(`machine-list`)],V);function g_(e){return e.kind===`remote`}function __(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var H=class extends v{constructor(...e){super(...e),this.projects=[],this.activities={},this.workspacesByProjectId={},this.unreadProjectIds=new Set,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(e=>e.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,c_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
866
+ `]}};B([b({attribute:!1})],V.prototype,`machines`,void 0),B([b({attribute:!1})],V.prototype,`selected`,void 0),B([b({attribute:!1})],V.prototype,`statuses`,void 0),B([b({attribute:!1})],V.prototype,`activities`,void 0),B([b({attribute:!1})],V.prototype,`unreadMachineIds`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([b({attribute:!1})],V.prototype,`onSelect`,void 0),B([b({attribute:!1})],V.prototype,`onRemove`,void 0),B([b({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],V.prototype,`openMenuMachineId`,void 0),B([x()],V.prototype,`menuStyle`,void 0),V=B([y(`machine-list`)],V);function i_(e){return e.kind===`remote`}function a_(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var H=class extends v{constructor(...e){super(...e),this.projects=[],this.activities={},this.workspacesByProjectId={},this.unreadProjectIds=new Set,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(e=>e.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Xg(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
875
867
  <section>
876
868
  <h2>${this.renderHeading()}</h2>
877
869
  ${this.collapsed?null:g`
@@ -881,7 +873,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
881
873
  class=${`action-row ${this.selected?.id===e.id?`selected`:``}`}
882
874
  tabindex="0"
883
875
  title=${e.path}
884
- @click=${t=>{o_(t,()=>this.onSelect?.(e))}}
876
+ @click=${t=>{Jg(t,()=>this.onSelect?.(e))}}
885
877
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
886
878
  >
887
879
  <div class="action-main">
@@ -901,17 +893,17 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
901
893
  </div>
902
894
  `}
903
895
  </section>
904
- `}handleProjectKeydown(e,t){s_(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return g`<span>Projects</span>`;let e=this.selected?.name??`No project selected`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Projects</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){let t=is(e,this.workspacesByProjectId[e.id]??[],this.activities),n=this.unreadProjectIds.has(e.id)?`Unread sessions in this project`:void 0;return n_(t,t===`terminal`?`Project terminal active`:`Project active`,n)}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Zg(t,{constrainTo:`viewport`}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?\n\nThis only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}static{this.styles=tm}};B([b({attribute:!1})],H.prototype,`projects`,void 0),B([b({attribute:!1})],H.prototype,`selected`,void 0),B([b({attribute:!1})],H.prototype,`activities`,void 0),B([b({attribute:!1})],H.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],H.prototype,`unreadProjectIds`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([b({attribute:!1})],H.prototype,`onSelect`,void 0),B([b({attribute:!1})],H.prototype,`onClose`,void 0),B([b({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],H.prototype,`openMenuProjectId`,void 0),B([x()],H.prototype,`menuStyle`,void 0),H=B([y(`project-list`)],H);async function v_(e,t=y_()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function y_(){let e=e=>S_(e),t=x_();return t===void 0?{isSecureContext:b_(),fallbackWriteText:e}:{isSecureContext:b_(),writeText:t,fallbackWriteText:e}}function b_(){return typeof window<`u`&&window.isSecureContext}function x_(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function S_(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:C_(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),w_(n,r),T_(t)}}function C_(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function w_(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function T_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function E_(e=[]){return e.map((e,t)=>g`${t===0?null:g`<span class="workspace-label-separator">·</span>`}${D_(e)}`)}function D_(e){if(e.type===`render`)return g`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&O_(e.href)){let t=e.target??`_blank`,n=t===`_blank`?`noopener noreferrer`:void 0;return g`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${n??void 0}>${e.text}</a>`}return g`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function O_(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var U=class extends v{constructor(...e){super(...e),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.unreadWorkspaceIds=new Set,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(e=>e.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuWorkspaceId=void 0),this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){return this.collapsed?!1:e.has(`collapsed`)?!0:e.has(`selected`)&&e.get(`selected`)?.id!==this.selected?.id}async focusSelectedOrFirst(){return await this.updateComplete,c_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
896
+ `}handleProjectKeydown(e,t){Yg(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return g`<span>Projects</span>`;let e=this.selected?.name??`No project selected`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Projects</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){let t=is(e,this.workspacesByProjectId[e.id]??[],this.activities),n=this.unreadProjectIds.has(e.id)?`Unread sessions in this project`:void 0;return Wg(t,t===`terminal`?`Project terminal active`:`Project active`,n)}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=zg(t,{constrainTo:`viewport`}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?\n\nThis only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}static{this.styles=Up}};B([b({attribute:!1})],H.prototype,`projects`,void 0),B([b({attribute:!1})],H.prototype,`selected`,void 0),B([b({attribute:!1})],H.prototype,`activities`,void 0),B([b({attribute:!1})],H.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],H.prototype,`unreadProjectIds`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([b({attribute:!1})],H.prototype,`onSelect`,void 0),B([b({attribute:!1})],H.prototype,`onClose`,void 0),B([b({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],H.prototype,`openMenuProjectId`,void 0),B([x()],H.prototype,`menuStyle`,void 0),H=B([y(`project-list`)],H);async function o_(e,t=s_()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function s_(){let e=e=>u_(e),t=l_();return t===void 0?{isSecureContext:c_(),fallbackWriteText:e}:{isSecureContext:c_(),writeText:t,fallbackWriteText:e}}function c_(){return typeof window<`u`&&window.isSecureContext}function l_(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function u_(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:d_(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),f_(n,r),p_(t)}}function d_(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function f_(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function p_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function m_(e=[]){return e.map((e,t)=>g`${t===0?null:g`<span class="workspace-label-separator">·</span>`}${h_(e)}`)}function h_(e){if(e.type===`render`)return g`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&g_(e.href)){let t=e.target??`_blank`,n=t===`_blank`?`noopener noreferrer`:void 0;return g`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${n??void 0}>${e.text}</a>`}return g`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function g_(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var U=class extends v{constructor(...e){super(...e),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.unreadWorkspaceIds=new Set,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(e=>e.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuWorkspaceId=void 0),this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){return this.collapsed?!1:e.has(`collapsed`)?!0:e.has(`selected`)&&e.get(`selected`)?.id!==this.selected?.id}async focusSelectedOrFirst(){return await this.updateComplete,Xg(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
905
897
  <section>
906
898
  <h2>${this.renderHeading()}</h2>
907
899
  ${this.collapsed?null:g`
908
900
  <div class="list-body">
909
- ${this.workspaces.map(e=>{let t=k_(e),n=this.workspaceLabelItems(e);return g`
901
+ ${this.workspaces.map(e=>{let t=__(e),n=this.workspaceLabelItems(e);return g`
910
902
  <div
911
903
  class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
912
904
  tabindex="0"
913
905
  title=${t}
914
- @click=${t=>{o_(t,()=>this.onSelect?.(e))}}
906
+ @click=${t=>{Jg(t,()=>this.onSelect?.(e))}}
915
907
  @keydown=${t=>{this.handleWorkspaceKeydown(t,e)}}
916
908
  >
917
909
  <div class="action-main">
@@ -923,18 +915,18 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
923
915
  </div>
924
916
  `}
925
917
  </section>
926
- `}renderHeading(){if(!this.collapsible)return g`<span>Workspaces</span>`;let e=this.selected===void 0?`No workspace selected`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Workspaces</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=rs(ns(e,this.activities)),n=this.unreadWorkspaceIds.has(e.id)?`Unread sessions in this workspace`:void 0;return n_(t,t===`terminal`?`Workspace terminal active`:`Workspace active`,n)}renderWorkspaceMain(e,t,n){return g`
918
+ `}renderHeading(){if(!this.collapsible)return g`<span>Workspaces</span>`;let e=this.selected===void 0?`No workspace selected`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Workspaces</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=rs(ns(e,this.activities)),n=this.unreadWorkspaceIds.has(e.id)?`Unread sessions in this workspace`:void 0;return Wg(t,t===`terminal`?`Workspace terminal active`:`Workspace active`,n)}renderWorkspaceMain(e,t,n){return g`
927
919
  <span class="workspace-primary">
928
920
  <span class="workspace-primary-label">${e}</span>
929
921
  ${this.isDeleting(n)?g`<span class="workspace-status">Deleting…</span>`:null}
930
922
  </span>
931
923
  ${t.length===0?null:g`
932
924
  <small class="workspace-secondary">
933
- <span class="workspace-label">${E_(t)}</span>
925
+ <span class="workspace-label">${m_(t)}</span>
934
926
  </small>
935
927
  `}
936
928
  ${this.renderActivity(n)}
937
- `}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=j_(n.id);return g`
929
+ `}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=y_(n.id);return g`
938
930
  <div class="action-menu">
939
931
  <button
940
932
  class="action-menu-toggle"
@@ -951,7 +943,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
951
943
  </div>
952
944
  `:null}
953
945
  </div>
954
- `}renderWorkspaceActions(e){if(!A_(e))return;let t=this.isDeleting(e);return g`
946
+ `}renderWorkspaceActions(e){if(!v_(e))return;let t=this.isDeleting(e);return g`
955
947
  <div class="workspace-menu-actions">
956
948
  <button class="danger" title=${t?`Workspace deletion in progress`:`Delete workspace`} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?`Deleting…`:`Delete workspace`}</button>
957
949
  </div>
@@ -968,7 +960,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
968
960
  ${t.length===0?null:g`
969
961
  <div class="workspace-detail-row">
970
962
  <dt>Details</dt>
971
- <dd><span class="workspace-label">${E_(t)}</span></dd>
963
+ <dd><span class="workspace-label">${m_(t)}</span></dd>
972
964
  </div>
973
965
  `}
974
966
  </dl>
@@ -976,7 +968,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
976
968
  <button type="button" class="detail-copy" title=${i} aria-label=${i} @click=${()=>{this.copyDetail(e,t)}}>
977
969
  <span aria-hidden="true">${r?`✓`:`⧉`}</span>
978
970
  </button>
979
- `}async copyDetail(e,t){await v_(t)&&(this.copiedDetailKey=e,window.setTimeout(()=>{this.copiedDetailKey===e&&(this.copiedDetailKey=void 0)},1200))}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=Zg(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}s_(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}static{this.styles=tm}};B([b({attribute:!1})],U.prototype,`workspaces`,void 0),B([b({attribute:!1})],U.prototype,`selected`,void 0),B([b({type:Boolean,reflect:!0})],U.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],U.prototype,`collapsed`,void 0),B([b({attribute:!1})],U.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],U.prototype,`activities`,void 0),B([b({attribute:!1})],U.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],U.prototype,`unreadWorkspaceIds`,void 0),B([b({attribute:!1})],U.prototype,`onSelect`,void 0),B([b({attribute:!1})],U.prototype,`onDelete`,void 0),B([b({attribute:!1})],U.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],U.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],U.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],U.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],U.prototype,`openMenuWorkspaceId`,void 0),B([x()],U.prototype,`menuStyle`,void 0),B([x()],U.prototype,`copiedDetailKey`,void 0),U=B([y(`workspace-list`)],U);function k_(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function A_(e){return e.isGitWorktree&&!e.isMain}function j_(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function M_(e){return e.slice(-8)}function N_(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?M_(e.id):e.firstMessage}var W=class extends v{constructor(...e){super(...e),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.collapsible=!1,this.collapsed=!1,this.parentLocation=()=>({kind:`unknown`}),this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0);let 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}this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){if(this.collapsed)return!1;if(e.has(`collapsed`))return!0;if(!e.has(`selected`))return!1;let t=e.get(`selected`);return t?.id!==this.selected?.id||t?.archived===!0&&this.selected?.archived!==!0}async focusSelectedOrFirst(){return await this.updateComplete,c_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=H_(this.sessions),t=new Set(e.map(e=>e.session.id)),n=e.map(e=>e.session).filter(e=>I_(e)===`current`),r=U_(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id))),i=R_(this.sessions),a=P_(n,this.unreadSessionIds);return g`
971
+ `}async copyDetail(e,t){await o_(t)&&(this.copiedDetailKey=e,window.setTimeout(()=>{this.copiedDetailKey===e&&(this.copiedDetailKey=void 0)},1200))}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=zg(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Yg(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}static{this.styles=Up}};B([b({attribute:!1})],U.prototype,`workspaces`,void 0),B([b({attribute:!1})],U.prototype,`selected`,void 0),B([b({type:Boolean,reflect:!0})],U.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],U.prototype,`collapsed`,void 0),B([b({attribute:!1})],U.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],U.prototype,`activities`,void 0),B([b({attribute:!1})],U.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],U.prototype,`unreadWorkspaceIds`,void 0),B([b({attribute:!1})],U.prototype,`onSelect`,void 0),B([b({attribute:!1})],U.prototype,`onDelete`,void 0),B([b({attribute:!1})],U.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],U.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],U.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],U.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],U.prototype,`openMenuWorkspaceId`,void 0),B([x()],U.prototype,`menuStyle`,void 0),B([x()],U.prototype,`copiedDetailKey`,void 0),U=B([y(`workspace-list`)],U);function __(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function v_(e){return e.isGitWorktree&&!e.isMain}function y_(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function b_(e){return e.slice(-8)}function x_(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?b_(e.id):e.firstMessage}var W=class extends v{constructor(...e){super(...e),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.parentLocation=()=>({kind:`unknown`}),this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0);let 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}this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){if(this.collapsed)return!1;if(e.has(`collapsed`))return!0;if(!e.has(`selected`))return!1;let t=e.get(`selected`);return t?.id!==this.selected?.id||t?.archived===!0&&this.selected?.archived!==!0}async focusSelectedOrFirst(){return await this.updateComplete,Xg(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=A_(this.sessions),t=new Set(e.map(e=>e.session.id)),n=e.map(e=>e.session).filter(e=>w_(e)===`current`),r=j_(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id))),i=E_(this.sessions),a=S_(n,this.unreadSessionIds);return g`
980
972
  <section>
981
973
  ${this.renderHeading(e.length+r.length,n,a)}
982
974
  ${this.collapsed?null:g`
@@ -1002,7 +994,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1002
994
  ${this.renderCleanupButton()}
1003
995
  ${this.renderStartButton()}
1004
996
  </h2>
1005
- `;let r=this.selected===void 0?`No session selected`:N_(this.selected),i=this.selected?.path??r;return g`
997
+ `;let r=this.selected===void 0?`No session selected`:x_(this.selected),i=this.selected?.path??r;return g`
1006
998
  <h2>
1007
999
  <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Sessions</span>${this.collapsed?g`<small class="section-selected" dir="auto" title=${i}>${r}</small>`:null}</span></button>
1008
1000
  ${this.renderCurrentSelectionButton(t)}
@@ -1011,7 +1003,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1011
1003
  ${this.renderCleanupButton()}
1012
1004
  ${this.renderStartButton()}
1013
1005
  </h2>
1014
- `}renderUnreadCount(e){if(e===0)return null;let t=`${String(e)} unread`;return g`<small class="section-unread-count" title=${t}>${t}</small>`}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;let t=this.selectionScopes.has(`current`);return g`<button class="bulk-select-entry ${t?`selected`:``}" title=${t?`Close current session selection`:`Select current sessions`} aria-label=${t?`Close current session selection`:`Select current sessions`} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${t=>{t.stopPropagation(),this.toggleSelection(`current`,e)}}>☑</button>`}renderCleanupButton(){return g`<button class="cleanup-entry" title=${this.canCleanup?`Preview session cleanup`:this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>Clean up</button>`}renderStartButton(){let e=this.startingCount>0?`Start another session`:`Start a new session`;return g`<button class="start-session-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${e=>{e.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){let e=this.startingCount!==1;return g`
1006
+ `}renderUnreadCount(e){if(e===0)return null;let t=`${String(e)} unread`;return g`<small class="section-unread-count" title=${t}>${t}</small>`}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;let t=this.selectionScopes.has(`current`);return g`<button class="bulk-select-entry ${t?`selected`:``}" title=${t?`Close current session selection`:`Select current sessions`} aria-label=${t?`Close current session selection`:`Select current sessions`} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${t=>{t.stopPropagation(),this.toggleSelection(`current`,e)}}>☑</button>`}renderCleanupButton(){return g`<button class="cleanup-entry" title="Preview session cleanup" @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>Clean up</button>`}renderStartButton(){let e=this.startingCount>0?`Start another session`:`Start a new session`;return g`<button class="start-session-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${e=>{e.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){let e=this.startingCount!==1;return g`
1015
1007
  <div class="pending-session-row starting-session" role="status" aria-live="polite">
1016
1008
  <div class="action-main">
1017
1009
  <span class="action-name"><span class="activity-indicator sending" aria-hidden="true"></span>${e?`Starting ${String(this.startingCount)} sessions…`:`Starting session…`}</span>
@@ -1024,36 +1016,32 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1024
1016
  ${this.archivedExpanded?g`<button class="bulk-select-entry ${t?`selected`:``}" title=${t?`Close archived session selection`:`Select archived sessions`} aria-label=${t?`Close archived session selection`:`Select archived sessions`} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection(`archived`,e)}}>☑</button>`:null}
1025
1017
  <small class="section-count">${e.length}</small>
1026
1018
  </h2>
1027
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has(`current`))return null;let t=this.selectedSessions(`current`),n=t.filter(e=>iu(e,this.statuses[e.id],this.sessionPersistenceOptions())),r=t.filter(e=>this.unreadSessionIds.has(e.id)),i=e.length>0&&e.every(e=>this.selectedSessionIds.has(e.id)),a=e.filter(e=>this.selectedSessionIds.has(e.id)).length;return g`
1019
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has(`current`))return null;let t=this.selectedSessions(`current`),n=t.filter(e=>ru(e,this.statuses[e.id])),r=t.filter(e=>this.unreadSessionIds.has(e.id));return g`
1028
1020
  <div class="bulk-row selecting">
1029
- <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!i)}}>${i?`Clear visible`:`Select visible`}</button>
1030
- <small>${t.length} selected${a===t.length?null:g` · ${a} visible`}</small>
1031
- <button ?disabled=${n.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>Archive selected</button>
1021
+ ${this.renderSelectionControls(`current`,e)}
1022
+ <button ?disabled=${n.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>Archive</button>
1032
1023
  <button ?disabled=${r.length===0} @click=${()=>{this.markSelectedCurrentRead()}}>Mark read</button>
1033
- <button @click=${()=>{this.clearSelection(`current`)}}>Clear</button>
1034
- <button @click=${()=>{this.closeSelection(`current`)}}>Done</button>
1035
1024
  </div>
1036
- `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has(`archived`))return null;let t=this.selectedSessions(`archived`),n=e.length>0&&e.every(e=>this.selectedSessionIds.has(e.id)),r=e.filter(e=>this.selectedSessionIds.has(e.id)).length;return g`
1025
+ `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has(`archived`))return null;let t=this.selectedSessions(`archived`);return g`
1037
1026
  <div class="bulk-row selecting">
1038
- <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!n)}}>${n?`Clear visible`:`Select visible`}</button>
1039
- <small>${t.length} selected${r===t.length?null:g` · ${r} visible`}</small>
1040
- <button class="danger" title=${this.canDeleteArchived?`Permanently delete selected archived sessions`:this.archivedDeleteUnavailableMessage} ?disabled=${t.length===0||!this.canDeleteArchived} @click=${()=>{this.confirmDeleteSelectedArchived()}}>Delete selected</button>
1041
- <button @click=${()=>{this.clearSelection(`archived`)}}>Clear</button>
1042
- <button @click=${()=>{this.closeSelection(`archived`)}}>Done</button>
1043
- ${this.canDeleteArchived?null:g`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
1027
+ ${this.renderSelectionControls(`archived`,e)}
1028
+ <button class="danger" title="Permanently delete selected archived sessions" ?disabled=${t.length===0} @click=${()=>{this.confirmDeleteSelectedArchived()}}>Delete</button>
1044
1029
  </div>
1045
- `}renderSession(e,t,n){let{session:r}=e,i=Math.min(e.depth,2),a=I_(r)===n,o=this.selectionScopes.has(n),s=o&&a,c=s&&this.selectedSessionIds.has(r.id),l=this.statuses[r.id],u=this.activities[r.id],d=z_(r,l,u,this.sending[r.id]===!0),f=B_(r,this.unreadSessionIds),p=this.sessionPersistenceOptions(),m=iu(r,l,p),ee=au(r,l,p),te=m&&this.canReload;return g`
1030
+ `}renderSelectionControls(e,t){let n=this.selectedSessions(e).length,r=t.filter(e=>this.selectedSessionIds.has(e.id)).length;return g`
1031
+ ${n===0?g`<button @click=${()=>{this.selectVisibleSessions(t)}}>Select visible</button>`:g`<button @click=${()=>{this.clearSelection(e)}}>Clear selected</button>`}
1032
+ <small>${n} selected${r===n?null:g` · ${r} visible`}</small>
1033
+ `}renderSession(e,t,n){let{session:r}=e,i=Math.min(e.depth,2),a=w_(r)===n,o=this.selectionScopes.has(n),s=o&&a,c=s&&this.selectedSessionIds.has(r.id),l=this.statuses[r.id],u=this.activities[r.id],d=D_(r,l,u,this.sending[r.id]===!0),f=O_(r,this.unreadSessionIds),p=ru(r,l),m=iu(r,l);return g`
1046
1034
  <div
1047
1035
  class="action-row ${this.selected?.id===r.id?`selected`:``} ${c?`bulk-selected`:``} ${r.archived===!0?`archived`:``} ${o?`selecting`:``} ${f?`unread`:``}"
1048
1036
  style=${`--depth:${String(i)}`}
1049
1037
  tabindex="0"
1050
1038
  title=${r.path}
1051
- @click=${e=>{o_(e,()=>{this.activateSessionRow(r,n)})}}
1039
+ @click=${e=>{Jg(e,()=>{this.activateSessionRow(r,n)})}}
1052
1040
  @keydown=${e=>{this.handleSessionKeydown(e,r,n)}}
1053
1041
  >
1054
1042
  <div class="action-main ${o?`selecting`:``}">
1055
- ${s?g`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${N_(r)}`} .checked=${c} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(r.id)}}>`:null}
1056
- <span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${N_(r)}</span>${this.renderRowBadges(e)}</span><small>${this.renderSessionMetaPrefix(r,l,u)}${this.renderRelatedSessionsMeta(e)}${String(r.messageCount)} messages</small>
1043
+ ${s?g`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${x_(r)}`} .checked=${c} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(r.id)}}>`:null}
1044
+ <span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${x_(r)}</span>${this.renderRowBadges(e)}</span><small>${this.renderSessionMetaPrefix(r,l,u)}${this.renderRelatedSessionsMeta(e)}${String(r.messageCount)} messages</small>
1057
1045
  ${this.renderActivity(d,f)}
1058
1046
  </div>
1059
1047
  <div class="action-menu">
@@ -1062,22 +1050,22 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1062
1050
  <div class="action-menu-panel" style=${this.menuStyle}>
1063
1051
  ${r.archived===!0?g`
1064
1052
  <button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(r)}}>Restore</button>
1065
- <button class="danger" title=${this.canDeleteArchived?`Permanently delete archived session`:this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(r)}}>Delete archived session</button>
1066
- `:ee?g`<button title="Delete transient new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(r)}}>Delete</button>`:g`
1053
+ <button class="danger" title="Permanently delete archived session" @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(r)}}>Delete archived session</button>
1054
+ `:m?g`<button title="Delete transient new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(r)}}>Delete</button>`:g`
1067
1055
  ${this.unreadSessionIds.has(r.id)?g`<button title="Mark session as read" @click=${()=>{this.openMenuSessionId=void 0,this.onMarkRead?.(r)}}>Mark as read</button>`:null}
1068
- ${m?g`
1056
+ ${p?g`
1069
1057
  <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(r)}}>Archive</button>
1070
1058
  ${t>0?g`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(r,t)}}>Archive with descendants (${t})</button>`:null}
1071
1059
  `:null}
1072
1060
  ${this.renderGoToParentMenuItem(e)}
1073
1061
  ${r.parentSessionPath===void 0?null:g`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(r)}}>Detach from parent</button>`}
1074
- ${te?g`<button title=${xo(this.statuses[r.id],this.activities[r.id])?`Stop current session activity before reloading from disk`:`Reload session from disk without refreshing Pi runtime resources`} ?disabled=${xo(this.statuses[r.id],this.activities[r.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(r)}}>Reload from disk</button>`:null}
1062
+ ${p?g`<button title=${xo(this.statuses[r.id],this.activities[r.id])?`Stop current session activity before reloading from disk`:`Reload session from disk without refreshing Pi runtime resources`} ?disabled=${xo(this.statuses[r.id],this.activities[r.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(r)}}>Reload from disk</button>`:null}
1075
1063
  `}
1076
1064
  </div>
1077
1065
  `:null}
1078
1066
  </div>
1079
1067
  </div>
1080
- `}renderRowMarker(e){if(e.hasMissingParent){let t=this.parentLocation(e.session);return g`<span class="tree-marker orphan-marker" title=${Ef(t)} aria-label=${Tf(t)}>↳</span>`}return e.depth>0?g`<span class="tree-marker">↳</span>`:null}renderRowBadges(e){return e.depth<=2?null:g`<span class="row-badges"><span class="badge">depth ${e.depth}</span></span>`}renderRelatedSessionsMeta(e){let t=[e.hasMissingParent?Tf(this.parentLocation(e.session)):void 0,F_(e.session.childSessionsElsewhere)].filter(e=>e!==void 0);return t.length===0?null:`${t.join(` · `)} · `}renderGoToParentMenuItem(e){if(!e.hasMissingParent||this.onGoToParent===void 0)return null;let t=this.parentLocation(e.session);return t.kind===`workspace`?g`<button title=${Ef(t)} @click=${()=>{this.openMenuSessionId=void 0,this.onGoToParent?.(e.session,t)}}>Go to parent session</button>`:null}handleSessionKeydown(e,t,n){s_(e,{activate:()=>{this.activateSessionRow(t,n)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&I_(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){let n=t===1?`descendant session`:`descendant sessions`;confirm(`Archive “${N_(e)}” and ${String(t)} ${n}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${N_(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;let e=this.selectedSessions(`archived`);if(e.length===0)return;let t=e.length===1?`archived session`:`archived sessions`;confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=L_(this.selectedSessionIds,e.map(e=>e.id)),this.onDeleteArchivedMany?.(e))}markSelectedCurrentRead(){let e=this.selectedSessions(`current`).filter(e=>this.unreadSessionIds.has(e.id));e.length!==0&&this.onMarkReadMany?.(e)}archiveSelectedCurrent(){let e=this.selectedSessions(`current`).filter(e=>iu(e,this.statuses[e.id],this.sessionPersistenceOptions()));this.selectedSessionIds=L_(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);let n=t.length===1?t[0]:void 0;n!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,n.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){let t=this.sessions.filter(t=>I_(t)===e).map(e=>e.id);this.selectedSessionIds=L_(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){let n=new Set(this.selectedSessionIds);for(let r of e)t?n.add(r.id):n.delete(r.id);this.selectedSessionIds=n}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&I_(t)===e)}pruneSelectedSessionIds(){let e=new Set(this.sessions.map(e=>e.id)),t=new Set([...this.selectedSessionIds].filter(t=>e.has(t)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has(`archived`)&&!this.sessions.some(e=>e.archived===!0)&&this.closeSelection(`archived`),this.selectionScopes.has(`current`)&&!this.sessions.some(e=>e.archived!==!0)&&this.closeSelection(`current`)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Zg(t,{constrainTo:`viewport`}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has(`archived`)&&this.closeSelection(`archived`),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}renderSessionMetaPrefix(e,t,n){return au(e,t,this.sessionPersistenceOptions())?n?.phase===`active`?`creating · `:n?.phase===`error`?`error · `:`new · `:e.archived===!0?`read-only · `:``}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e,t){return n_(e,e===`sending`?`Sending message`:`Session active`,t?`Unread session activity`:void 0)}static{this.styles=[tm,h`
1068
+ `}renderRowMarker(e){if(e.hasMissingParent){let t=this.parentLocation(e.session);return g`<span class="tree-marker orphan-marker" title=${vf(t)} aria-label=${_f(t)}>↳</span>`}return e.depth>0?g`<span class="tree-marker">↳</span>`:null}renderRowBadges(e){return e.depth<=2?null:g`<span class="row-badges"><span class="badge">depth ${e.depth}</span></span>`}renderRelatedSessionsMeta(e){let t=[e.hasMissingParent?_f(this.parentLocation(e.session)):void 0,C_(e.session.childSessionsElsewhere)].filter(e=>e!==void 0);return t.length===0?null:`${t.join(` · `)} · `}renderGoToParentMenuItem(e){if(!e.hasMissingParent||this.onGoToParent===void 0)return null;let t=this.parentLocation(e.session);return t.kind===`workspace`?g`<button title=${vf(t)} @click=${()=>{this.openMenuSessionId=void 0,this.onGoToParent?.(e.session,t)}}>Go to parent session</button>`:null}handleSessionKeydown(e,t,n){Yg(e,{activate:()=>{this.activateSessionRow(t,n)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&w_(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){let n=t===1?`descendant session`:`descendant sessions`;confirm(`Archive “${x_(e)}” and ${String(t)} ${n}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){confirm(`Permanently delete archived session “${x_(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){let e=this.selectedSessions(`archived`);if(e.length===0)return;let t=e.length===1?`archived session`:`archived sessions`;confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=T_(this.selectedSessionIds,e.map(e=>e.id)),this.onDeleteArchivedMany?.(e))}markSelectedCurrentRead(){let e=this.selectedSessions(`current`).filter(e=>this.unreadSessionIds.has(e.id));e.length!==0&&this.onMarkReadMany?.(e)}archiveSelectedCurrent(){let e=this.selectedSessions(`current`).filter(e=>ru(e,this.statuses[e.id]));this.selectedSessionIds=T_(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);let n=t.length===1?t[0]:void 0;n!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,n.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){let t=this.sessions.filter(t=>w_(t)===e).map(e=>e.id);this.selectedSessionIds=T_(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}selectVisibleSessions(e){this.selectedSessionIds=new Set([...this.selectedSessionIds,...e.map(e=>e.id)])}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&w_(t)===e)}pruneSelectedSessionIds(){let e=new Set(this.sessions.map(e=>e.id)),t=new Set([...this.selectedSessionIds].filter(t=>e.has(t)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has(`archived`)&&!this.sessions.some(e=>e.archived===!0)&&this.closeSelection(`archived`),this.selectionScopes.has(`current`)&&!this.sessions.some(e=>e.archived!==!0)&&this.closeSelection(`current`)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=zg(t,{constrainTo:`viewport`}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has(`archived`)&&this.closeSelection(`archived`),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}renderSessionMetaPrefix(e,t,n){return iu(e,t)?n?.phase===`active`?`creating · `:n?.phase===`error`?`error · `:`new · `:e.archived===!0?`read-only · `:``}renderActivity(e,t){return Wg(e,e===`sending`?`Sending message`:`Session active`,t?`Unread session activity`:void 0)}static{this.styles=[Up,h`
1081
1069
  h2 { min-height: 30px; }
1082
1070
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
1083
1071
  h2 > .section-unread-count { flex: 0 0 auto; display: inline; color: var(--pi-accent); font-size: inherit; text-transform: none; }
@@ -1097,7 +1085,6 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1097
1085
  .row-badges .badge { margin-left: 0; white-space: nowrap; }
1098
1086
  /* Same glyph as a normal child marker, dimmed: the row is a child whose parent is not displayed here. */
1099
1087
  .orphan-marker { color: var(--pi-dim); opacity: .65; }
1100
- .bulk-row .capability-hint { flex: 1 0 100%; color: var(--pi-warning); }
1101
1088
  .bulk-row.selecting { padding: 6px; border: 1px solid var(--pi-border-muted); border-radius: 8px; background: color-mix(in srgb, var(--pi-surface) 65%, transparent); }
1102
1089
  button.danger, .action-menu-panel button.danger { color: var(--pi-danger); }
1103
1090
  button.danger:hover, .action-menu-panel button.danger:hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
@@ -1108,7 +1095,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1108
1095
  .pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
1109
1096
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
1110
1097
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
1111
- `]}};B([b({attribute:!1})],W.prototype,`sessions`,void 0),B([b({attribute:!1})],W.prototype,`statuses`,void 0),B([b({attribute:!1})],W.prototype,`activities`,void 0),B([b({attribute:!1})],W.prototype,`sending`,void 0),B([b({attribute:!1})],W.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],W.prototype,`selected`,void 0),B([b({type:Number})],W.prototype,`startingCount`,void 0),B([b({type:Boolean})],W.prototype,`canStart`,void 0),B([b({type:Boolean})],W.prototype,`canDeleteArchived`,void 0),B([b({type:Boolean})],W.prototype,`canReload`,void 0),B([b({type:Boolean})],W.prototype,`canCleanup`,void 0),B([b({type:Boolean})],W.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],W.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],W.prototype,`cleanupUnavailableMessage`,void 0),B([b({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),B([b({attribute:!1})],W.prototype,`onSelect`,void 0),B([b({attribute:!1})],W.prototype,`onStart`,void 0),B([b({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],W.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),B([b({attribute:!1})],W.prototype,`onArchive`,void 0),B([b({attribute:!1})],W.prototype,`onArchiveWithDescendants`,void 0),B([b({attribute:!1})],W.prototype,`onArchiveMany`,void 0),B([b({attribute:!1})],W.prototype,`onRestore`,void 0),B([b({attribute:!1})],W.prototype,`onDelete`,void 0),B([b({attribute:!1})],W.prototype,`onDeleteArchived`,void 0),B([b({attribute:!1})],W.prototype,`onDeleteArchivedMany`,void 0),B([b({attribute:!1})],W.prototype,`onDetachParent`,void 0),B([b({attribute:!1})],W.prototype,`parentLocation`,void 0),B([b({attribute:!1})],W.prototype,`onGoToParent`,void 0),B([b({attribute:!1})],W.prototype,`onMarkRead`,void 0),B([b({attribute:!1})],W.prototype,`onMarkReadMany`,void 0),B([b({attribute:!1})],W.prototype,`onReload`,void 0),B([b({attribute:!1})],W.prototype,`onCleanup`,void 0),B([x()],W.prototype,`openMenuSessionId`,void 0),B([x()],W.prototype,`menuStyle`,void 0),B([x()],W.prototype,`archivedExpanded`,void 0),B([x()],W.prototype,`selectionScopes`,void 0),B([x()],W.prototype,`selectedSessionIds`,void 0),W=B([y(`session-list`)],W);function P_(e,t){return e.filter(e=>B_(e,t)).length}function F_(e){if(!(e===void 0||e===0))return e===1?`1 child elsewhere`:`${String(e)} children elsewhere`}function I_(e){return e.archived===!0?`archived`:`current`}function L_(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function R_(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=Su(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=Su(e.path);if(r.has(i))return 0;let a=new Set(r);a.add(i);let o=0;for(let e of t.get(i)??[])a.has(Su(e.path))||(e.archived!==!0&&(o+=1),o+=n(e,a));return o};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function z_(e,t,n,r){if(!(xs(e)||e.archived===!0)){if(r)return`sending`;if(xo(t,n))return`session`}}function B_(e,t){return xs(e)||e.archived===!0?!1:t.has(e.id)}function V_(e){return new Map(e.map(e=>[Su(e.path),e]))}function H_(e){let t=V_(e),n=new Set;for(let r of e){if(r.archived===!0)continue;n.add(r.id);let e=r.parentSessionPath===void 0?void 0:Su(r.parentSessionPath),i=new Set([Su(r.path)]);for(;e!==void 0&&!i.has(e);){i.add(e);let r=t.get(e);if(r===void 0)break;n.add(r.id),e=r.parentSessionPath===void 0?void 0:Su(r.parentSessionPath)}}return U_(e.filter(e=>n.has(e.id)))}function U_(e){let t=V_(e),n=new Map,r=[];for(let i of e){let e=i.parentSessionPath,a=e===void 0?void 0:t.get(Su(e));if(a===void 0){r.push(i);continue}let o=Su(a.path),s=n.get(o)??[];s.push(i),n.set(o,s)}let i=[],a=(e,r,o)=>{let s=Su(e.path);if(o.has(s))return;let c=e.parentSessionPath;i.push({session:e,depth:r,hasMissingParent:c!==void 0&&!t.has(Su(c))});let l=new Set(o);l.add(s);for(let e of n.get(s)??[])a(e,r+1,l)};for(let e of r)a(e,0,new Set);return i}var W_=class extends v{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.loading=!1,this.running=!1,this.error=``,this.draft={...Af},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=jf(this.draft),t=this.selectedPreview(),n=Nf({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!Pf(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
1098
+ `]}};B([b({attribute:!1})],W.prototype,`sessions`,void 0),B([b({attribute:!1})],W.prototype,`statuses`,void 0),B([b({attribute:!1})],W.prototype,`activities`,void 0),B([b({attribute:!1})],W.prototype,`sending`,void 0),B([b({attribute:!1})],W.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],W.prototype,`selected`,void 0),B([b({type:Number})],W.prototype,`startingCount`,void 0),B([b({type:Boolean})],W.prototype,`canStart`,void 0),B([b({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),B([b({attribute:!1})],W.prototype,`onSelect`,void 0),B([b({attribute:!1})],W.prototype,`onStart`,void 0),B([b({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],W.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),B([b({attribute:!1})],W.prototype,`onArchive`,void 0),B([b({attribute:!1})],W.prototype,`onArchiveWithDescendants`,void 0),B([b({attribute:!1})],W.prototype,`onArchiveMany`,void 0),B([b({attribute:!1})],W.prototype,`onRestore`,void 0),B([b({attribute:!1})],W.prototype,`onDelete`,void 0),B([b({attribute:!1})],W.prototype,`onDeleteArchived`,void 0),B([b({attribute:!1})],W.prototype,`onDeleteArchivedMany`,void 0),B([b({attribute:!1})],W.prototype,`onDetachParent`,void 0),B([b({attribute:!1})],W.prototype,`parentLocation`,void 0),B([b({attribute:!1})],W.prototype,`onGoToParent`,void 0),B([b({attribute:!1})],W.prototype,`onMarkRead`,void 0),B([b({attribute:!1})],W.prototype,`onMarkReadMany`,void 0),B([b({attribute:!1})],W.prototype,`onReload`,void 0),B([b({attribute:!1})],W.prototype,`onCleanup`,void 0),B([x()],W.prototype,`openMenuSessionId`,void 0),B([x()],W.prototype,`menuStyle`,void 0),B([x()],W.prototype,`archivedExpanded`,void 0),B([x()],W.prototype,`selectionScopes`,void 0),B([x()],W.prototype,`selectedSessionIds`,void 0),W=B([y(`session-list`)],W);function S_(e,t){return e.filter(e=>O_(e,t)).length}function C_(e){if(!(e===void 0||e===0))return e===1?`1 child elsewhere`:`${String(e)} children elsewhere`}function w_(e){return e.archived===!0?`archived`:`current`}function T_(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function E_(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=z(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=z(e.path);if(r.has(i))return 0;let a=new Set(r);a.add(i);let o=0;for(let e of t.get(i)??[])a.has(z(e.path))||(e.archived!==!0&&(o+=1),o+=n(e,a));return o};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function D_(e,t,n,r){if(!(xs(e)||e.archived===!0)){if(r)return`sending`;if(xo(t,n))return`session`}}function O_(e,t){return xs(e)||e.archived===!0?!1:t.has(e.id)}function k_(e){return new Map(e.map(e=>[z(e.path),e]))}function A_(e){let t=k_(e),n=new Set;for(let r of e){if(r.archived===!0)continue;n.add(r.id);let e=r.parentSessionPath===void 0?void 0:z(r.parentSessionPath),i=new Set([z(r.path)]);for(;e!==void 0&&!i.has(e);){i.add(e);let r=t.get(e);if(r===void 0)break;n.add(r.id),e=r.parentSessionPath===void 0?void 0:z(r.parentSessionPath)}}return j_(e.filter(e=>n.has(e.id)))}function j_(e){let t=k_(e),n=new Map,r=[];for(let i of e){let e=i.parentSessionPath,a=e===void 0?void 0:t.get(z(e));if(a===void 0){r.push(i);continue}let o=z(a.path),s=n.get(o)??[];s.push(i),n.set(o,s)}let i=[],a=(e,r,o)=>{let s=z(e.path);if(o.has(s))return;let c=e.parentSessionPath;i.push({session:e,depth:r,hasMissingParent:c!==void 0&&!t.has(z(c))});let l=new Set(o);l.add(s);for(let e of n.get(s)??[])a(e,r+1,l)};for(let e of r)a(e,0,new Set);return i}var M_=class extends v{constructor(...e){super(...e),this.loading=!1,this.running=!1,this.error=``,this.draft={...Sf},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=Cf(this.draft),t=this.selectedPreview(),n=Tf({draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!Ef(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
1112
1099
  <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
1113
1100
  <section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1114
1101
  <header>
@@ -1120,37 +1107,37 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1120
1107
  </header>
1121
1108
  <div class="body">
1122
1109
  <p class="intro">Preview manual cleanup for this machine before archiving idle sessions or permanently deleting old archived sessions.</p>
1123
- ${this.canCleanup?this.renderForm(e.ok?``:e.error):this.renderUnavailable()}
1110
+ ${this.renderForm(e.ok?``:e.error)}
1124
1111
  ${this.renderMessage()}
1125
1112
  ${this.preview===void 0?null:this.renderPreview(this.preview)}
1126
1113
  ${this.result===void 0?null:this.renderResult(this.result)}
1127
1114
  </div>
1128
1115
  <footer>
1129
1116
  <button @click=${()=>{this.onClose?.()}}>${this.result===void 0?`Cancel`:`Close`}</button>
1130
- <button ?disabled=${!this.canCleanup||this.loading||this.running} @click=${()=>{this.previewCleanup()}}>${this.loading?`Previewing…`:`Preview`}</button>
1117
+ <button ?disabled=${this.loading||this.running} @click=${()=>{this.previewCleanup()}}>${this.loading?`Previewing…`:`Preview`}</button>
1131
1118
  <button class="danger" ?disabled=${!n} title=${r} @click=${()=>{this.runCleanup()}}>${this.running?`Running…`:`Run cleanup`}</button>
1132
1119
  </footer>
1133
1120
  </section>
1134
1121
  </div>
1135
- `}renderForm(e){let t=this.loading||this.running,n=jf(this.draft),r=this.preview!==void 0&&n.ok&&Mf(n.request)!==Mf(this.previewRequest)&&Pf(this.preview);return g`
1122
+ `}renderForm(e){let t=this.loading||this.running,n=Cf(this.draft),r=this.preview!==void 0&&n.ok&&wf(n.request)!==wf(this.previewRequest)&&Ef(this.preview);return g`
1136
1123
  <fieldset ?disabled=${t}>
1137
1124
  <label class="toggle-row">
1138
- <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:G_(e)})}}>
1125
+ <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:N_(e)})}}>
1139
1126
  <span>Archive non-archived sessions idle for more than</span>
1140
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:K_(e)})}}>
1127
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:P_(e)})}}>
1141
1128
  <span>days</span>
1142
1129
  </label>
1143
1130
  <label class="toggle-row delete-row">
1144
- <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:G_(e)})}}>
1131
+ <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:N_(e)})}}>
1145
1132
  <span>Delete archived sessions archived for more than</span>
1146
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:K_(e)})}}>
1133
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:P_(e)})}}>
1147
1134
  <span>days</span>
1148
1135
  </label>
1149
1136
  </fieldset>
1150
1137
  <p class="warning"><strong>Deletion is permanent.</strong> Cleanup only deletes sessions that are already archived.</p>
1151
1138
  ${e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}
1152
1139
  ${r?g`<div class="hint" role="status">Thresholds changed. Preview again before running cleanup.</div>`:null}
1153
- `}renderUnavailable(){return g`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){let e=this.formError||this.error;return e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){let t=this.selectedProjectCwdsForPreview(),n=new Set(t),r=If(e,t);return g`
1140
+ `}renderMessage(){let e=this.formError||this.error;return e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){let t=this.selectedProjectCwdsForPreview(),n=new Set(t),r=Of(e,t);return g`
1154
1141
  <section class="preview" aria-label="Cleanup preview">
1155
1142
  <h2>Preview</h2>
1156
1143
  ${e.projects.length===0?g`<p class="empty">No sessions match these thresholds.</p>`:g`
@@ -1180,7 +1167,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1180
1167
  ${t.length===0?g`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
1181
1168
  `}renderProjectRow(e,t){return g`
1182
1169
  <tr class=${t?``:`unselected`}>
1183
- <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,G_(t))}}></td>
1170
+ <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,N_(t))}}></td>
1184
1171
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
1185
1172
  <td>${e.archiveCount}</td>
1186
1173
  <td>${e.deleteCount}</td>
@@ -1190,7 +1177,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1190
1177
  <h2>Cleanup complete</h2>
1191
1178
  <p>Archived ${e.archivedSessionIds.length} ${e.archivedSessionIds.length===1?`session`:`sessions`}; permanently deleted ${e.deletedSessionIds.length} archived ${e.deletedSessionIds.length===1?`session`:`sessions`}.</p>
1192
1179
  </section>
1193
- `}updateDraft(e){this.draft={...this.draft,...e},this.formError=``}selectedPreview(){return this.preview===void 0?void 0:If(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:Ff(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=``}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=``}setProjectSelected(e,t){let n=this.preview;if(n===void 0)return;let r=new Set(this.selectedProjectCwdsForPreview());t?r.add(e):r.delete(e),this.selectedProjectCwds=n.projects.map(e=>e.cwd).filter(e=>r.has(e)),this.formError=``}previewCleanup(){let e=jf(this.draft);if(!e.ok){this.formError=e.error;return}this.formError=``,this.onPreview?.(e.request)}runCleanup(){let e=jf(this.draft);if(!e.ok){this.formError=e.error;return}let t=this.selectedPreview(),n=this.selectedProjectCwdsForPreview();if(!Nf({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!Pf(t)?`Select at least one project to run cleanup.`:`Preview cleanup before running it.`;return}t===void 0||!Lf(t,e=>confirm(e))||(this.formError=``,this.onRun?.({...e.request,projectCwds:n}))}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
1180
+ `}updateDraft(e){this.draft={...this.draft,...e},this.formError=``}selectedPreview(){return this.preview===void 0?void 0:Of(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:Df(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=``}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=``}setProjectSelected(e,t){let n=this.preview;if(n===void 0)return;let r=new Set(this.selectedProjectCwdsForPreview());t?r.add(e):r.delete(e),this.selectedProjectCwds=n.projects.map(e=>e.cwd).filter(e=>r.has(e)),this.formError=``}previewCleanup(){let e=Cf(this.draft);if(!e.ok){this.formError=e.error;return}this.formError=``,this.onPreview?.(e.request)}runCleanup(){let e=Cf(this.draft);if(!e.ok){this.formError=e.error;return}let t=this.selectedPreview(),n=this.selectedProjectCwdsForPreview();if(!Tf({draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!Ef(t)?`Select at least one project to run cleanup.`:`Preview cleanup before running it.`;return}t===void 0||!kf(t,e=>confirm(e))||(this.formError=``,this.onRun?.({...e.request,projectCwds:n}))}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
1194
1181
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1195
1182
  .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; }
1196
1183
  section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1207,9 +1194,8 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1207
1194
  input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--pi-accent); }
1208
1195
  input.days { box-sizing: border-box; width: 88px; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1209
1196
  input.days:disabled { opacity: .55; }
1210
- .warning, .unavailable, .dialog-error, .result { border: 1px solid var(--pi-border); border-radius: 10px; padding: 10px 12px; }
1197
+ .warning, .dialog-error, .result { border: 1px solid var(--pi-border); border-radius: 10px; padding: 10px 12px; }
1211
1198
  .warning { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-text); }
1212
- .unavailable { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
1213
1199
  .dialog-error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); }
1214
1200
  .result { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
1215
1201
  .preview { display: grid; gap: 10px; min-width: 0; }
@@ -1240,7 +1226,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1240
1226
  table { min-width: 560px; }
1241
1227
  thead th:first-child, td.select-cell { width: 58px; }
1242
1228
  }
1243
- `}};B([b({type:Boolean})],W_.prototype,`canCleanup`,void 0),B([b({type:String})],W_.prototype,`unavailableMessage`,void 0),B([b({attribute:!1})],W_.prototype,`preview`,void 0),B([b({attribute:!1})],W_.prototype,`previewRequest`,void 0),B([b({attribute:!1})],W_.prototype,`result`,void 0),B([b({type:Boolean})],W_.prototype,`loading`,void 0),B([b({type:Boolean})],W_.prototype,`running`,void 0),B([b({type:String})],W_.prototype,`error`,void 0),B([b({attribute:!1})],W_.prototype,`onPreview`,void 0),B([b({attribute:!1})],W_.prototype,`onRun`,void 0),B([b({attribute:!1})],W_.prototype,`onClose`,void 0),B([x()],W_.prototype,`draft`,void 0),B([x()],W_.prototype,`formError`,void 0),B([x()],W_.prototype,`selectedProjectCwds`,void 0),W_=B([y(`session-cleanup-dialog`)],W_);function G_(e){return e.target instanceof HTMLInputElement&&e.target.checked}function K_(e){return e.target instanceof HTMLInputElement?e.target.value:``}function q_(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=$_(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:ev(d,r),activeLeafId:d}}function J_(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function Y_(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function X_(e,t,n){let r=J_(e,t.foldedIds).map(e=>e.node.id),i=tv(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function Z_(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function Q_(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:`Custom summary focus must be ${String(At)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function $_(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function ev(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function tv(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var nv={nodes:[],activeLeafId:null,activePathIds:[]},rv=8,iv=class extends v{constructor(...e){super(...e),this.tree=nv,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=q_(nv),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
1229
+ `}};B([b({attribute:!1})],M_.prototype,`preview`,void 0),B([b({attribute:!1})],M_.prototype,`previewRequest`,void 0),B([b({attribute:!1})],M_.prototype,`result`,void 0),B([b({type:Boolean})],M_.prototype,`loading`,void 0),B([b({type:Boolean})],M_.prototype,`running`,void 0),B([b({type:String})],M_.prototype,`error`,void 0),B([b({attribute:!1})],M_.prototype,`onPreview`,void 0),B([b({attribute:!1})],M_.prototype,`onRun`,void 0),B([b({attribute:!1})],M_.prototype,`onClose`,void 0),B([x()],M_.prototype,`draft`,void 0),B([x()],M_.prototype,`formError`,void 0),B([x()],M_.prototype,`selectedProjectCwds`,void 0),M_=B([y(`session-cleanup-dialog`)],M_);function N_(e){return e.target instanceof HTMLInputElement&&e.target.checked}function P_(e){return e.target instanceof HTMLInputElement?e.target.value:``}function F_(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=V_(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:H_(d,r),activeLeafId:d}}function I_(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function L_(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function R_(e,t,n){let r=I_(e,t.foldedIds).map(e=>e.node.id),i=U_(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function z_(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function B_(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:`Custom summary focus must be ${String(jt)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function V_(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function H_(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function U_(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var W_={nodes:[],activeLeafId:null,activePathIds:[]},G_=8,K_=class extends v{constructor(...e){super(...e),this.tree=W_,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=F_(W_),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
1244
1230
  <div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
1245
1231
  <section
1246
1232
  role="dialog"
@@ -1262,7 +1248,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1262
1248
  ${this.renderFooter()}
1263
1249
  </section>
1264
1250
  </div>
1265
- `}renderTreeStep(){let e=J_(this.model,this.foldedIds);return g`
1251
+ `}renderTreeStep(){let e=I_(this.model,this.foldedIds);return g`
1266
1252
  <div class="body tree-step">
1267
1253
  <div class="tree-intro">
1268
1254
  <p>Select where conversation context should continue. All retained branches stay in this session file.</p>
@@ -1281,7 +1267,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1281
1267
  </div>
1282
1268
  `}
1283
1269
  </div>
1284
- `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,cv(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=av(e.branchDepth);return g`
1270
+ `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,X_(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=q_(e.branchDepth);return g`
1285
1271
  <div
1286
1272
  class=${r}
1287
1273
  style=${`--tree-indent: ${String(i*16)}px; --tree-indent-mobile: ${String(i*12)}px;`}
@@ -1302,7 +1288,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1302
1288
  @click=${t=>{this.toggleNode(e.node.id,t)}}
1303
1289
  >${e.childIds.length===0?`·`:n?`▾`:`▸`}</span>
1304
1290
  <span class="metadata">
1305
- <span class="kind">${sv(e.node.kind)}</span>
1291
+ <span class="kind">${Y_(e.node.kind)}</span>
1306
1292
  <span class="badges">
1307
1293
  ${e.activePath&&!e.activeLeaf?g`<span class="badge path">Active path</span>`:null}
1308
1294
  ${e.activeLeaf?g`<span class="badge leaf">Active leaf</span>`:null}
@@ -1314,7 +1300,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1314
1300
  ${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
1315
1301
  </span>
1316
1302
  </div>
1317
- `}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=Q_(this.summaryMode,this.customInstructions);return g`
1303
+ `}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=B_(this.summaryMode,this.customInstructions);return g`
1318
1304
  <div class="body confirmation-step">
1319
1305
  <div class="confirmation-card">
1320
1306
  <div>
@@ -1323,9 +1309,9 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1323
1309
  </div>
1324
1310
  ${e===void 0?g`<div class="empty">The selected history entry is no longer available.</div>`:g`
1325
1311
  <div class="selected-entry">
1326
- <span class="kind">${sv(e.kind)}</span>
1312
+ <span class="kind">${Y_(e.kind)}</span>
1327
1313
  <strong dir="auto">${e.summary}</strong>
1328
- ${ov(e.kind)?g`<p>This message’s text will return to the prompt editor for optional editing and resubmission.</p>`:g`<p>The prompt editor will be empty after navigating to this entry.</p>`}
1314
+ ${J_(e.kind)?g`<p>This message’s text will return to the prompt editor for optional editing and resubmission.</p>`:g`<p>The prompt editor will be empty after navigating to this entry.</p>`}
1329
1315
  </div>
1330
1316
  `}
1331
1317
  <fieldset ?disabled=${this.busy}>
@@ -1339,11 +1325,11 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1339
1325
  <textarea
1340
1326
  id="session-tree-custom-focus"
1341
1327
  rows="5"
1342
- maxlength=${String(At)}
1328
+ maxlength=${String(jt)}
1343
1329
  .value=${this.customInstructions}
1344
1330
  @input=${e=>{this.handleCustomInstructionsInput(e)}}
1345
1331
  ></textarea>
1346
- <span class="character-count">${this.customInstructions.length} / ${At}</span>
1332
+ <span class="character-count">${this.customInstructions.length} / ${jt}</span>
1347
1333
  </label>
1348
1334
  ${t.ok?null:g`<div class="validation-error" role="alert">${t.error}</div>`}
1349
1335
  `:null}
@@ -1382,7 +1368,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1382
1368
  ${this.busy?e?`Summarizing…`:`Navigating…`:e?`Summarize and navigate`:`Navigate`}
1383
1369
  </button>
1384
1370
  </footer>
1385
- `}resetTree(){this.operationGeneration+=1,this.model=q_(this.tree),this.selectedId=Y_(this.model),this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=Z_(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){let t=X_(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`cancel`){this.onCancel?.();return}if(t.action===`confirm`){this.continueToConfirmation();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToConfirmation(){this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(Q_(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`confirm`,this.error=``,this.statusMessage=``,this.pendingFocus=`summary`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=Q_(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`Session tree navigation is unavailable. Close and reopen /tree, then try again.`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`Summarization cancelled. Your selected history entry is unchanged.`:`Navigation cancelled. Your selected history entry is unchanged.`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`Could not navigate session history: ${lv(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`Summarization cannot be cancelled from this client.`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`Cancelling summarization…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`Could not cancel summarization: ${lv(e)}`}}handleBackdropMouseDown(e){e.target===e.currentTarget&&!this.busy&&this.onCancel?.()}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.summaryMode!==`none`&&this.abortNavigation();return}this.step===`confirm`?this.returnToTree():this.onCancel?.()}}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=this.shadowRoot?.activeElement,r=t.findIndex(e=>e===n),i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r<=0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
1371
+ `}resetTree(){this.operationGeneration+=1,this.model=F_(this.tree),this.selectedId=L_(this.model),this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=z_(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){let t=R_(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`cancel`){this.onCancel?.();return}if(t.action===`confirm`){this.continueToConfirmation();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToConfirmation(){this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(B_(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`confirm`,this.error=``,this.statusMessage=``,this.pendingFocus=`summary`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=B_(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`Session tree navigation is unavailable. Close and reopen /tree, then try again.`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`Summarization cancelled. Your selected history entry is unchanged.`:`Navigation cancelled. Your selected history entry is unchanged.`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`Could not navigate session history: ${Z_(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`Summarization cannot be cancelled from this client.`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`Cancelling summarization…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`Could not cancel summarization: ${Z_(e)}`}}handleBackdropMouseDown(e){e.target===e.currentTarget&&!this.busy&&this.onCancel?.()}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.summaryMode!==`none`&&this.abortNavigation();return}this.step===`confirm`?this.returnToTree():this.onCancel?.()}}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=this.shadowRoot?.activeElement,r=t.findIndex(e=>e===n),i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r<=0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
1386
1372
  :host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1387
1373
  * { box-sizing: border-box; }
1388
1374
  .backdrop { width: 100%; height: 100dvh; background: var(--pi-overlay); overflow: hidden; }
@@ -1475,7 +1461,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1475
1461
  .custom-focus, .validation-error { margin-inline-start: 0; }
1476
1462
  footer { flex-wrap: wrap; }
1477
1463
  }
1478
- `}};B([b({attribute:!1})],iv.prototype,`tree`,void 0),B([b({attribute:!1})],iv.prototype,`onNavigate`,void 0),B([b({attribute:!1})],iv.prototype,`onAbort`,void 0),B([b({attribute:!1})],iv.prototype,`onCancel`,void 0),B([x()],iv.prototype,`selectedId`,void 0),B([x()],iv.prototype,`foldedIds`,void 0),B([x()],iv.prototype,`step`,void 0),B([x()],iv.prototype,`summaryMode`,void 0),B([x()],iv.prototype,`customInstructions`,void 0),B([x()],iv.prototype,`busy`,void 0),B([x()],iv.prototype,`aborting`,void 0),B([x()],iv.prototype,`error`,void 0),B([x()],iv.prototype,`statusMessage`,void 0),iv=B([y(`session-tree-navigator`)],iv);function av(e){return Math.min(Math.max(0,e),rv)}function ov(e){return e===`user`||e===`custom-message`}function sv(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function cv(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function lv(e){return e instanceof Error?e.message:String(e)}var uv={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},dv=e=>(...t)=>({_$litDirective$:e,values:t}),fv=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:pv}=lt,mv=e=>e,hv=()=>document.createComment(``),gv=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new pv(r.insertBefore(hv(),i),r.insertBefore(hv(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=mv(e).nextSibling;mv(r).insertBefore(e,i),e=t}}}return n},_v=(e,t,n=e)=>(e._$AI(t,n),e),vv={},yv=(e,t=vv)=>e._$AH=t,bv=e=>e._$AH,xv=e=>{e._$AR(),e._$AA.remove()},Sv=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},Cv=dv(class extends fv{constructor(e){if(super(e),e.type!==uv.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=bv(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,p=0,m=a.length-1;for(;d<=f&&p<=m;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[p])c[p]=_v(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=_v(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=_v(i[d],a[m]),gv(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=_v(i[f],a[p]),gv(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=Sv(o,p,m),u=Sv(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[p]),n=t===void 0?null:i[t];if(n===null){let t=gv(e,i[d]);_v(t,a[p]),c[p]=t}else c[p]=_v(n,a[p]),gv(e,i[d],n),i[t]=null;p++}else xv(i[f]),f--;else xv(i[d]),d++;for(;p<=m;){let t=gv(e,c[m+1]);_v(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&xv(e)}return this.ut=o,yv(e,c),Ye}}),wv=`pi-web:chat-groups:`,Tv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Dv(e));return t===null||t===``?void 0:Ov(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Dv(e),JSON.stringify(t))}catch{}}},Ev=class{constructor(e=Tv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Av(i,this.openGroupKeys)&&Av(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Dv(e){return`${wv}${e}`}function Ov(e){if(Array.isArray(e))return{open:kv(e),closedDefaultOpen:[]};if(jv(e))return{open:Array.isArray(e.open)?kv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?kv(e.closedDefaultOpen):[]}}function kv(e){return e.filter(e=>typeof e==`string`)}function Av(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function jv(e){return typeof e==`object`&&!!e}function Mv(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>Iv(e,t)),s=e.parts.filter(t=>!Iv(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...l};if(Pv(t)){let e=Fv(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function Nv(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function Pv(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Fv(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Iv(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function Lv(e,t){let n=zv(Hv(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Rv(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Bv(r,t.markerOffset);return}e.scrollTop=Vv(e.scrollHeight,t.distanceFromBottom)}function zv(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function Bv(e,t){return e-t}function Vv(e,t){return Math.max(0,e-t)}function Hv(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var Uv=600,Wv=1;function Gv(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Kv(e)||qv(e)}function Kv(e){return e.scrollTop<(e.topThreshold??Math.max(Uv,e.clientHeight))}function qv(e){return e.scrollHeight<=e.clientHeight+Wv}var Jv=`pi-web:chat-scroll:`,Yv=180,Xv=48,Zv=2,Qv={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)}},$v={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},ey=class{constructor(e=Qv,t=$v){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=Yv){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Zv){if(e===``||t===void 0||!ry(t))return`skipped`;try{if(ay(t,r))return this.storage.setItem(ty(e),JSON.stringify({mode:`bottom`})),`saved`;let i=sy(t,n);if(i===void 0)return`skipped`;let a=oy(t,i);return this.storage.setItem(ty(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!ry(t))return{status:`skipped`};let i=ly(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(ty(e));if(t===null||t===``)return;let n=JSON.parse(t);return ny(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!ry(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function ty(e){return`${Jv}${e}`}function ny(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function ry(e){return e.clientHeight>0&&e.scrollHeight>0}function iy(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ay(e,t=Xv){return iy(e)<t}function oy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:uy(t)??``,offset:t.getBoundingClientRect().top-n}}function sy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(uy(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function cy(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function ly(e,t){return e.find(e=>uy(e)===t)}function uy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var dy=e=>e??_,fy=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.renderOpenAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=Ec(e.questions,this.answers),n=Dc(e.questions,this.answers);return g`
1464
+ `}};B([b({attribute:!1})],K_.prototype,`tree`,void 0),B([b({attribute:!1})],K_.prototype,`onNavigate`,void 0),B([b({attribute:!1})],K_.prototype,`onAbort`,void 0),B([b({attribute:!1})],K_.prototype,`onCancel`,void 0),B([x()],K_.prototype,`selectedId`,void 0),B([x()],K_.prototype,`foldedIds`,void 0),B([x()],K_.prototype,`step`,void 0),B([x()],K_.prototype,`summaryMode`,void 0),B([x()],K_.prototype,`customInstructions`,void 0),B([x()],K_.prototype,`busy`,void 0),B([x()],K_.prototype,`aborting`,void 0),B([x()],K_.prototype,`error`,void 0),B([x()],K_.prototype,`statusMessage`,void 0),K_=B([y(`session-tree-navigator`)],K_);function q_(e){return Math.min(Math.max(0,e),G_)}function J_(e){return e===`user`||e===`custom-message`}function Y_(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function X_(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function Z_(e){return e instanceof Error?e.message:String(e)}var Q_={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},$_=e=>(...t)=>({_$litDirective$:e,values:t}),ev=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:tv}=lt,nv=e=>e,rv=()=>document.createComment(``),iv=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new tv(r.insertBefore(rv(),i),r.insertBefore(rv(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=nv(e).nextSibling;nv(r).insertBefore(e,i),e=t}}}return n},av=(e,t,n=e)=>(e._$AI(t,n),e),ov={},sv=(e,t=ov)=>e._$AH=t,cv=e=>e._$AH,lv=e=>{e._$AR(),e._$AA.remove()},uv=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},dv=$_(class extends ev{constructor(e){if(super(e),e.type!==Q_.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=cv(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,p=0,m=a.length-1;for(;d<=f&&p<=m;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[p])c[p]=av(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=av(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=av(i[d],a[m]),iv(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=av(i[f],a[p]),iv(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=uv(o,p,m),u=uv(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[p]),n=t===void 0?null:i[t];if(n===null){let t=iv(e,i[d]);av(t,a[p]),c[p]=t}else c[p]=av(n,a[p]),iv(e,i[d],n),i[t]=null;p++}else lv(i[f]),f--;else lv(i[d]),d++;for(;p<=m;){let t=iv(e,c[m+1]);av(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&lv(e)}return this.ut=o,sv(e,c),Ye}}),fv=`pi-web:chat-groups:`,pv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(hv(e));return t===null||t===``?void 0:gv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(hv(e),JSON.stringify(t))}catch{}}},mv=class{constructor(e=pv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&vv(i,this.openGroupKeys)&&vv(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function hv(e){return`${fv}${e}`}function gv(e){if(Array.isArray(e))return{open:_v(e),closedDefaultOpen:[]};if(yv(e))return{open:Array.isArray(e.open)?_v(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?_v(e.closedDefaultOpen):[]}}function _v(e){return e.filter(e=>typeof e==`string`)}function vv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function yv(e){return typeof e==`object`&&!!e}function bv(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>wv(e,t)),s=e.parts.filter(t=>!wv(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...l};if(Sv(t)){let e=Cv(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function xv(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function Sv(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Cv(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function wv(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function Tv(e,t){let n=Dv(Av(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Ev(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ov(r,t.markerOffset);return}e.scrollTop=kv(e.scrollHeight,t.distanceFromBottom)}function Dv(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function Ov(e,t){return e-t}function kv(e,t){return Math.max(0,e-t)}function Av(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var jv=600,Mv=1;function Nv(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Pv(e)||Fv(e)}function Pv(e){return e.scrollTop<(e.topThreshold??Math.max(jv,e.clientHeight))}function Fv(e){return e.scrollHeight<=e.clientHeight+Mv}var Iv=`pi-web:chat-scroll:`,Lv=180,Rv=48,zv=2,Bv={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)}},Vv={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},Hv=class{constructor(e=Bv,t=Vv){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=Lv){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=zv){if(e===``||t===void 0||!Gv(t))return`skipped`;try{if(qv(t,r))return this.storage.setItem(Uv(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Yv(t,n);if(i===void 0)return`skipped`;let a=Jv(t,i);return this.storage.setItem(Uv(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!Gv(t))return{status:`skipped`};let i=Zv(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(Uv(e));if(t===null||t===``)return;let n=JSON.parse(t);return Wv(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!Gv(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Uv(e){return`${Iv}${e}`}function Wv(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function Gv(e){return e.clientHeight>0&&e.scrollHeight>0}function Kv(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function qv(e,t=Rv){return Kv(e)<t}function Jv(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:Qv(t)??``,offset:t.getBoundingClientRect().top-n}}function Yv(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(Qv(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function Xv(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Zv(e,t){return e.find(e=>Qv(e)===t)}function Qv(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var $v=e=>e??_,ey=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.renderOpenAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=Ec(e.questions,this.answers),n=Dc(e.questions,this.answers);return g`
1479
1465
  <article class="card open-card" aria-labelledby="ask-user-heading">
1480
1466
  <header class="card-header">
1481
1467
  <h2 id="ask-user-heading">Questions</h2>
@@ -1500,7 +1486,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1500
1486
  <fieldset
1501
1487
  id=${this.questionFieldsetId(n)}
1502
1488
  class=${`question${i?` answered`:``}`}
1503
- aria-describedby=${dy(a)}
1489
+ aria-describedby=${$v(a)}
1504
1490
  tabindex="-1"
1505
1491
  >
1506
1492
  <legend>
@@ -1542,7 +1528,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1542
1528
  <textarea
1543
1529
  id=${this.otherInputId(n)}
1544
1530
  rows="3"
1545
- maxlength=${String(Dt)}
1531
+ maxlength=${String(Ot)}
1546
1532
  .value=${r?.otherText??``}
1547
1533
  @input=${e=>{this.changeOtherText(t,e)}}
1548
1534
  ></textarea>
@@ -1595,7 +1581,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1595
1581
  ${r.fromDraft?g`<p class="draft-note">Draft answer · not sent</p>`:null}
1596
1582
  `}
1597
1583
  </section>
1598
- `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Dt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Sc(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){if(e.preventDefault(),!this.submitting){if(Dc(t.questions,this.answers).length>0){this.showPartialSubmitConfirmation();return}this.submitAnswers(t)}}submitAnswers(e){if(this.submitting)return;this.submitting=!0;let t=this.onSubmit;if(t===void 0){this.submitting=!1;return}let n=e.askId;Promise.resolve().then(()=>t(n,Oc(e.questions,this.answers))).catch(()=>{}).finally(()=>{this.ask?.askId===n&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e.reason!==`superseded`)return;let n=Oc([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`open:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:xc(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=h`
1584
+ `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Ot)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Sc(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){if(e.preventDefault(),!this.submitting){if(Dc(t.questions,this.answers).length>0){this.showPartialSubmitConfirmation();return}this.submitAnswers(t)}}submitAnswers(e){if(this.submitting)return;this.submitting=!0;let t=this.onSubmit;if(t===void 0){this.submitting=!1;return}let n=e.askId;Promise.resolve().then(()=>t(n,Oc(e.questions,this.answers))).catch(()=>{}).finally(()=>{this.ask?.askId===n&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e.reason!==`superseded`)return;let n=Oc([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`open:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:xc(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=h`
1599
1585
  :host {
1600
1586
  display: block;
1601
1587
  box-sizing: border-box;
@@ -1750,7 +1736,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1750
1736
  .confirmation-actions { justify-content: flex-end; }
1751
1737
  .primary-action { min-height: 42px; }
1752
1738
  }
1753
- `}};B([b({attribute:!1})],fy.prototype,`ask`,void 0),B([b({attribute:!1})],fy.prototype,`outcome`,void 0),B([b({attribute:!1})],fy.prototype,`draftSessionId`,void 0),B([b({attribute:!1})],fy.prototype,`onSubmit`,void 0),B([x()],fy.prototype,`answers`,void 0),B([x()],fy.prototype,`confirmingPartialSubmit`,void 0),B([x()],fy.prototype,`submitting`,void 0),fy=B([y(`ask-user-card`)],fy);var py=1e3;function my(e){switch(e){case`answered`:return`Answered`;case`cancelled`:return`Cancelled`;case`timeout`:return`Timed out`;case`aborted`:return`Aborted`;case`session-ended`:return`Session ended`}}function hy(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`Closed without an answer.`:typeof t==`boolean`?`Answered: ${t?`Yes`:`No`}`:t===``?`Answered with an empty response.`:`Answered: ${t}`}case`cancelled`:return`Dismissed without an answer.`;case`timeout`:return`No answer was given before the dialog timed out.`;case`aborted`:return`The run ended before this dialog was answered.`;case`session-ended`:return`The session ended before this dialog was answered.`}}function gy(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`Auto-cancel imminent`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`Auto-cancels in ${String(e)}h ${String(t)}m`}if(i>=60){let e=Math.floor(i/60);return`Auto-cancels in ${String(e)}m ${String(i%60)}s`}return`Auto-cancels in ${String(i)}s`}var _y=class extends v{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=gy(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return g`
1739
+ `}};B([b({attribute:!1})],ey.prototype,`ask`,void 0),B([b({attribute:!1})],ey.prototype,`outcome`,void 0),B([b({attribute:!1})],ey.prototype,`draftSessionId`,void 0),B([b({attribute:!1})],ey.prototype,`onSubmit`,void 0),B([x()],ey.prototype,`answers`,void 0),B([x()],ey.prototype,`confirmingPartialSubmit`,void 0),B([x()],ey.prototype,`submitting`,void 0),ey=B([y(`ask-user-card`)],ey);var ty=1e3;function ny(e){switch(e){case`answered`:return`Answered`;case`cancelled`:return`Cancelled`;case`timeout`:return`Timed out`;case`aborted`:return`Aborted`;case`session-ended`:return`Session ended`}}function ry(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`Closed without an answer.`:typeof t==`boolean`?`Answered: ${t?`Yes`:`No`}`:t===``?`Answered with an empty response.`:`Answered: ${t}`}case`cancelled`:return`Dismissed without an answer.`;case`timeout`:return`No answer was given before the dialog timed out.`;case`aborted`:return`The run ended before this dialog was answered.`;case`session-ended`:return`The session ended before this dialog was answered.`}}function iy(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`Auto-cancel imminent`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`Auto-cancels in ${String(e)}h ${String(t)}m`}if(i>=60){let e=Math.floor(i/60);return`Auto-cancels in ${String(e)}m ${String(i%60)}s`}return`Auto-cancels in ${String(i)}s`}var ay=class extends v{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=iy(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return g`
1754
1740
  <article class="card open-card" aria-labelledby="extension-dialog-heading">
1755
1741
  <header class="card-header">
1756
1742
  <h2 id="extension-dialog-heading">${e.title}</h2>
@@ -1781,8 +1767,8 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1781
1767
  type="text"
1782
1768
  name="dialog-answer"
1783
1769
  aria-label="Your answer"
1784
- placeholder=${dy(e.placeholder)}
1785
- maxlength=${String(kt)}
1770
+ placeholder=${$v(e.placeholder)}
1771
+ maxlength=${String(At)}
1786
1772
  .value=${this.inputValue}
1787
1773
  ?disabled=${this.closing}
1788
1774
  @input=${e=>{this.changeInput(e)}}
@@ -1796,14 +1782,14 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1796
1782
  <article class="card closed-card" aria-labelledby="extension-dialog-closed-heading">
1797
1783
  <header class="card-header">
1798
1784
  <h2 id="extension-dialog-closed-heading">${e.dialog.title}</h2>
1799
- <span class=${`header-status ${e.reason}`}>${my(e.reason)}</span>
1785
+ <span class=${`header-status ${e.reason}`}>${ny(e.reason)}</span>
1800
1786
  </header>
1801
- <p class="closed-summary">${hy(e)}</p>
1787
+ <p class="closed-summary">${ry(e)}</p>
1802
1788
  <footer class="dialog-footer">
1803
1789
  <button class="secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>Dismiss</button>
1804
1790
  </footer>
1805
1791
  </article>
1806
- `}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},py);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
1792
+ `}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},ty);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
1807
1793
  :host {
1808
1794
  display: block;
1809
1795
  box-sizing: border-box;
@@ -1908,7 +1894,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1908
1894
  @container (max-width: 580px) {
1909
1895
  .primary-action { min-height: 42px; }
1910
1896
  }
1911
- `}};B([b({attribute:!1})],_y.prototype,`dialog`,void 0),B([b({attribute:!1})],_y.prototype,`outcome`,void 0),B([b({attribute:!1})],_y.prototype,`onAnswer`,void 0),B([b({attribute:!1})],_y.prototype,`onCancel`,void 0),B([b({attribute:!1})],_y.prototype,`onDismiss`,void 0),B([x()],_y.prototype,`inputValue`,void 0),B([x()],_y.prototype,`closing`,void 0),B([x()],_y.prototype,`countdownNow`,void 0),_y=B([y(`extension-dialog-card`)],_y);var vy=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=yy(this.positionPercent),t=yy(this.loadedPercent),n=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return g`
1897
+ `}};B([b({attribute:!1})],ay.prototype,`dialog`,void 0),B([b({attribute:!1})],ay.prototype,`outcome`,void 0),B([b({attribute:!1})],ay.prototype,`onAnswer`,void 0),B([b({attribute:!1})],ay.prototype,`onCancel`,void 0),B([b({attribute:!1})],ay.prototype,`onDismiss`,void 0),B([x()],ay.prototype,`inputValue`,void 0),B([x()],ay.prototype,`closing`,void 0),B([x()],ay.prototype,`countdownNow`,void 0),ay=B([y(`extension-dialog-card`)],ay);var oy=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=sy(this.positionPercent),t=sy(this.loadedPercent),n=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return g`
1912
1898
  <div
1913
1899
  class="meter"
1914
1900
  style=${`--position:${e.toFixed(2)}%;`}
@@ -1931,14 +1917,14 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1931
1917
  .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); }
1932
1918
  .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)); }
1933
1919
  .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%); }
1934
- `}};B([b({type:Number})],vy.prototype,`positionPercent`,void 0),B([b({type:Number})],vy.prototype,`loadedPercent`,void 0),vy=B([y(`conversation-meter`)],vy);function yy(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var by=class extends fv{constructor(e){if(super(e),this.it=_,e.type!==uv.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===_||e==null)return this._t=void 0,this.it=e;if(e===Ye)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};by.directiveName=`unsafeHTML`,by.resultType=1;var xy=dv(by);function Sy(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Cy=Sy();function wy(e){Cy=e}var Ty={exec:()=>null};function Ey(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function G(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Oy.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Dy=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Oy={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=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Ey(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Ey(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Ey(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Ey(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Ey(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Ey(e=>RegExp(`^ {0,${e}}>`))},ky=/^(?:[ \t]*(?:\n|$))+/,Ay=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jy=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,My=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ny=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Py=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Fy=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Iy=G(Fy).replace(/bull/g,Py).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(),Ly=G(Fy).replace(/bull/g,Py).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(),Ry=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,zy=/^[^\n]+/,By=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Vy=G(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,By).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Hy=G(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Py).getRegex(),Uy=`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`,Wy=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Gy=G(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\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`,Wy).replace(`tag`,Uy).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ky=e=>G(Ry).replace(`hr`,My).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`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Uy).getRegex(),qy=Ky(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Jy=Ky(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Yy={blockquote:G(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Jy).getRegex(),code:Ay,def:Vy,fences:jy,heading:Ny,hr:My,html:Gy,lheading:Iy,list:Hy,newline:ky,paragraph:qy,table:Ty,text:zy},Xy=G(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,My).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`,Uy).getRegex(),Zy={...Yy,lheading:Ly,table:Xy,paragraph:G(Ry).replace(`hr`,My).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Xy).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Uy).getRegex()},Qy={...Yy,html:G(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Wy).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:Ty,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:G(Ry).replace(`hr`,My).replace(`heading`,` *#{1,6} *[^
1935
- ]`).replace(`lheading`,Iy).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},$y=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,eb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,tb=/^( {2,}|\\)\n(?!\s*$)/,nb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,rb=/[\p{P}\p{S}]/u,ib=/[\s\p{P}\p{S}]/u,ab=/[^\s\p{P}\p{S}]/u,ob=G(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,ib).getRegex(),sb=/(?!~)[\p{P}\p{S}]/u,cb=/(?!~)[\s\p{P}\p{S}]/u,lb=/(?:[^\s\p{P}\p{S}]|~)/u,ub=G(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Dy?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),db=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,fb=G(db,`u`).replace(/punct/g,rb).getRegex(),pb=G(db,`u`).replace(/punct/g,sb).getRegex(),mb=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,hb=G(mb,`gu`).replace(/notPunctSpace/g,ab).replace(/punctSpace/g,ib).replace(/punct/g,rb).getRegex(),gb=G(mb,`gu`).replace(/notPunctSpace/g,lb).replace(/punctSpace/g,cb).replace(/punct/g,sb).getRegex(),_b=G(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,ab).replace(/punctSpace/g,ib).replace(/punct/g,rb).getRegex(),vb=G(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,rb).getRegex(),yb=G(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,ab).replace(/punctSpace/g,ib).replace(/punct/g,rb).getRegex(),bb=G(/\\(punct)/,`gu`).replace(/punct/g,rb).getRegex(),xb=G(/^<(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(),Sb=G(Wy).replace(`(?:-->|$)`,`-->`).getRegex(),Cb=G(`^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`,Sb).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),wb=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Tb=G(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,wb).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Eb=G(/^!?\[(label)\]\[(ref)\]/).replace(`label`,wb).replace(`ref`,By).getRegex(),Db=G(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,By).getRegex(),Ob=G(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Eb).replace(`nolink`,Db).getRegex(),kb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ab={_backpedal:Ty,anyPunctuation:bb,autolink:xb,blockSkip:ub,br:tb,code:eb,del:Ty,delLDelim:Ty,delRDelim:Ty,emStrongLDelim:fb,emStrongRDelimAst:hb,emStrongRDelimUnd:_b,escape:$y,link:Tb,nolink:Db,punctuation:ob,reflink:Eb,reflinkSearch:Ob,tag:Cb,text:nb,url:Ty},jb={...Ab,link:G(/^!?\[(label)\]\((.*?)\)/).replace(`label`,wb).getRegex(),reflink:G(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,wb).getRegex()},Mb={...Ab,emStrongRDelimAst:gb,emStrongLDelim:pb,delLDelim:vb,delRDelim:yb,url:G(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,kb).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:G(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,kb).getRegex()},Nb={...Mb,br:G(tb).replace(`{2,}`,`*`).getRegex(),text:G(Mb.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},Pb={normal:Yy,gfm:Zy,pedantic:Qy},Fb={normal:Ab,gfm:Mb,breaks:Nb,pedantic:jb},Ib={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},Lb=e=>Ib[e];function Rb(e,t){if(t){if(Oy.escapeTest.test(e))return e.replace(Oy.escapeReplace,Lb)}else if(Oy.escapeTestNoEncode.test(e))return e.replace(Oy.escapeReplaceNoEncode,Lb);return e}function zb(e){try{e=encodeURI(e).replace(Oy.percentDecode,`%`)}catch{return null}return e}function Bb(e,t){let n=e.replace(Oy.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Oy.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Oy.slashPipe,`|`);return n}function Vb(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Hb(e){let t=e.split(`
1936
- `),n=t.length-1;for(;n>=0&&Oy.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
1937
- `)}function Ub(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Wb(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Gb(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Kb(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
1920
+ `}};B([b({type:Number})],oy.prototype,`positionPercent`,void 0),B([b({type:Number})],oy.prototype,`loadedPercent`,void 0),oy=B([y(`conversation-meter`)],oy);function sy(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var cy=class extends ev{constructor(e){if(super(e),this.it=_,e.type!==Q_.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===_||e==null)return this._t=void 0,this.it=e;if(e===Ye)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};cy.directiveName=`unsafeHTML`,cy.resultType=1;var ly=$_(cy);function uy(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var dy=uy();function fy(e){dy=e}var py={exec:()=>null};function my(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function G(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(K.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var hy=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),K={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=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:my(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:my(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:my(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:my(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:my(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:my(e=>RegExp(`^ {0,${e}}>`))},gy=/^(?:[ \t]*(?:\n|$))+/,_y=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,vy=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,yy=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,by=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,xy=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Sy=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Cy=G(Sy).replace(/bull/g,xy).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(),wy=G(Sy).replace(/bull/g,xy).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(),Ty=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ey=/^[^\n]+/,Dy=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Oy=G(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Dy).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ky=G(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,xy).getRegex(),Ay=`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`,jy=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,My=G(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\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`,jy).replace(`tag`,Ay).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ny=e=>G(Ty).replace(`hr`,yy).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`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Ay).getRegex(),Py=Ny(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Fy=Ny(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Iy={blockquote:G(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Fy).getRegex(),code:_y,def:Oy,fences:vy,heading:by,hr:yy,html:My,lheading:Cy,list:ky,newline:gy,paragraph:Py,table:py,text:Ey},Ly=G(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,yy).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`,Ay).getRegex(),Ry={...Iy,lheading:wy,table:Ly,paragraph:G(Ty).replace(`hr`,yy).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ly).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Ay).getRegex()},zy={...Iy,html:G(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,jy).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:py,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:G(Ty).replace(`hr`,yy).replace(`heading`,` *#{1,6} *[^
1921
+ ]`).replace(`lheading`,Cy).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},By=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Vy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Hy=/^( {2,}|\\)\n(?!\s*$)/,Uy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Wy=/[\p{P}\p{S}]/u,Gy=/[\s\p{P}\p{S}]/u,Ky=/[^\s\p{P}\p{S}]/u,qy=G(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Gy).getRegex(),Jy=/(?!~)[\p{P}\p{S}]/u,Yy=/(?!~)[\s\p{P}\p{S}]/u,Xy=/(?:[^\s\p{P}\p{S}]|~)/u,Zy=G(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,hy?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Qy=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,$y=G(Qy,`u`).replace(/punct/g,Wy).getRegex(),eb=G(Qy,`u`).replace(/punct/g,Jy).getRegex(),tb=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,nb=G(tb,`gu`).replace(/notPunctSpace/g,Ky).replace(/punctSpace/g,Gy).replace(/punct/g,Wy).getRegex(),rb=G(tb,`gu`).replace(/notPunctSpace/g,Xy).replace(/punctSpace/g,Yy).replace(/punct/g,Jy).getRegex(),ib=G(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Ky).replace(/punctSpace/g,Gy).replace(/punct/g,Wy).getRegex(),ab=G(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Wy).getRegex(),ob=G(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Ky).replace(/punctSpace/g,Gy).replace(/punct/g,Wy).getRegex(),sb=G(/\\(punct)/,`gu`).replace(/punct/g,Wy).getRegex(),cb=G(/^<(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(),lb=G(jy).replace(`(?:-->|$)`,`-->`).getRegex(),ub=G(`^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`,lb).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),db=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,fb=G(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,db).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),pb=G(/^!?\[(label)\]\[(ref)\]/).replace(`label`,db).replace(`ref`,Dy).getRegex(),mb=G(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Dy).getRegex(),hb=G(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,pb).replace(`nolink`,mb).getRegex(),gb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,_b={_backpedal:py,anyPunctuation:sb,autolink:cb,blockSkip:Zy,br:Hy,code:Vy,del:py,delLDelim:py,delRDelim:py,emStrongLDelim:$y,emStrongRDelimAst:nb,emStrongRDelimUnd:ib,escape:By,link:fb,nolink:mb,punctuation:qy,reflink:pb,reflinkSearch:hb,tag:ub,text:Uy,url:py},vb={..._b,link:G(/^!?\[(label)\]\((.*?)\)/).replace(`label`,db).getRegex(),reflink:G(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,db).getRegex()},yb={..._b,emStrongRDelimAst:rb,emStrongLDelim:eb,delLDelim:ab,delRDelim:ob,url:G(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,gb).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:G(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,gb).getRegex()},bb={...yb,br:G(Hy).replace(`{2,}`,`*`).getRegex(),text:G(yb.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},xb={normal:Iy,gfm:Ry,pedantic:zy},Sb={normal:_b,gfm:yb,breaks:bb,pedantic:vb},Cb={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},wb=e=>Cb[e];function Tb(e,t){if(t){if(K.escapeTest.test(e))return e.replace(K.escapeReplace,wb)}else if(K.escapeTestNoEncode.test(e))return e.replace(K.escapeReplaceNoEncode,wb);return e}function Eb(e){try{e=encodeURI(e).replace(K.percentDecode,`%`)}catch{return null}return e}function Db(e,t){let n=e.replace(K.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(K.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(K.slashPipe,`|`);return n}function Ob(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function kb(e){let t=e.split(`
1922
+ `),n=t.length-1;for(;n>=0&&K.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
1923
+ `)}function Ab(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function jb(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Mb(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Nb(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
1938
1924
  `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
1939
- `)}var qb=class{options;rules;lexer;constructor(e){this.options=e||Cy}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 e=this.options.pedantic?t[0]:Hb(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Kb(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Vb(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Vb(t[0],`
1940
- `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Vb(t[0],`
1941
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Vb(t[0],`
1925
+ `)}var Pb=class{options;rules;lexer;constructor(e){this.options=e||dy}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 e=this.options.pedantic?t[0]:kb(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Nb(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Ob(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Ob(t[0],`
1926
+ `),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Ob(t[0],`
1927
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Ob(t[0],`
1942
1928
  `).split(`
1943
1929
  `),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
1944
1930
  `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
@@ -1949,20 +1935,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
1949
1935
  `),o=this.blockquote(a);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,r=r.substring(0,r.length-t.text.length)+o.text;break}else if(u?.type===`list`){let t=u,a=t.raw+`
1950
1936
  `+e.join(`
1951
1937
  `),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
1952
- `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Wb(t[2].split(`
1938
+ `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=jb(t[2].split(`
1953
1939
  `,1)[0],t[1].length),l=e.split(`
1954
1940
  `,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
1955
1941
  `,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
1956
1942
  `,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
1957
1943
  `+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
1958
1944
  `+l}u=!l.trim(),r+=p+`
1959
- `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=Hb(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=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:e,raw:Vb(t[0],`
1960
- `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Bb(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
1961
- `):[],a={type:`table`,raw:Vb(t[0],`
1962
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Bb(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Vb(t[0],`
1945
+ `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=kb(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=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:e,raw:Ob(t[0],`
1946
+ `),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Db(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
1947
+ `):[],a={type:`table`,raw:Ob(t[0],`
1948
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Db(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Ob(t[0],`
1963
1949
  `),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
1964
- `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Vb(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Ub(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Gb(t,{href:n&&n.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 n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Gb(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},Jb=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Cy,this.options.tokenizer=this.options.tokenizer||new qb,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 t={other:Oy,block:Pb.normal,inline:Fb.normal};this.options.pedantic?(t.block=Pb.pedantic,t.inline=Fb.pedantic):this.options.gfm&&(t.block=Pb.gfm,this.options.breaks?t.inline=Fb.breaks:t.inline=Fb.gfm),this.tokenizer.rules=t}static get rules(){return{block:Pb,inline:Fb}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Oy.carriageReturn,`
1965
- `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Oy.tabCharGlobal,` `).replace(Oy.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
1950
+ `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Ob(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Ab(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Mb(t,{href:n&&n.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 n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Mb(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},Fb=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||dy,this.options.tokenizer=this.options.tokenizer||new Pb,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 t={other:K,block:xb.normal,inline:Sb.normal};this.options.pedantic?(t.block=xb.pedantic,t.inline=Sb.pedantic):this.options.gfm&&(t.block=xb.gfm,this.options.breaks?t.inline=Sb.breaks:t.inline=Sb.gfm),this.tokenizer.rules=t}static get rules(){return{block:xb,inline:Sb}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(K.carriageReturn,`
1951
+ `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(K.tabCharGlobal,` `).replace(K.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
1966
1952
  `:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
1967
1953
  `)?``:`
1968
1954
  `)+i.raw,n.text+=`
@@ -1975,9 +1961,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
1975
1961
  `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
1976
1962
  `)?``:`
1977
1963
  `)+i.raw,n.text+=`
1978
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Yb=class{options;parser;constructor(e){this.options=e||Cy}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Oy.notSpaceStart)?.[0],i=e.replace(Oy.endingNewline,``)+`
1979
- `;return r?`<pre><code class="language-`+Rb(r)+`">`+(n?i:Rb(i,!0))+`</code></pre>
1980
- `:`<pre><code>`+(n?i:Rb(i,!0))+`</code></pre>
1964
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Ib=class{options;parser;constructor(e){this.options=e||dy}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(K.notSpaceStart)?.[0],i=e.replace(K.endingNewline,``)+`
1965
+ `;return r?`<pre><code class="language-`+Tb(r)+`">`+(n?i:Tb(i,!0))+`</code></pre>
1966
+ `:`<pre><code>`+(n?i:Tb(i,!0))+`</code></pre>
1981
1967
  `}blockquote({tokens:e}){return`<blockquote>
1982
1968
  ${this.parser.parse(e)}</blockquote>
1983
1969
  `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -1993,19 +1979,19 @@ ${this.parser.parse(e)}</blockquote>
1993
1979
  `}tablerow({text:e}){return`<tr>
1994
1980
  ${e}</tr>
1995
1981
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
1996
- `}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>${Rb(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=zb(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+Rb(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=zb(e);if(i===null)return Rb(n);e=i;let a=`<img src="${e}" alt="${Rb(n)}"`;return t&&(a+=` title="${Rb(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Rb(e.text)}},Xb=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}},Zb=class e{options;renderer;textRenderer;constructor(e){this.options=e||Cy,this.options.renderer=this.options.renderer||new Yb,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Xb}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},Qb=class{options;block;constructor(e){this.options=e||Cy}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?Jb.lex:Jb.lexInline}provideParser(e=this.block){return e?Zb.parse:Zb.parseInline}},$b=new class{defaults=Sy();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Zb;Renderer=Yb;TextRenderer=Xb;Lexer=Jb;Tokenizer=qb;Hooks=Qb;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Yb(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new qb(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Qb;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];Qb.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&Qb.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Jb.lex(e,t??this.defaults)}parser(e,t){return Zb.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Jb.lex:Jb.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Zb.parse:Zb.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Jb.lex:Jb.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Zb.parse:Zb.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
1997
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Rb(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function K(e,t){return $b.parse(e,t)}K.options=K.setOptions=function(e){return $b.setOptions(e),K.defaults=$b.defaults,wy(K.defaults),K},K.getDefaults=Sy,K.defaults=Cy,K.use=function(...e){return $b.use(...e),K.defaults=$b.defaults,wy(K.defaults),K},K.walkTokens=function(e,t){return $b.walkTokens(e,t)},K.parseInline=$b.parseInline,K.Parser=Zb,K.parser=Zb.parse,K.Renderer=Yb,K.TextRenderer=Xb,K.Lexer=Jb,K.lexer=Jb.lex,K.Tokenizer=qb,K.Hooks=Qb,K.parse=K,K.options,K.setOptions,K.use,K.walkTokens,K.parseInline,Zb.parse,Jb.lex;var ex=new K.Renderer;ex.html=({text:e})=>ix(e);var tx=300,nx=new Map;function rx(e){let t=nx.get(e);if(t!==void 0)return t;let n=ox(K.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:ex}));if(nx.set(e,n),nx.size>tx){let e=nx.keys().next().value;e!==void 0&&nx.delete(e)}return n}function ix(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var ax=`table-scroll`;function ox(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!cx(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),sx(t.content),t.innerHTML}function sx(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(ax)===!0)return;let t=document.createElement(`div`);t.className=ax,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function cx(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var lx=class extends v{constructor(...e){super(...e),this.text=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${xy(rx(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;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await v_(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?`Copied code block`:t===`failed`?`Failed to copy code block`:`Copy code block`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=rm}};B([b()],lx.prototype,`text`,void 0),lx=B([y(`formatted-text`)],lx);var ux=180,dx=class extends v{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=px(e.args),n=hx(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:gx(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=fx(e,t);return g`
1982
+ `}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>${Tb(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Eb(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+Tb(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Eb(e);if(i===null)return Tb(n);e=i;let a=`<img src="${e}" alt="${Tb(n)}"`;return t&&(a+=` title="${Tb(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Tb(e.text)}},Lb=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}},Rb=class e{options;renderer;textRenderer;constructor(e){this.options=e||dy,this.options.renderer=this.options.renderer||new Ib,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Lb}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},zb=class{options;block;constructor(e){this.options=e||dy}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?Fb.lex:Fb.lexInline}provideParser(e=this.block){return e?Rb.parse:Rb.parseInline}},Bb=new class{defaults=uy();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Rb;Renderer=Ib;TextRenderer=Lb;Lexer=Fb;Tokenizer=Pb;Hooks=zb;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Ib(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Pb(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new zb;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];zb.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&zb.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Fb.lex(e,t??this.defaults)}parser(e,t){return Rb.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Fb.lex:Fb.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Rb.parse:Rb.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Fb.lex:Fb.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Rb.parse:Rb.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
1983
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Tb(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function q(e,t){return Bb.parse(e,t)}q.options=q.setOptions=function(e){return Bb.setOptions(e),q.defaults=Bb.defaults,fy(q.defaults),q},q.getDefaults=uy,q.defaults=dy,q.use=function(...e){return Bb.use(...e),q.defaults=Bb.defaults,fy(q.defaults),q},q.walkTokens=function(e,t){return Bb.walkTokens(e,t)},q.parseInline=Bb.parseInline,q.Parser=Rb,q.parser=Rb.parse,q.Renderer=Ib,q.TextRenderer=Lb,q.Lexer=Fb,q.lexer=Fb.lex,q.Tokenizer=Pb,q.Hooks=zb,q.parse=q,q.options,q.setOptions,q.use,q.walkTokens,q.parseInline,Rb.parse,Fb.lex;var Vb=new q.Renderer;Vb.html=({text:e})=>Gb(e);var Hb=300,Ub=new Map;function Wb(e){let t=Ub.get(e);if(t!==void 0)return t;let n=qb(q.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Vb}));if(Ub.set(e,n),Ub.size>Hb){let e=Ub.keys().next().value;e!==void 0&&Ub.delete(e)}return n}function Gb(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}var Kb=`table-scroll`;function qb(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!Yb(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),Jb(t.content),t.innerHTML}function Jb(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(Kb)===!0)return;let t=document.createElement(`div`);t.className=Kb,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Yb(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Xb=class extends v{constructor(...e){super(...e),this.text=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${ly(Wb(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;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await o_(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?`Copied code block`:t===`failed`?`Failed to copy code block`:`Copy code block`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=Gp}};B([b()],Xb.prototype,`text`,void 0),Xb=B([y(`formatted-text`)],Xb);var Zb=180,Qb=class extends v{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=ex(e.args),n=nx(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:rx(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=$b(e,t);return g`
1998
1984
  <section class=${`tool-card ${e.status}`}>
1999
1985
  <div class="tool-header">
2000
1986
  <div class="tool-title">
2001
- <span class="status-icon" aria-hidden="true">${bx(e.status)}</span>
1987
+ <span class="status-icon" aria-hidden="true">${sx(e.status)}</span>
2002
1988
  <strong>${e.toolName}</strong>
2003
1989
  ${this.renderHeaderTarget(l)}
2004
1990
  </div>
2005
1991
  <div class="tool-meta">
2006
- ${mx(e)===void 0?null:g`<span>${mx(e)}</span>`}
1992
+ ${tx(e)===void 0?null:g`<span>${tx(e)}</span>`}
2007
1993
  ${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
2008
- <span class="status-label">${xx(e.status)}</span>
1994
+ <span class="status-label">${cx(e.status)}</span>
2009
1995
  </div>
2010
1996
  </div>
2011
1997
 
@@ -2030,7 +2016,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2030
2016
  `}
2031
2017
  </details>
2032
2018
  `}renderDiffBody(e,t,n){let r=e.split(`
2033
- `),i=!this.showFullDiff&&r.length>ux,a=i?r.slice(0,ux):r;return g`
2019
+ `),i=!this.showFullDiff&&r.length>Zb,a=i?r.slice(0,Zb):r;return g`
2034
2020
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
2035
2021
  <summary>
2036
2022
  <span>${t}</span>
@@ -2041,14 +2027,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2041
2027
  <span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
2042
2028
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
2043
2029
  </div>
2044
- <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${_x(e)}>${e}</span>`)}</code></pre>
2030
+ <pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${ix(e)}>${e}</span>`)}</code></pre>
2045
2031
  ${i?g`
2046
2032
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
2047
2033
  Show all ${String(r.length)} diff lines
2048
2034
  </button>
2049
2035
  `:null}
2050
2036
  </details>
2051
- `}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await v_(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
2037
+ `}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await o_(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
2052
2038
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
2053
2039
  .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); }
2054
2040
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -2092,24 +2078,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2092
2078
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
2093
2079
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
2094
2080
  .show-more { justify-self: start; }
2095
- `}};B([b({attribute:!1})],dx.prototype,`execution`,void 0),B([x()],dx.prototype,`showFullDiff`,void 0),B([x()],dx.prototype,`copied`,void 0),B([x()],dx.prototype,`diffOpen`,void 0),dx=B([y(`tool-execution-view`)],dx);function fx(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=wx(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function px(e){return wx(e,`path`)??wx(e,`file_path`)}function mx(e){if(e.toolName!==`edit`)return;let t=Cx(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof Cx(e.args,`oldText`)==`string`&&typeof Cx(e.args,`newText`)==`string`)return`1 edit`}function hx(e){return wx(e,`diff`)}function gx(e){let t=0,n=0;for(let r of e.split(`
2096
- `))vx(r)?t++:yx(r)&&n++;return{added:t,removed:n}}function _x(e){return vx(e)?`added`:yx(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function vx(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function yx(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function bx(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function xx(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function Sx(e){return typeof e==`object`&&!!e}function Cx(e,t){return Sx(e)?e[t]:void 0}function wx(e,t){let n=Cx(e,t);return typeof n==`string`?n:void 0}var Tx=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),Ex=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function Dx(e){return g`
2081
+ `}};B([b({attribute:!1})],Qb.prototype,`execution`,void 0),B([x()],Qb.prototype,`showFullDiff`,void 0),B([x()],Qb.prototype,`copied`,void 0),B([x()],Qb.prototype,`diffOpen`,void 0),Qb=B([y(`tool-execution-view`)],Qb);function $b(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=dx(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function ex(e){return dx(e,`path`)??dx(e,`file_path`)}function tx(e){if(e.toolName!==`edit`)return;let t=ux(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof ux(e.args,`oldText`)==`string`&&typeof ux(e.args,`newText`)==`string`)return`1 edit`}function nx(e){return dx(e,`diff`)}function rx(e){let t=0,n=0;for(let r of e.split(`
2082
+ `))ax(r)?t++:ox(r)&&n++;return{added:t,removed:n}}function ix(e){return ax(e)?`added`:ox(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function ax(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function ox(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function sx(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function cx(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function lx(e){return typeof e==`object`&&!!e}function ux(e,t){return lx(e)?e[t]:void 0}function dx(e,t){let n=ux(e,t);return typeof n==`string`?n:void 0}var fx=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),px=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function mx(e){return g`
2097
2083
  <svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2098
2084
  <path d="m9 18 6-6-6-6"></path>
2099
2085
  </svg>
2100
- `}function Ox(){return g`
2086
+ `}function hx(){return g`
2101
2087
  <svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2102
2088
  <path d="M6 6l12 12"></path>
2103
2089
  <path d="M18 6 6 18"></path>
2104
2090
  </svg>
2105
- `}function kx(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function Ax(e){return jx(e,0,100)}function jx(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Mx(e,t){return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},t.length===0?void 0:{source:`server`,heading:`Queued messages`,detail:`${String(t.length)} pending`,messages:t}].filter(e=>e!==void 0)}function Nx(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function Px(e){return e===void 0||e===``?`tool output`:`${e} output`}function Fx(e){return`m:${String(e)}`}function Ix(e){return`g:${String(e)}`}function Lx(e){return`e:${String(e)}`}function Rx(e){return`g:${String(e)}`}function zx(e){return e?`msg event-group live`:`msg event-group`}function Bx(e){return e?`live events`:`events`}function Vx(e,t,n){return e.source===`server`&&t&&n}function Hx(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function Ux(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:Wx(t),Gx(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function Wx(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return Tx.format(t)}function Gx(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var q=class extends v{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.canClearServerQueue=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new Ev,this.scrollController=new ey,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.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}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.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),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.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,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),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),(e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let 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();let t=e.has(`pendingAsk`)&&this.isNewPendingAsk(e.get(`pendingAsk`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&(e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&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`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!kx(e)||t===void 0?e!==t:cd(e)!==cd(t)}render(){let e=this.groupedMessages();return g`
2091
+ `}function gx(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function _x(e){return vx(e,0,100)}function vx(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function yx(e,t){return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},t.length===0?void 0:{source:`server`,heading:`Queued messages`,detail:`${String(t.length)} pending`,messages:t}].filter(e=>e!==void 0)}function bx(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function xx(e){return e===void 0||e===``?`tool output`:`${e} output`}function Sx(e){return`m:${String(e)}`}function Cx(e){return`g:${String(e)}`}function wx(e){return`e:${String(e)}`}function Tx(e){return`g:${String(e)}`}function Ex(e){return e?`msg event-group live`:`msg event-group`}function Dx(e){return e?`live events`:`events`}function Ox(e,t){return e.source===`server`&&t}function kx(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function Ax(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:jx(t),Mx(e),e.meta?.thinkingLevel].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function jx(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return fx.format(t)}function Mx(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var J=class extends v{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new mv,this.scrollController=new Hv,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.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}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.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),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.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,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),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),(e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let 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();let t=e.has(`pendingAsk`)&&this.isNewPendingAsk(e.get(`pendingAsk`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&(e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&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`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!gx(e)||t===void 0?e!==t:ed(e)!==ed(t)}render(){let e=this.groupedMessages();return g`
2106
2092
  ${this.renderTopNotices()}
2107
2093
  ${this.renderNotificationLiveRegions()}
2108
2094
  <div class="chat-wrap">
2109
2095
  ${this.renderConversationRail()}
2110
2096
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
2111
2097
  ${this.renderHistoryBoundary()}
2112
- ${Cv(e,e=>e.kind===`group`?this.groupRenderKey(e.startIndex):this.messageAnchorKey(e.index),(t,n)=>t.kind===`group`?this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,n)):t.kind===`tool-image`?this.renderToolImageOutput(t.message,t.index,t.toolName):this.renderMessage(t.message,t.index))}
2098
+ ${dv(e,e=>e.kind===`group`?this.groupRenderKey(e.startIndex):this.messageAnchorKey(e.index),(t,n)=>t.kind===`group`?this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,n)):t.kind===`tool-image`?this.renderToolImageOutput(t.message,t.index,t.toolName):this.renderMessage(t.message,t.index))}
2113
2099
  ${this.renderQueuedMessages()}
2114
2100
  ${this.renderSessionActivity()}
2115
2101
  ${this.renderOpenAsk()}
@@ -2118,10 +2104,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2118
2104
  ${this.renderActivityDock()}
2119
2105
  </div>
2120
2106
  ${this.renderImageZoom()}
2121
- `}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderNotificationTray(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return null;let t=cd(e),n=e.pendingDismissedIds.size>0||e.dismissAllPending,r=this.retainedEmptyNotificationTrayTargetKey===t,i=id(e);if(i===0&&!n&&!r)return null;let a=ld(this.collapsedNotificationTargetKeys,e),o=a?`Expand notifications`:`Collapse notifications`;return g`
2107
+ `}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderNotificationTray(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return null;let t=ed(e),n=e.pendingDismissedIds.size>0||e.dismissAllPending,r=this.retainedEmptyNotificationTrayTargetKey===t,i=Xu(e);if(i===0&&!n&&!r)return null;let a=td(this.collapsedNotificationTargetKeys,e),o=a?`Expand notifications`:`Collapse notifications`;return g`
2122
2108
  <section class=${`notification-tray${a?` collapsed`:``}`} role="region" aria-labelledby="session-notifications-heading" @focusout=${e=>{this.releaseEmptyNotificationTray(e)}}>
2123
2109
  <header class="notification-header" data-notification-focus="header" tabindex="-1">
2124
- <strong class="notification-heading" id="session-notifications-heading">${ad(e)}</strong>
2110
+ <strong class="notification-heading" id="session-notifications-heading">${Zu(e)}</strong>
2125
2111
  <div class="notification-header-actions">
2126
2112
  <button
2127
2113
  type="button"
@@ -2139,38 +2125,38 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2139
2125
  aria-expanded=${String(!a)}
2140
2126
  aria-controls="session-notification-list"
2141
2127
  @click=${()=>{this.toggleNotificationTray(e,a)}}
2142
- >${Dx(a)}</button>
2128
+ >${mx(a)}</button>
2143
2129
  </div>
2144
2130
  </header>
2145
2131
  <div class="notification-list" id="session-notification-list" ?hidden=${a}>
2146
2132
  ${e.discardedCount===0?null:g`
2147
- <p class="notification-overflow">${dd(e.discardedCount)}</p>
2133
+ <p class="notification-overflow">${rd(e.discardedCount)}</p>
2148
2134
  `}
2149
- ${e.notifications.map(t=>{let n=nd(t.severity),r=fd(t);return g`
2135
+ ${e.notifications.map(t=>{let n=Ju(t.severity),r=id(t);return g`
2150
2136
  <article class=${`notification-row ${t.severity}`} data-notification-id=${t.id} tabindex="-1">
2151
2137
  <div class="notification-metadata">
2152
2138
  <strong class="notification-severity">${n}</strong>
2153
2139
  <span aria-hidden="true">·</span>
2154
- <time datetime=${t.receivedAt}>${Ex.format(new Date(t.receivedAt))}</time>
2140
+ <time datetime=${t.receivedAt}>${px.format(new Date(t.receivedAt))}</time>
2155
2141
  </div>
2156
2142
  <p class="notification-message" dir="auto">${t.message}</p>
2157
2143
  ${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
2158
2144
  <button
2159
2145
  type="button"
2160
2146
  class="notification-row-dismiss"
2161
- aria-label=${od(t)}
2147
+ aria-label=${Qu(t)}
2162
2148
  title="Dismiss notification"
2163
2149
  ?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
2164
2150
  @click=${()=>{this.dismissNotification(t.id)}}
2165
- >${Ox()}</button>
2151
+ >${hx()}</button>
2166
2152
  </article>
2167
2153
  `})}
2168
2154
  </div>
2169
2155
  </section>
2170
2156
  `}renderNotificationLiveRegions(){let e=this.notificationInbox?.sessionId===this.sessionId?this.notificationInbox.announcements:[],t=e.filter(e=>e.severity!==`error`),n=e.filter(e=>e.severity===`error`);return g`
2171
- <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${Cv(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${rd(e)}</span>`)}</div>
2172
- <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${Cv(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${rd(e)}</span>`)}</div>
2173
- `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=ud(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=sd(t.notifications,e),r=cd(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=cd(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===cd(r)&&id(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||cd(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}id(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=Hx(this.status);return!this.warningsVisible||e.length===0?null:g`
2157
+ <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${dv(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yu(e)}</span>`)}</div>
2158
+ <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${dv(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yu(e)}</span>`)}</div>
2159
+ `}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=nd(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$u(t.notifications,e),r=ed(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=ed(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===ed(r)&&Xu(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||ed(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}Xu(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=kx(this.status);return!this.warningsVisible||e.length===0?null:g`
2174
2160
  <aside class="session-warnings" role="alert" aria-live="polite">
2175
2161
  ${this.onToggleWarnings===void 0?null:g`
2176
2162
  <div class="session-warnings-controls">
@@ -2191,7 +2177,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2191
2177
  ${e.map(e=>{let t=e.dismissId;return g`
2192
2178
  <div class=${e.severityClass}>
2193
2179
  <div class="session-warning-head">
2194
- ${Qp(e.severity,`session-warning-icon`)}
2180
+ ${Bp(e.severity,`session-warning-icon`)}
2195
2181
  ${e.source===void 0?null:g`<span class="session-warning-source">${e.source}</span>`}
2196
2182
  </div>
2197
2183
  <div class="session-warning-body">
@@ -2217,7 +2203,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2217
2203
  <img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
2218
2204
  `}
2219
2205
  </dialog>
2220
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Mv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return g`
2206
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=bv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return g`
2221
2207
  <div class="activity-dock active" aria-live="polite">
2222
2208
  <span class="dot"></span>
2223
2209
  <span class="activity-text">Sending your message…</span>
@@ -2227,7 +2213,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2227
2213
  <span class="dot"></span>
2228
2214
  <span class="activity-text">${this.activityText(e)}</span>
2229
2215
  </div>
2230
- `}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${Mx(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=Vx(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
2216
+ `}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${yx(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=Ox(e,this.onClearServerQueue!==void 0);return g`
2231
2217
  <aside class="queued-messages" aria-live="polite">
2232
2218
  <div class="queued-header">
2233
2219
  <div class="queued-heading">
@@ -2253,7 +2239,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2253
2239
  .onSubmit=${this.onSubmitAsk}
2254
2240
  ></ask-user-card>
2255
2241
  `}renderExtensionDialogs(){let e=this.pendingDialogs[0];if(e===void 0&&this.closedDialogs.length===0)return null;let t=this.pendingDialogs.length-1;return g`
2256
- ${Cv(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
2242
+ ${dv(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
2257
2243
  <extension-dialog-card
2258
2244
  class="closed-dialog-card"
2259
2245
  data-scroll-anchor-id=${`closed-dialog:${e.dialog.dialogId}`}
@@ -2277,7 +2263,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2277
2263
  <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
2278
2264
  ${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
2279
2265
  </aside>
2280
- `:null}activityState(){let 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){let 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;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?Ax(this.messages.length/e*100):100}></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;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return Ax(jx(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
2266
+ `:null}activityState(){let 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){let 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;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?_x(this.messages.length/e*100):100}></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;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return _x(vx(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
2281
2267
  <div class="history-boundary">
2282
2268
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
2283
2269
  <span>Scroll up to load earlier messages</span>
@@ -2289,7 +2275,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2289
2275
  ${n||r?null:this.renderMessageHeader(e,String(t))}
2290
2276
  ${e.parts.map(t=>this.renderPart(t,e))}
2291
2277
  </article>
2292
- `}renderToolImageOutput(e,t,n){let r=Px(n);return g`
2278
+ `}renderToolImageOutput(e,t,n){let r=xx(n);return g`
2293
2279
  ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
2294
2280
  <article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
2295
2281
  ${this.renderMessageHeader(e,String(t),r)}
@@ -2297,10 +2283,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2297
2283
  </article>
2298
2284
  `}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}isAskUserRecordOnlyMessage(e){return e.parts.length>0&&e.parts.every(e=>e.type===`askUserRecord`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
2299
2285
  ${this.renderScrollMarker(this.groupScrollMarkerId(n))}
2300
- <details class=${zx(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2286
+ <details class=${Ex(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
2301
2287
  <summary>
2302
- <b class="label">${Bx(r)}</b>
2303
- <span>${Nv(e)}</span>
2288
+ <b class="label">${Dx(r)}</b>
2289
+ <span>${xv(e)}</span>
2304
2290
  </summary>
2305
2291
  ${a?this.renderMessageGroupBody(e,t):null}
2306
2292
  </details>
@@ -2329,7 +2315,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2329
2315
  </div>
2330
2316
  `}onMetaKeydown(e,t,n){e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),this.expandedMetaKey=n?void 0:t)}isCopyableMessage(e){return(e.role===`user`||e.role===`assistant`)&&this.messageCopyText(e)!==``}messageCopyText(e){let t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;let n=e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(`
2331
2317
 
2332
- `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await v_(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=Ux(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
2318
+ `);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await o_(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=Ax(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
2333
2319
  <details class="part skill-invocation">
2334
2320
  <summary><b>[skill]</b> ${e.name}</summary>
2335
2321
  <small>${e.location}</small>
@@ -2346,51 +2332,51 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2346
2332
  .outcome=${e.outcome}
2347
2333
  .draftSessionId=${this.askDraftSessionId}
2348
2334
  ></ask-user-card>
2349
- `;if(e.type===`image`){let{src:t,alt:n}=Nx(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
2335
+ `;if(e.type===`image`){let{src:t,alt:n}=bx(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
2350
2336
  <details class="part" ?open=${e.isError}>
2351
2337
  <summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
2352
2338
  <formatted-text .text=${e.text}></formatted-text>
2353
2339
  </details>
2354
- `:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&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){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let 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;let e=this.chat;e&&Gv({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(){let e=this.chat;return!e||ay(e)}isAtBottom(){let e=this.chat;return!e||iy(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let 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(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}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;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Lv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(Rv(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}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}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=jx(n,0,Math.max(0,e-1));return}this.currentConversationIndex=jx(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(){let e=this.chat;if(e!==void 0)return cy(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??cy(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,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return Fx(e)}groupRenderKey(e){return Ix(e)}groupAnchorKey(e){return Ix(e)}eventAnchorKey(e){return Lx(e)}messageScrollMarkerId(e){return Fx(e)}groupScrollMarkerId(e){return Rx(e)}static{this.styles=nm}};B([b({attribute:!1})],q.prototype,`messages`,void 0),B([b()],q.prototype,`sessionId`,void 0),B([b({type:Number})],q.prototype,`messageStart`,void 0),B([b({type:Number})],q.prototype,`messageEnd`,void 0),B([b({type:Number})],q.prototype,`messageTotal`,void 0),B([b({type:Boolean})],q.prototype,`hasMore`,void 0),B([b({type:Boolean})],q.prototype,`loadingMore`,void 0),B([b({type:Boolean})],q.prototype,`isSendingPrompt`,void 0),B([b({type:Boolean})],q.prototype,`isCompacting`,void 0),B([b({type:Number})],q.prototype,`pendingMessageCount`,void 0),B([b({attribute:!1})],q.prototype,`clientQueuedMessages`,void 0),B([b({attribute:!1})],q.prototype,`status`,void 0),B([b({attribute:!1})],q.prototype,`activity`,void 0),B([b({attribute:!1})],q.prototype,`pendingAsk`,void 0),B([b({attribute:!1})],q.prototype,`askDraftSessionId`,void 0),B([b({attribute:!1})],q.prototype,`onSubmitAsk`,void 0),B([b({attribute:!1})],q.prototype,`pendingDialogs`,void 0),B([b({attribute:!1})],q.prototype,`closedDialogs`,void 0),B([b({attribute:!1})],q.prototype,`onAnswerDialog`,void 0),B([b({attribute:!1})],q.prototype,`onCancelDialog`,void 0),B([b({attribute:!1})],q.prototype,`onDismissClosedDialog`,void 0),B([b({attribute:!1})],q.prototype,`notificationInbox`,void 0),B([b({type:Boolean})],q.prototype,`canClearServerQueue`,void 0),B([b({attribute:!1})],q.prototype,`onClearServerQueue`,void 0),B([b({attribute:!1})],q.prototype,`onDismissWarning`,void 0),B([b({attribute:!1})],q.prototype,`onDismissNotification`,void 0),B([b({attribute:!1})],q.prototype,`onDismissAllNotifications`,void 0),B([b({type:Boolean})],q.prototype,`warningsVisible`,void 0),B([b({attribute:!1})],q.prototype,`onToggleWarnings`,void 0),B([b({attribute:!1})],q.prototype,`onLoadMore`,void 0),B([S(`.chat`)],q.prototype,`chat`,void 0),B([S(`dialog.image-zoom`)],q.prototype,`imageZoomDialog`,void 0),B([x()],q.prototype,`pinnedToBottom`,void 0),B([x()],q.prototype,`zoomedImage`,void 0),B([x()],q.prototype,`expandedMetaKey`,void 0),B([x()],q.prototype,`copiedMessageKey`,void 0),B([x()],q.prototype,`currentConversationIndex`,void 0),B([x()],q.prototype,`collapsedNotificationTargetKeys`,void 0),B([x()],q.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([x()],q.prototype,`loadMoreRequested`,void 0),q=B([y(`chat-view`)],q);var Kx=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function qx(e){return typeof e==`string`&&Kx.has(e)}function Jx(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var Yx=`application/octet-stream`,Xx=`Failed to read an attachment.`;async function Zx(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(tS(i,e))}catch{r=Xx}return{attachments:n,...r===void 0?{}:{error:r}}}function Qx(e){return e.kind===`image`&&qx(e.mimeType)}function $x(e){return e.every(e=>Qx(e))}function eS(e,t){return $x(t)?e:`folder`}function tS(e,t){return qx(e.type)?{kind:`image`,name:rS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:rS(e),mimeType:nS(e),data:t,size:e.size}}function nS(e){let t=e.type.trim();return t===``?Yx:t}function rS(e){return e.name===``?qx(e.type)?`pasted-image.${Jx(e.type)}`:`pasted-file.bin`:e.name}var iS=`pi-web:attachment-delivery`;function aS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function oS(e=aS()){try{return e?.getItem(iS)===`folder`?`folder`:`inline`}catch{return`inline`}}function sS(e,t=aS()){try{t?.setItem(iS,e)}catch{}}var cS=`(pointer: coarse), (max-width: 760px)`,lS=`pi-web.promptEnterPreference`;function uS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(cS):void 0}function dS(e){return e===`send`||e===`newline`?e:`auto`}function fS(e=_S()){if(e===void 0)return`auto`;try{return dS(e.getItem(lS))}catch{return`auto`}}function pS(e,t=_S()){if(t!==void 0)try{t.setItem(lS,e)}catch{}}function mS(e=uS(),t=fS()){return t===`send`||t!==`newline`&&e?.matches!==!0}function hS(e,t,n=uS()){return e?n?.matches!==!0||t:!1}function gS(e,t=uS(),n=fS()){let r=mS(t,n);return e?!r:r}function _S(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function vS(){return Je`
2340
+ `:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&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){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let 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;let e=this.chat;e&&Nv({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(){let e=this.chat;return!e||qv(e)}isAtBottom(){let e=this.chat;return!e||Kv(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let 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(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}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;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Tv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(Ev(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}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}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=vx(n,0,Math.max(0,e-1));return}this.currentConversationIndex=vx(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(){let e=this.chat;if(e!==void 0)return Xv(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??Xv(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,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return Sx(e)}groupRenderKey(e){return Cx(e)}groupAnchorKey(e){return Cx(e)}eventAnchorKey(e){return wx(e)}messageScrollMarkerId(e){return Sx(e)}groupScrollMarkerId(e){return Tx(e)}static{this.styles=Wp}};B([b({attribute:!1})],J.prototype,`messages`,void 0),B([b()],J.prototype,`sessionId`,void 0),B([b({type:Number})],J.prototype,`messageStart`,void 0),B([b({type:Number})],J.prototype,`messageEnd`,void 0),B([b({type:Number})],J.prototype,`messageTotal`,void 0),B([b({type:Boolean})],J.prototype,`hasMore`,void 0),B([b({type:Boolean})],J.prototype,`loadingMore`,void 0),B([b({type:Boolean})],J.prototype,`isSendingPrompt`,void 0),B([b({type:Boolean})],J.prototype,`isCompacting`,void 0),B([b({type:Number})],J.prototype,`pendingMessageCount`,void 0),B([b({attribute:!1})],J.prototype,`clientQueuedMessages`,void 0),B([b({attribute:!1})],J.prototype,`status`,void 0),B([b({attribute:!1})],J.prototype,`activity`,void 0),B([b({attribute:!1})],J.prototype,`pendingAsk`,void 0),B([b({attribute:!1})],J.prototype,`askDraftSessionId`,void 0),B([b({attribute:!1})],J.prototype,`onSubmitAsk`,void 0),B([b({attribute:!1})],J.prototype,`pendingDialogs`,void 0),B([b({attribute:!1})],J.prototype,`closedDialogs`,void 0),B([b({attribute:!1})],J.prototype,`onAnswerDialog`,void 0),B([b({attribute:!1})],J.prototype,`onCancelDialog`,void 0),B([b({attribute:!1})],J.prototype,`onDismissClosedDialog`,void 0),B([b({attribute:!1})],J.prototype,`notificationInbox`,void 0),B([b({attribute:!1})],J.prototype,`onClearServerQueue`,void 0),B([b({attribute:!1})],J.prototype,`onDismissWarning`,void 0),B([b({attribute:!1})],J.prototype,`onDismissNotification`,void 0),B([b({attribute:!1})],J.prototype,`onDismissAllNotifications`,void 0),B([b({type:Boolean})],J.prototype,`warningsVisible`,void 0),B([b({attribute:!1})],J.prototype,`onToggleWarnings`,void 0),B([b({attribute:!1})],J.prototype,`onLoadMore`,void 0),B([S(`.chat`)],J.prototype,`chat`,void 0),B([S(`dialog.image-zoom`)],J.prototype,`imageZoomDialog`,void 0),B([x()],J.prototype,`pinnedToBottom`,void 0),B([x()],J.prototype,`zoomedImage`,void 0),B([x()],J.prototype,`expandedMetaKey`,void 0),B([x()],J.prototype,`copiedMessageKey`,void 0),B([x()],J.prototype,`currentConversationIndex`,void 0),B([x()],J.prototype,`collapsedNotificationTargetKeys`,void 0),B([x()],J.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([x()],J.prototype,`loadMoreRequested`,void 0),J=B([y(`chat-view`)],J);var Nx=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function Px(e){return typeof e==`string`&&Nx.has(e)}function Fx(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var Ix=`application/octet-stream`,Lx=`Failed to read an attachment.`;async function Rx(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(Hx(i,e))}catch{r=Lx}return{attachments:n,...r===void 0?{}:{error:r}}}function zx(e){return e.kind===`image`&&Px(e.mimeType)}function Bx(e){return e.every(e=>zx(e))}function Vx(e,t){return Bx(t)?e:`folder`}function Hx(e,t){return Px(e.type)?{kind:`image`,name:Wx(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:Wx(e),mimeType:Ux(e),data:t,size:e.size}}function Ux(e){let t=e.type.trim();return t===``?Ix:t}function Wx(e){return e.name===``?Px(e.type)?`pasted-image.${Fx(e.type)}`:`pasted-file.bin`:e.name}var Gx=`pi-web:attachment-delivery`;function Kx(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function qx(e=Kx()){try{return e?.getItem(Gx)===`folder`?`folder`:`inline`}catch{return`inline`}}function Jx(e,t=Kx()){try{t?.setItem(Gx,e)}catch{}}var Yx=`(pointer: coarse), (max-width: 760px)`,Xx=`pi-web.promptEnterPreference`;function Zx(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(Yx):void 0}function Qx(e){return e===`send`||e===`newline`?e:`auto`}function $x(e=iS()){if(e===void 0)return`auto`;try{return Qx(e.getItem(Xx))}catch{return`auto`}}function eS(e,t=iS()){if(t!==void 0)try{t.setItem(Xx,e)}catch{}}function tS(e=Zx(),t=$x()){return t===`send`||t!==`newline`&&e?.matches!==!0}function nS(e,t,n=Zx()){return e?n?.matches!==!0||t:!1}function rS(e,t=Zx(),n=$x()){let r=tS(t,n);return e?!r:r}function iS(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function aS(){return Je`
2355
2341
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2356
2342
  <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
2357
2343
  </svg>
2358
- `}function yS(){return Je`
2344
+ `}function oS(){return Je`
2359
2345
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2360
2346
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
2361
2347
  <path d="M21 3 11.5 12.5"></path>
2362
2348
  </svg>
2363
- `}function bS(){return Je`
2349
+ `}function sS(){return Je`
2364
2350
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2365
2351
  <path d="M4 7h11"></path>
2366
2352
  <path d="M4 12h7"></path>
2367
2353
  <path d="M4 17h7"></path>
2368
2354
  <path d="m15 14 5 3-5 3z"></path>
2369
2355
  </svg>
2370
- `}function xS(){return yS()}function SS(){return Je`
2356
+ `}function cS(){return oS()}function lS(){return Je`
2371
2357
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2372
2358
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
2373
2359
  </svg>
2374
- `}function CS(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Je`
2360
+ `}function uS(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Je`
2375
2361
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2376
2362
  ${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return Je`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
2377
2363
  </svg>
2378
- `}var wS=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function TS(e){return e===void 0||e===``?`off`:e}function ES(e,t){let n=t.length>=2?t:wS,r=n.length-1,i=TS(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var DS=dv(class extends fv{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===uv.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),OS=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
2364
+ `}var dS=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function fS(e){return e===void 0||e===``?`off`:e}function pS(e,t){let n=t.length>=2?t:dS,r=n.length-1,i=fS(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var mS=$_(class extends ev{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Q_.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),hS=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
2379
2365
  <div class="menu">
2380
2366
  ${this.items.map((e,t)=>g`
2381
- <button class=${t===this.selectedIndex?`selected`:``} ${DS(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
2367
+ <button class=${t===this.selectedIndex?`selected`:``} ${mS(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
2382
2368
  <strong>${e.insertText}</strong>
2383
2369
  <span>${e.detail}</span>
2384
2370
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
2385
2371
  </button>
2386
2372
  `)}
2387
2373
  </div>
2388
- `:null}static{this.styles=am}};B([b({attribute:!1})],OS.prototype,`items`,void 0),B([b({type:Number})],OS.prototype,`selectedIndex`,void 0),B([b({attribute:!1})],OS.prototype,`onPick`,void 0),OS=B([y(`autocomplete-menu`)],OS);var J=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=oS(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=uS(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=AS(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&hc(n,this.draft);let r=AS(this.machineId,this.sessionId);this.draft=r===void 0?``:mc(r),this.currentInputMode=zl(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!kS(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
2374
+ `:null}static{this.styles=qp}};B([b({attribute:!1})],hS.prototype,`items`,void 0),B([b({type:Number})],hS.prototype,`selectedIndex`,void 0),B([b({attribute:!1})],hS.prototype,`onPick`,void 0),hS=B([y(`autocomplete-menu`)],hS);var Y=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=qx(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=Zx(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=_S(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&hc(n,this.draft);let r=_S(this.machineId,this.sessionId);this.draft=r===void 0?``:mc(r),this.currentInputMode=Ul(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!gS(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
2389
2375
  <footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
2390
2376
  <div class="editor-wrap">
2391
2377
  <div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
2392
2378
  <input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
2393
- <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${vS()}</button>
2379
+ <button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${aS()}</button>
2394
2380
  ${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
2395
2381
  ${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
2396
2382
  ${this.renderAttachments()}
@@ -2398,20 +2384,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2398
2384
  </div>
2399
2385
  <div class="actions">
2400
2386
  ${this.renderCompactStatus()}
2401
- <button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?bS():yS()}</button>
2402
- ${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${xS()}</button>`:null}
2403
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${SS()}</button>
2387
+ <button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?sS():oS()}</button>
2388
+ ${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${cS()}</button>`:null}
2389
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${lS()}</button>
2404
2390
  </div>
2405
2391
  </footer>
2406
- `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=AS(this.machineId,this.sessionId);t!==void 0&&hc(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=zl(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??`no model`;return g`
2392
+ `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=_S(this.machineId,this.sessionId);t!==void 0&&hc(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=Ul(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??`no model`;return g`
2407
2393
  <div class="compact-status" aria-label="Session status">
2408
2394
  <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``}${t}</button>
2409
- <button class="select-thinking icon-button" title=${`Thinking level: ${TS(e.thinkingLevel)}`} aria-label=${`Thinking level: ${TS(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${CS(ES(e.thinkingLevel,this.availableThinkingLevels))}</button>
2395
+ <button class="select-thinking icon-button" title=${`Thinking level: ${fS(e.thinkingLevel)}`} aria-label=${`Thinking level: ${fS(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${uS(pS(e.thinkingLevel,this.availableThinkingLevels))}</button>
2410
2396
  </div>
2411
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=$x(this.attachments),t=this.effectiveAttachmentDelivery();return g`
2397
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=Bx(this.attachments),t=this.effectiveAttachmentDelivery();return g`
2412
2398
  <div class="attachments" aria-label="Pending attachments">
2413
2399
  ${this.attachments.map(e=>g`
2414
- <div class=${`attachment-chip ${Qx(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
2400
+ <div class=${`attachment-chip ${zx(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
2415
2401
  ${this.renderAttachmentPreview(e)}
2416
2402
  <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
2417
2403
  </div>
@@ -2426,10 +2412,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2426
2412
  `:null}
2427
2413
  ${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
2428
2414
  </div>
2429
- `}renderAttachmentPreview(e){return Qx(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
2430
- <div class="attachment-file-preview" aria-hidden="true">${IS(e.name)}</div>
2415
+ `}renderAttachmentPreview(e){return zx(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
2416
+ <div class="attachment-file-preview" aria-hidden="true">${wS(e.name)}</div>
2431
2417
  <span class="attachment-file-name">${e.name}</span>
2432
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!$x(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,sS(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=NS(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&PS(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=NS(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;let{attachments:t,error:n}=await Zx(e,LS);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>FS(e))}effectiveAttachmentDelivery(){return eS(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>BS(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=AS(this.machineId,this.sessionId);t!==void 0&&hc(t,this.draft);let n=zl(this.draft);Vl(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(jS);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await L.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(MS);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Pl(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return Nl(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=hS(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return gS(t,this.mobilePromptEnterMedia,fS())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=AS(this.machineId,this.sessionId);e!==void 0&&gc(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=cm}};B([b({type:Boolean})],J.prototype,`disabled`,void 0),B([b()],J.prototype,`sessionId`,void 0),B([b()],J.prototype,`cwd`,void 0),B([b()],J.prototype,`machineId`,void 0),B([b()],J.prototype,`projectId`,void 0),B([b()],J.prototype,`workspaceId`,void 0),B([b({type:Boolean})],J.prototype,`workspaceScopedFileSuggestions`,void 0),B([b({type:Boolean})],J.prototype,`canSteer`,void 0),B([b({type:Boolean})],J.prototype,`isCompacting`,void 0),B([b({type:Boolean})],J.prototype,`canStop`,void 0),B([b({attribute:!1})],J.prototype,`status`,void 0),B([b({type:Boolean})],J.prototype,`sending`,void 0),B([b({attribute:!1})],J.prototype,`onSend`,void 0),B([b({attribute:!1})],J.prototype,`onStop`,void 0),B([b({attribute:!1})],J.prototype,`onSelectModel`,void 0),B([b({attribute:!1})],J.prototype,`onSelectThinking`,void 0),B([b({attribute:!1})],J.prototype,`availableThinkingLevels`,void 0),B([S(`.markdown-editor`)],J.prototype,`editorHost`,void 0),B([S(`.attachment-input`)],J.prototype,`attachmentInput`,void 0),B([x()],J.prototype,`currentInputMode`,void 0),B([x()],J.prototype,`completions`,void 0),B([x()],J.prototype,`selectedIndex`,void 0),B([x()],J.prototype,`attachments`,void 0),B([x()],J.prototype,`attachmentDelivery`,void 0),B([x()],J.prototype,`attachmentError`,void 0),J=B([y(`prompt-editor`)],J);function kS(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function AS(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return wo(e,t)}function jS(){return[]}function MS(){return[]}function NS(e){return e===null?[]:Array.from(e.files)}function PS(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function FS(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function IS(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function LS(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var RS={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},zS={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function BS(e){return zl(e).kind===`normal`?RS:zS}function VS(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 HS(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function US(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}var WS=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${VS(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${VS(t.contextWindow)}`:`context unknown`,r=e.tokens,i=US(this.warningCount,this.warningsExpanded);return g`
2418
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!Bx(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,Jx(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=xS(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&SS(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=xS(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;let{attachments:t,error:n}=await Rx(e,TS);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>CS(e))}effectiveAttachmentDelivery(){return Vx(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>OS(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files, # for models`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=_S(this.machineId,this.sessionId);t!==void 0&&hc(t,this.draft);let n=Ul(this.draft);Gl(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(vS);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.projectId!==void 0&&this.workspaceId!==void 0){let n=await I.files(e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(yS);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Rl(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(bS);if(t!==this.requestVersion)return;this.completions=Fl(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return Nl(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=nS(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return rS(t,this.mobilePromptEnterMedia,$x())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=_S(this.machineId,this.sessionId);e!==void 0&&gc(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Xp}};B([b({type:Boolean})],Y.prototype,`disabled`,void 0),B([b()],Y.prototype,`sessionId`,void 0),B([b()],Y.prototype,`cwd`,void 0),B([b()],Y.prototype,`machineId`,void 0),B([b()],Y.prototype,`projectId`,void 0),B([b()],Y.prototype,`workspaceId`,void 0),B([b({type:Boolean})],Y.prototype,`canSteer`,void 0),B([b({type:Boolean})],Y.prototype,`isCompacting`,void 0),B([b({type:Boolean})],Y.prototype,`canStop`,void 0),B([b({attribute:!1})],Y.prototype,`status`,void 0),B([b({type:Boolean})],Y.prototype,`sending`,void 0),B([b({attribute:!1})],Y.prototype,`onSend`,void 0),B([b({attribute:!1})],Y.prototype,`onStop`,void 0),B([b({attribute:!1})],Y.prototype,`onSelectModel`,void 0),B([b({attribute:!1})],Y.prototype,`onSelectThinking`,void 0),B([b({attribute:!1})],Y.prototype,`availableThinkingLevels`,void 0),B([S(`.markdown-editor`)],Y.prototype,`editorHost`,void 0),B([S(`.attachment-input`)],Y.prototype,`attachmentInput`,void 0),B([x()],Y.prototype,`currentInputMode`,void 0),B([x()],Y.prototype,`completions`,void 0),B([x()],Y.prototype,`selectedIndex`,void 0),B([x()],Y.prototype,`attachments`,void 0),B([x()],Y.prototype,`attachmentDelivery`,void 0),B([x()],Y.prototype,`attachmentError`,void 0),Y=B([y(`prompt-editor`)],Y);function gS(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function _S(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return wo(e,t)}function vS(){return[]}function yS(){return[]}function bS(){return[]}function xS(e){return e===null?[]:Array.from(e.files)}function SS(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function CS(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function wS(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function TS(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var ES={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},DS={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function OS(e){return Ul(e).kind===`normal`?ES:DS}function kS(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 AS(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function jS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}var MS=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${kS(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${kS(t.contextWindow)}`:`context unknown`,r=e.tokens,i=jS(this.warningCount,this.warningsExpanded);return g`
2433
2419
  <div class="bar">
2434
2420
  ${i===void 0||this.onToggleWarnings===void 0?null:g`
2435
2421
  <button
@@ -2440,17 +2426,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2440
2426
  aria-expanded=${String(this.warningsExpanded)}
2441
2427
  @click=${this.handleToggleWarnings}
2442
2428
  >
2443
- ${Qp(`warning`,`warning-toggle-icon`)}
2429
+ ${Bp(`warning`,`warning-toggle-icon`)}
2444
2430
  <span>${i.countText}</span>
2445
2431
  </button>
2446
2432
  `}
2447
- <span>↑${VS(r.input)}</span>
2448
- <span>↓${VS(r.output)}</span>
2433
+ <span>↑${kS(r.input)}</span>
2434
+ <span>↓${kS(r.output)}</span>
2449
2435
  <span class="context">${n}</span>
2450
- <span>${HS(e.cost)}</span>
2436
+ <span>${AS(e.cost)}</span>
2451
2437
  ${e.pendingMessageCount>0?g`<span>${String(e.pendingMessageCount)} queued</span>`:null}
2452
2438
  </div>
2453
- `}static{this.styles=im}};B([b({attribute:!1})],WS.prototype,`status`,void 0),B([b({type:Number})],WS.prototype,`warningCount`,void 0),B([b({type:Boolean})],WS.prototype,`warningsExpanded`,void 0),B([b({attribute:!1})],WS.prototype,`onToggleWarnings`,void 0),WS=B([y(`status-bar`)],WS);var GS=class extends v{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
2439
+ `}static{this.styles=Kp}};B([b({attribute:!1})],MS.prototype,`status`,void 0),B([b({type:Number})],MS.prototype,`warningCount`,void 0),B([b({type:Boolean})],MS.prototype,`warningsExpanded`,void 0),B([b({attribute:!1})],MS.prototype,`onToggleWarnings`,void 0),MS=B([y(`status-bar`)],MS);var NS=class extends v{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
2454
2440
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
2455
2441
  <section @mousedown=${e=>{e.stopPropagation()}}>
2456
2442
  <header>
@@ -2460,7 +2446,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2460
2446
  ${this.searchable?g`<input placeholder="Search" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>`:null}
2461
2447
  <div class="options" @keydown=${e=>{this.handleKeyDown(e)}} tabindex="0">
2462
2448
  ${e.map((e,t)=>g`
2463
- <button class=${t===this.selectedIndex?`selected`:``} ${DS(t===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
2449
+ <button class=${t===this.selectedIndex?`selected`:``} ${mS(t===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
2464
2450
  <span>${e.label}</span>
2465
2451
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
2466
2452
  </button>
@@ -2469,7 +2455,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2469
2455
  </div>
2470
2456
  </section>
2471
2457
  </div>
2472
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=om}};B([b()],GS.prototype,`title`,void 0),B([b({type:Boolean})],GS.prototype,`searchable`,void 0),B([b({attribute:!1})],GS.prototype,`options`,void 0),B([b({attribute:!1})],GS.prototype,`selectedValue`,void 0),B([b({attribute:!1})],GS.prototype,`onPick`,void 0),B([b({attribute:!1})],GS.prototype,`onCancel`,void 0),B([x()],GS.prototype,`selectedIndex`,void 0),B([x()],GS.prototype,`query`,void 0),GS=B([y(`command-picker`)],GS);var KS=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
2458
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=Jp}};B([b()],NS.prototype,`title`,void 0),B([b({type:Boolean})],NS.prototype,`searchable`,void 0),B([b({attribute:!1})],NS.prototype,`options`,void 0),B([b({attribute:!1})],NS.prototype,`selectedValue`,void 0),B([b({attribute:!1})],NS.prototype,`onPick`,void 0),B([b({attribute:!1})],NS.prototype,`onCancel`,void 0),B([x()],NS.prototype,`selectedIndex`,void 0),B([x()],NS.prototype,`query`,void 0),NS=B([y(`command-picker`)],NS);var PS=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
2473
2459
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
2474
2460
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
2475
2461
  <header>
@@ -2482,20 +2468,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2482
2468
  </header>
2483
2469
  <div class="options">
2484
2470
  ${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
2485
- <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${DS(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
2471
+ <button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${mS(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
2486
2472
  <span class="main">
2487
2473
  <strong>${e.title}</strong>
2488
2474
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
2489
2475
  ${e.enabled===!1&&e.disabledReason!==void 0?g`<small class="disabled-reason">${e.disabledReason}</small>`:null}
2490
2476
  </span>
2491
- ${e.shortcut===void 0?null:g`<kbd>${tf(e.shortcut)}</kbd>`}
2477
+ ${e.shortcut===void 0?null:g`<kbd>${qd(e.shortcut)}</kbd>`}
2492
2478
  ${e.group!==void 0&&e.group!==``?g`<small class="group">${e.group}</small>`:null}
2493
2479
  </button>
2494
2480
  `)}
2495
2481
  </div>
2496
2482
  </section>
2497
2483
  </div>
2498
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return qS(this.actions,this.queryText)}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=sm}};B([b({attribute:!1})],KS.prototype,`actions`,void 0),B([b({attribute:!1})],KS.prototype,`onRun`,void 0),B([b({attribute:!1})],KS.prototype,`onCancel`,void 0),B([S(`input`)],KS.prototype,`input`,void 0),B([x()],KS.prototype,`queryText`,void 0),B([x()],KS.prototype,`selectedIndex`,void 0),KS=B([y(`action-palette`)],KS);function qS(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var JS=class extends v{render(){let e=this.state;return e===void 0?null:g`
2484
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return FS(this.actions,this.queryText)}handleKeyDown(e){let 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();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=Yp}};B([b({attribute:!1})],PS.prototype,`actions`,void 0),B([b({attribute:!1})],PS.prototype,`onRun`,void 0),B([b({attribute:!1})],PS.prototype,`onCancel`,void 0),B([S(`input`)],PS.prototype,`input`,void 0),B([x()],PS.prototype,`queryText`,void 0),B([x()],PS.prototype,`selectedIndex`,void 0),PS=B([y(`action-palette`)],PS);function FS(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var IS=class extends v{render(){let e=this.state;return e===void 0?null:g`
2499
2485
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
2500
2486
  <section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
2501
2487
  <header>
@@ -2505,26 +2491,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2505
2491
  ${this.renderBody(e)}
2506
2492
  </section>
2507
2493
  </div>
2508
- `}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 credential 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 g`
2494
+ `}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 credential provider`;case`oauth`:return`Login to ${e.flow.providerName}`;case`logout`:return`Remove stored provider authentication`}}renderBody(e){switch(e.step){case`method`:return g`
2509
2495
  <div class="options">
2510
2496
  <button @click=${()=>{this.onChooseMethod?.(`oauth`)}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
2511
2497
  <button @click=${()=>{this.onChooseMethod?.(`api_key`)}}><span>Use provider credentials</span><small>Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json</small></button>
2512
2498
  </div>
2513
- `;case`providers`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No providers available.</div>`:e.providers.map(e=>this.renderProviderButton(e))}</div>`;case`apiKey`:return g`
2514
- <div class="form">
2515
- <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored in the active Pi-compatible profile's <code>auth.json</code>.</p>
2516
- <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${e=>{e.target instanceof HTMLInputElement&&this.onApiKeyInput?.(e.target.value)}}>
2517
- ${e.error!==void 0&&e.error!==``?g`<div class="error-text">${e.error}</div>`:null}
2518
- <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>
2519
- </div>
2520
- `;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(e=>g`
2521
- <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${XS(e.authType)}</small></button>
2499
+ `;case`providers`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No providers available.</div>`:e.providers.map(e=>this.renderProviderButton(e))}</div>`;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(e=>g`
2500
+ <button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${RS(e.authType)}</small></button>
2522
2501
  `)}</div>`}}renderProviderButton(e){return g`
2523
2502
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
2524
- <span>${e.name}${e.status.source===void 0?null:g` <em>${QS(e)}</em>`}</span>
2525
- <small>${e.id} · ${XS(e.authType)}</small>
2503
+ <span>${e.name}${e.status.source===void 0?null:g` <em>${BS(e)}</em>`}</span>
2504
+ <small>${e.id} · ${RS(e.authType)}</small>
2526
2505
  </button>
2527
- `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=YS(n?.promptType);return g`
2506
+ `}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=n===void 0?void 0:LS(n.promptType);return g`
2528
2507
  <div class="form">
2529
2508
  ${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
2530
2509
  <p>Open this authorization link:</p>
@@ -2557,7 +2536,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2557
2536
  ${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
2558
2537
  ${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
2559
2538
  </div>
2560
- `}focusInputIfNeeded(){let e=ZS(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;let 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?.()}static{this.styles=[om,h`
2539
+ `}focusInputIfNeeded(){let e=zS(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;let t=this.state;t?.step===`oauth`&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[Jp,h`
2561
2540
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
2562
2541
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
2563
2542
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -2575,7 +2554,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2575
2554
  .inline-options button { display: grid; gap: 2px; text-align: left; }
2576
2555
  .inline-options small { color: var(--pi-muted); }
2577
2556
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
2578
- `]}};B([b({attribute:!1})],JS.prototype,`state`,void 0),B([b({attribute:!1})],JS.prototype,`onChooseMethod`,void 0),B([b({attribute:!1})],JS.prototype,`onSelectProvider`,void 0),B([b({attribute:!1})],JS.prototype,`onApiKeyInput`,void 0),B([b({attribute:!1})],JS.prototype,`onSaveApiKey`,void 0),B([b({attribute:!1})],JS.prototype,`onLogoutProvider`,void 0),B([b({attribute:!1})],JS.prototype,`onOAuthInput`,void 0),B([b({attribute:!1})],JS.prototype,`onOAuthRespond`,void 0),B([b({attribute:!1})],JS.prototype,`onOAuthCancel`,void 0),B([b({attribute:!1})],JS.prototype,`onCancel`,void 0),B([S(`input`)],JS.prototype,`input`,void 0),JS=B([y(`auth-dialog`)],JS);function YS(e){return e===`secret`?`password`:`text`}function XS(e){return e===`oauth`?`subscription`:`credentials`}function ZS(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 QS(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 $S=class extends v{constructor(...e){super(...e),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(){let e=++this.requestId;this.loading=!0;try{let t=await L.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`Enter`)e.preventDefault(),this.submit();else if(e.key===`ArrowDown`)e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key===`Tab`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
2557
+ `]}};B([b({attribute:!1})],IS.prototype,`state`,void 0),B([b({attribute:!1})],IS.prototype,`onChooseMethod`,void 0),B([b({attribute:!1})],IS.prototype,`onSelectProvider`,void 0),B([b({attribute:!1})],IS.prototype,`onLogoutProvider`,void 0),B([b({attribute:!1})],IS.prototype,`onOAuthInput`,void 0),B([b({attribute:!1})],IS.prototype,`onOAuthRespond`,void 0),B([b({attribute:!1})],IS.prototype,`onOAuthCancel`,void 0),B([b({attribute:!1})],IS.prototype,`onCancel`,void 0),B([S(`input`)],IS.prototype,`input`,void 0),IS=B([y(`auth-dialog`)],IS);function LS(e){return e===`secret`?`password`:`text`}function RS(e){return e===`oauth`?`subscription`:`credentials`}function zS(e){if(e?.step===`oauth`&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function BS(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 VS=class extends v{constructor(...e){super(...e),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(){let e=++this.requestId;this.loading=!0;try{let t=await I.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`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
2579
2558
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
2580
2559
  <section @click=${e=>{e.stopPropagation()}}>
2581
2560
  <header>
@@ -2625,7 +2604,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2625
2604
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
2626
2605
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
2627
2606
  button:disabled { opacity: .5; cursor: not-allowed; }
2628
- `}};B([b({attribute:!1})],$S.prototype,`onSubmit`,void 0),B([b({attribute:!1})],$S.prototype,`onCancel`,void 0),B([b()],$S.prototype,`machineId`,void 0),B([x()],$S.prototype,`path`,void 0),B([x()],$S.prototype,`createMissing`,void 0),B([x()],$S.prototype,`suggestions`,void 0),B([x()],$S.prototype,`selected`,void 0),B([x()],$S.prototype,`loading`,void 0),B([S(`input`)],$S.prototype,`pathInput`,void 0),$S=B([y(`project-dialog`)],$S);var eC=class extends v{constructor(...e){super(...e),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;let t=e.target.value,n=tC(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,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`&&nC(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||nC(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?nC(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
2607
+ `}};B([b({attribute:!1})],VS.prototype,`onSubmit`,void 0),B([b({attribute:!1})],VS.prototype,`onCancel`,void 0),B([b()],VS.prototype,`machineId`,void 0),B([x()],VS.prototype,`path`,void 0),B([x()],VS.prototype,`createMissing`,void 0),B([x()],VS.prototype,`suggestions`,void 0),B([x()],VS.prototype,`selected`,void 0),B([x()],VS.prototype,`loading`,void 0),B([S(`input`)],VS.prototype,`pathInput`,void 0),VS=B([y(`project-dialog`)],VS);var HS=class extends v{constructor(...e){super(...e),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;let t=e.target.value,n=US(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,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`&&WS(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||WS(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?WS(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
2629
2608
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
2630
2609
  <section @click=${e=>{e.stopPropagation()}}>
2631
2610
  <form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
@@ -2680,7 +2659,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2680
2659
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
2681
2660
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
2682
2661
  button:disabled { opacity: .5; cursor: not-allowed; }
2683
- `}};B([b({attribute:!1})],eC.prototype,`onSubmit`,void 0),B([b({attribute:!1})],eC.prototype,`onCancel`,void 0),B([b()],eC.prototype,`error`,void 0),B([x()],eC.prototype,`url`,void 0),B([x()],eC.prototype,`name`,void 0),B([x()],eC.prototype,`token`,void 0),B([x()],eC.prototype,`submitting`,void 0),B([S(`input[name='baseUrl']`)],eC.prototype,`urlInput`,void 0),B([S(`input[name='name']`)],eC.prototype,`nameInput`,void 0),eC=B([y(`machine-dialog`)],eC);function tC(e){let t=e.trim();if(t===``)return``;let n=rC(t)??rC(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):iC(t)}function nC(e){let t=e.trim();if(t===``)return`Remote PI WEB URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function rC(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function iC(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var aC={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function oC(e){return e.tone??aC[e.type]}var sC=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
2662
+ `}};B([b({attribute:!1})],HS.prototype,`onSubmit`,void 0),B([b({attribute:!1})],HS.prototype,`onCancel`,void 0),B([b()],HS.prototype,`error`,void 0),B([x()],HS.prototype,`url`,void 0),B([x()],HS.prototype,`name`,void 0),B([x()],HS.prototype,`token`,void 0),B([x()],HS.prototype,`submitting`,void 0),B([S(`input[name='baseUrl']`)],HS.prototype,`urlInput`,void 0),B([S(`input[name='name']`)],HS.prototype,`nameInput`,void 0),HS=B([y(`machine-dialog`)],HS);function US(e){let t=e.trim();if(t===``)return``;let n=GS(t)??GS(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):KS(t)}function WS(e){let t=e.trim();if(t===``)return`Remote PI WEB URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function GS(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function KS(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var qS={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function JS(e){return e.tone??qS[e.type]}var YS=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
2684
2663
  <section class="panel" aria-label=${this.heading||`Settings panel`}>
2685
2664
  <header class="section-heading">
2686
2665
  <div class="heading-copy">
@@ -2703,7 +2682,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2703
2682
  <div class="notice-stack" aria-label="Settings notices">
2704
2683
  ${this.notices.map(e=>this.renderNotice(e))}
2705
2684
  </div>
2706
- `}renderNotice(e){let t=oC(e),n=e.role??cC(t),r=e.title;return g`
2685
+ `}renderNotice(e){let t=JS(e),n=e.role??XS(t),r=e.title;return g`
2707
2686
  <article class=${`notice ${t}`} role=${n}>
2708
2687
  ${r===void 0||r===``?_:g`<strong class="notice-title">${r}</strong>`}
2709
2688
  <div class="notice-content">${e.content}</div>
@@ -2736,13 +2715,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2736
2715
  .section-heading { display: grid; gap: 12px; }
2737
2716
  .heading-actions { justify-self: start; }
2738
2717
  }
2739
- `}};B([b()],sC.prototype,`heading`,void 0),B([b({attribute:!1})],sC.prototype,`description`,void 0),B([b()],sC.prototype,`actionLabel`,void 0),B([b()],sC.prototype,`actionTitle`,void 0),B([b({type:Boolean})],sC.prototype,`actionDisabled`,void 0),B([b({attribute:!1})],sC.prototype,`notices`,void 0),B([b({attribute:!1})],sC.prototype,`onAction`,void 0),sC=B([y(`settings-panel-frame`)],sC);function cC(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function lC(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function uC(){return{allowedPathsText:``,uploadDefaultFolder:``}}function dC(){return{command:``,dir:``}}function fC(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(`
2740
- `):``}}function pC(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
2741
- `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function mC(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function hC(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function gC(e,t){let n=hC(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function _C(e,t={}){let n=yC(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||bC(e.allowedHostsText),n}function vC(e){let t=xC(e.allowedPathsText),n=SC(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function yC(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.askUser===void 0?{}:{askUser:e.askUser},...e.agent===void 0?{}:{agent:e.agent}}}function bC(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function xC(e){let t=e.split(`
2742
- `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!CC(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function SC(e){let t=e.trim();if(t===``)return``;if(wC(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function CC(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function wC(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function TC(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=class extends v{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=lC(),this.machineDraft=uC(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=fC(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=pC(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
2718
+ `}};B([b()],YS.prototype,`heading`,void 0),B([b({attribute:!1})],YS.prototype,`description`,void 0),B([b()],YS.prototype,`actionLabel`,void 0),B([b()],YS.prototype,`actionTitle`,void 0),B([b({type:Boolean})],YS.prototype,`actionDisabled`,void 0),B([b({attribute:!1})],YS.prototype,`notices`,void 0),B([b({attribute:!1})],YS.prototype,`onAction`,void 0),YS=B([y(`settings-panel-frame`)],YS);function XS(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function ZS(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function QS(){return{allowedPathsText:``,uploadDefaultFolder:``}}function $S(){return{command:``,dir:``}}function eC(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(`
2719
+ `):``}}function tC(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
2720
+ `)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function nC(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function rC(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function iC(e,t){let n=rC(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function aC(e,t={}){let n=sC(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||cC(e.allowedHostsText),n}function oC(e){let t=lC(e.allowedPathsText),n=uC(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function sC(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.askUser===void 0?{}:{askUser:e.askUser},...e.agent===void 0?{}:{agent:e.agent}}}function cC(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function lC(e){let t=e.split(`
2721
+ `).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!dC(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function uC(e){let t=e.trim();if(t===``)return``;if(fC(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function dC(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function fC(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function pC(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var X=class extends v{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=ZS(),this.machineDraft=QS(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=eC(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=tC(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
2743
2722
  <settings-panel-frame
2744
2723
  heading="General configuration"
2745
- .description=${TC(this.targetLabel)}
2724
+ .description=${pC(this.targetLabel)}
2746
2725
  actionLabel="Reload"
2747
2726
  .actionDisabled=${this.loading||this.machineLoading}
2748
2727
  .notices=${this.panelNotices()}
@@ -2771,7 +2750,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2771
2750
  <span>Host</span>
2772
2751
  ${this.renderOverrideBadge(`host`)}
2773
2752
  </span>
2774
- <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:OC(e)})}}>
2753
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:gC(e)})}}>
2775
2754
  <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
2776
2755
  </label>
2777
2756
 
@@ -2780,7 +2759,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2780
2759
  <span>Port</span>
2781
2760
  ${this.renderOverrideBadge(`port`)}
2782
2761
  </span>
2783
- <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:OC(e)})}}>
2762
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:gC(e)})}}>
2784
2763
  <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
2785
2764
  </label>
2786
2765
 
@@ -2789,11 +2768,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2789
2768
  <span>Allowed hosts</span>
2790
2769
  ${this.renderOverrideBadge(`allowedHosts`)}
2791
2770
  </span>
2792
- <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:kC(e)===`all`?`all`:`list`})}}>
2771
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:_C(e)===`all`?`all`:`list`})}}>
2793
2772
  <option value="list">Only listed hosts</option>
2794
2773
  <option value="all">Allow every host</option>
2795
2774
  </select>
2796
- <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:AC(e)})}}></textarea>
2775
+ <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:vC(e)})}}></textarea>
2797
2776
  <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
2798
2777
  </div>
2799
2778
 
@@ -2823,7 +2802,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2823
2802
  <span class="field-heading">
2824
2803
  <span>External filesystem roots</span>
2825
2804
  </span>
2826
- <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:AC(e)})}}></textarea>
2805
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:vC(e)})}}></textarea>
2827
2806
  <small>Allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace on ${this.targetLabel}. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
2828
2807
  </label>
2829
2808
 
@@ -2831,7 +2810,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2831
2810
  <span class="field-heading">
2832
2811
  <span>Default upload folder</span>
2833
2812
  </span>
2834
- <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Xa} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:OC(e)})}}>
2813
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Xa} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:gC(e)})}}>
2835
2814
  <small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEB's default <code>${Xa}</code>.</small>
2836
2815
  </label>
2837
2816
 
@@ -2849,18 +2828,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2849
2828
  <dl>
2850
2829
  <div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
2851
2830
  <div><dt>Port</dt><dd>${e.port??g`<span class="muted">8504 default</span>`}</dd></div>
2852
- <div><dt>Allowed hosts</dt><dd>${EC(e.allowedHosts)}</dd></div>
2831
+ <div><dt>Allowed hosts</dt><dd>${mC(e.allowedHosts)}</dd></div>
2853
2832
  </dl>
2854
2833
  </section>
2855
2834
  `}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
2856
2835
  <section class="effective-card" aria-label="Effective selected machine file access and upload summary">
2857
2836
  <h3>Effective selected-machine settings</h3>
2858
2837
  <dl>
2859
- <div><dt>External roots</dt><dd>${DC(e.pathAccess?.allowedPaths)}</dd></div>
2838
+ <div><dt>External roots</dt><dd>${hC(e.pathAccess?.allowedPaths)}</dd></div>
2860
2839
  <div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-web/uploads`} default</span>`}</dd></div>
2861
2840
  </dl>
2862
2841
  </section>
2863
- `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(_C(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=jC(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(vC(this.machineDraft))}catch(e){this.machineLocalError=jC(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
2842
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(aC(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=yC(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(oC(this.machineDraft))}catch(e){this.machineLocalError=yC(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
2864
2843
  :host { display: block; }
2865
2844
  .card-heading { display: grid; gap: 6px; min-width: 0; }
2866
2845
  h3, p { margin: 0; }
@@ -2899,10 +2878,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2899
2878
  @media (max-width: 760px) {
2900
2879
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
2901
2880
  }
2902
- `}};B([b({attribute:!1})],Y.prototype,`configResponse`,void 0),B([b({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),B([b({type:Boolean})],Y.prototype,`loading`,void 0),B([b({type:Boolean})],Y.prototype,`machineLoading`,void 0),B([b({type:Boolean})],Y.prototype,`saving`,void 0),B([b()],Y.prototype,`error`,void 0),B([b()],Y.prototype,`machineError`,void 0),B([b()],Y.prototype,`savedMessage`,void 0),B([b()],Y.prototype,`targetLabel`,void 0),B([b({attribute:!1})],Y.prototype,`onReload`,void 0),B([b({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),B([b({attribute:!1})],Y.prototype,`onSave`,void 0),B([b({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),B([x()],Y.prototype,`gatewayDraft`,void 0),B([x()],Y.prototype,`machineDraft`,void 0),B([x()],Y.prototype,`gatewayLocalError`,void 0),B([x()],Y.prototype,`machineLocalError`,void 0),Y=B([y(`settings-general-panel`)],Y);function EC(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function DC(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function OC(e){return e.target instanceof HTMLInputElement?e.target.value:``}function kC(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function AC(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function jC(e){return e instanceof Error?e.message:String(e)}function MC(e){return{spawnSessions:e}}function NC(e){return{subsessions:e}}function PC(e){return{askUser:e}}function FC(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEB_AGENT_SESSION_DIR`,...Mt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&RC(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function IC(e,t){return e?.agentDirSource===`pi-web`?!0:e?.agentDirSource===`pi-compatibility`?Mt(t.trim()||`pi`):e?.agentDir===!0}function LC(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function RC(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var zC=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentProfileSupport={state:`supported`},this.agentDraft=dC(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=dC(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||gC(this.agentDraft,this.configResponse.config))&&(this.agentDraft=mC(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.effectiveConfig.askUser!==void 0,o=e?.envOverrides.askUser===!0,s=e?.effectiveConfig.askUser===!0,c=e?.envOverrides.agentCommand===!0,l=this.agentProfileSupport.state===`supported`,u=c?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,d=IC(e?.envOverrides,u),f=e?.envOverrides.agentDir===!0,p=e?.effectiveConfig.agent,m=FC(e,this.activeAgentProfile);return g`
2881
+ `}};B([b({attribute:!1})],X.prototype,`configResponse`,void 0),B([b({attribute:!1})],X.prototype,`machineConfigResponse`,void 0),B([b({type:Boolean})],X.prototype,`loading`,void 0),B([b({type:Boolean})],X.prototype,`machineLoading`,void 0),B([b({type:Boolean})],X.prototype,`saving`,void 0),B([b()],X.prototype,`error`,void 0),B([b()],X.prototype,`machineError`,void 0),B([b()],X.prototype,`savedMessage`,void 0),B([b()],X.prototype,`targetLabel`,void 0),B([b({attribute:!1})],X.prototype,`onReload`,void 0),B([b({attribute:!1})],X.prototype,`onReloadMachine`,void 0),B([b({attribute:!1})],X.prototype,`onSave`,void 0),B([b({attribute:!1})],X.prototype,`onSaveMachineConfig`,void 0),B([x()],X.prototype,`gatewayDraft`,void 0),B([x()],X.prototype,`machineDraft`,void 0),B([x()],X.prototype,`gatewayLocalError`,void 0),B([x()],X.prototype,`machineLocalError`,void 0),X=B([y(`settings-general-panel`)],X);function mC(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function hC(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function gC(e){return e.target instanceof HTMLInputElement?e.target.value:``}function _C(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function vC(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function yC(e){return e instanceof Error?e.message:String(e)}function bC(e){return{spawnSessions:e}}function xC(e){return{subsessions:e}}function SC(e){return{askUser:e}}function CC(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEB_AGENT_SESSION_DIR`,...Nt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&EC(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function wC(e,t){return e?.agentDirSource===`pi-web`||e?.agentDirSource===`pi-compatibility`&&Nt(t.trim()||`pi`)}function TC(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function EC(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var DC=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentDraft=$S(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=$S(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||iC(this.agentDraft,this.configResponse.config))&&(this.agentDraft=nC(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.envOverrides.askUser===!0,o=e?.effectiveConfig.askUser===!0,s=e?.envOverrides.agentCommand===!0,c=s?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,l=wC(e?.envOverrides,c),u=e?.envOverrides.agentDir===!0,d=e?.effectiveConfig.agent,f=CC(e,this.activeAgentProfile);return g`
2903
2882
  <settings-panel-frame
2904
2883
  heading="Session daemon"
2905
- .description=${UC(this.targetLabel)}
2884
+ .description=${jC(this.targetLabel)}
2906
2885
  actionLabel="Reload"
2907
2886
  .actionDisabled=${this.loading}
2908
2887
  .notices=${this.panelNotices(e)}
@@ -2914,11 +2893,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2914
2893
  <code>${e.path}</code>
2915
2894
  </div>
2916
2895
  <form class="profile-form" aria-label="Pi-compatible agent profile" @submit=${e=>{this.saveAgentProfile(e)}}>
2917
- ${l?null:g`<div class="profile-support-message">${this.agentProfileSupport.message??`Pi-compatible agent profile editing is unavailable for this machine.`}</div>`}
2918
2896
  <label class="field">
2919
2897
  <span class="field-heading">
2920
2898
  <span>Companion CLI command</span>
2921
- ${c?g`<span class="override-badge">environment override</span>`:null}
2899
+ ${s?g`<span class="override-badge">environment override</span>`:null}
2922
2900
  </span>
2923
2901
  <input
2924
2902
  class="text-input"
@@ -2927,15 +2905,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2927
2905
  spellcheck="false"
2928
2906
  .value=${this.agentDraft.command}
2929
2907
  placeholder="pi"
2930
- ?disabled=${this.loading||this.saving||!l||c}
2931
- @input=${e=>{this.updateAgentDraft({command:VC(e)})}}
2908
+ ?disabled=${this.loading||this.saving||s}
2909
+ @input=${e=>{this.updateAgentDraft({command:kC(e)})}}
2932
2910
  >
2933
2911
  <small>Set the Pi-compatible companion CLI used for doctor and update checks. The embedded session runtime remains PI WEB's bundled Pi SDK.</small>
2934
2912
  </label>
2935
2913
  <label class="field">
2936
2914
  <span class="field-heading">
2937
2915
  <span>Profile state directory</span>
2938
- ${f?g`<span class="override-badge">environment override</span>`:null}
2916
+ ${u?g`<span class="override-badge">environment override</span>`:null}
2939
2917
  </span>
2940
2918
  <input
2941
2919
  class="text-input"
@@ -2944,13 +2922,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2944
2922
  spellcheck="false"
2945
2923
  .value=${this.agentDraft.dir}
2946
2924
  placeholder="~/.pi/agent or ~/agent-profiles/work"
2947
- ?disabled=${this.loading||this.saving||!l||d}
2948
- @input=${e=>{this.updateAgentDraft({dir:VC(e)})}}
2925
+ ?disabled=${this.loading||this.saving||l}
2926
+ @input=${e=>{this.updateAgentDraft({dir:kC(e)})}}
2949
2927
  >
2950
2928
  <small>Choose the Pi-compatible auth, models, settings, and sessions PI WEB reads. An alternate command and its required state directory are saved together.</small>
2951
2929
  </label>
2952
2930
  <footer class="form-actions">
2953
- <button class="primary" type="submit" ?disabled=${this.loading||this.saving||!l||c&&d}>${this.saving?`Saving…`:`Save agent profile`}</button>
2931
+ <button class="primary" type="submit" ?disabled=${this.loading||this.saving||s&&l}>${this.saving?`Saving…`:`Save agent profile`}</button>
2954
2932
  </footer>
2955
2933
  </form>
2956
2934
  <div class="field">
@@ -2989,46 +2967,45 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
2989
2967
  <div class="field">
2990
2968
  <span class="field-heading">
2991
2969
  <span>Allow agents to ask questions</span>
2992
- ${o?g`<span class="override-badge">environment override</span>`:null}
2970
+ ${a?g`<span class="override-badge">environment override</span>`:null}
2993
2971
  </span>
2994
2972
  <label class="toggle">
2995
2973
  <input
2996
2974
  type="checkbox"
2997
2975
  aria-label="Enable Ask Questions"
2998
- .checked=${s}
2999
- ?disabled=${this.loading||this.saving||o||!a}
2976
+ .checked=${o}
2977
+ ?disabled=${this.loading||this.saving||a}
3000
2978
  @change=${e=>{this.toggleAskUser(e)}}
3001
2979
  >
3002
2980
  <span>Enable the <code>ask_user</code> tool</span>
3003
2981
  </label>
3004
- <small>${a?g`Agents can post a structured question form and pause until the user responds. On by default.`:g`This machine does not expose the Ask Questions setting. Update and restart PI WEB on that machine to configure it.`}</small>
2982
+ <small>Agents can post a structured question form and pause until the user responds. On by default.</small>
3005
2983
  </div>
3006
2984
  <section class="effective-card" aria-label="Desired and active session daemon configuration summary">
3007
2985
  <h3>Desired after environment overrides</h3>
3008
2986
  <dl>
3009
- <div><dt>Desired command</dt><dd>${p?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
3010
- <div><dt>Desired state</dt><dd>${p?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
2987
+ <div><dt>Desired command</dt><dd>${d?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
2988
+ <div><dt>Desired state</dt><dd>${d?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
3011
2989
  <div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
3012
2990
  <div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
3013
- <div><dt>Profile status</dt><dd>${BC(m)}</dd></div>
2991
+ <div><dt>Profile status</dt><dd>${OC(f)}</dd></div>
3014
2992
  <div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
3015
2993
  <div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
3016
- <div><dt>Ask questions</dt><dd>${a?s?`Enabled`:g`<span class="muted">Disabled</span>`:g`<span class="muted">Unavailable</span>`}</dd></div>
2994
+ <div><dt>Ask questions</dt><dd>${o?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
3017
2995
  </dl>
3018
2996
  </section>
3019
2997
  `}
3020
2998
  </settings-panel-frame>
3021
- `}panelNotices(e){return WC(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel,profileEditingSupported:this.agentProfileSupport.state===`supported`})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(hC(this.agentDraft))}catch(e){this.agentLocalError=HC(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(MC(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(NC(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(PC(t))}static{this.styles=h`
2999
+ `}panelNotices(e){return MC(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(rC(this.agentDraft))}catch(e){this.agentLocalError=AC(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(bC(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(xC(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(SC(t))}static{this.styles=h`
3022
3000
  :host { display: block; }
3023
3001
  h3 { margin: 0; font-size: 13px; line-height: 1.3; }
3024
3002
  button, input { font: inherit; }
3025
3003
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
3026
3004
  button:disabled { opacity: .55; cursor: not-allowed; }
3027
- .loading-card, .config-path-card, .effective-card, .profile-support-message { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
3005
+ .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
3028
3006
  .loading-card { color: var(--pi-muted); }
3029
3007
  .config-path-card { display: grid; gap: 5px; }
3030
3008
  .profile-form { display: grid; gap: 14px; }
3031
- .profile-support-message { color: var(--pi-muted); line-height: 1.45; }
3032
3009
  .form-actions { display: flex; justify-content: flex-end; }
3033
3010
  .primary { border-color: var(--pi-accent); background: var(--pi-accent); color: var(--pi-accent-contrast); }
3034
3011
  .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
@@ -3064,19 +3041,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3064
3041
  @media (max-width: 760px) {
3065
3042
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
3066
3043
  }
3067
- `}};B([b({attribute:!1})],zC.prototype,`configResponse`,void 0),B([b({type:Boolean})],zC.prototype,`loading`,void 0),B([b({type:Boolean})],zC.prototype,`saving`,void 0),B([b()],zC.prototype,`error`,void 0),B([b()],zC.prototype,`savedMessage`,void 0),B([b()],zC.prototype,`targetLabel`,void 0),B([b({attribute:!1})],zC.prototype,`activeAgentProfile`,void 0),B([b({attribute:!1})],zC.prototype,`agentProfileSupport`,void 0),B([b({attribute:!1})],zC.prototype,`onReload`,void 0),B([b({attribute:!1})],zC.prototype,`onSave`,void 0),B([x()],zC.prototype,`agentDraft`,void 0),B([x()],zC.prototype,`agentDraftDirty`,void 0),B([x()],zC.prototype,`agentLocalError`,void 0),zC=B([y(`settings-sessiond-panel`)],zC);function BC(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function VC(e){return e.target instanceof HTMLInputElement?e.target.value:``}function HC(e){return e instanceof Error?e.message:String(e)}function UC(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function WC(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=FC(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-web restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&t.profileEditingSupported&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEB cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function GC(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function KC(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function qC(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:XC(e)}:{state:`unknown`}}function JC(e){return`${e.state}:${e.message??``}`}function YC(e){return e?.state===`unsupported`}function XC(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function ZC(e){return e.kind===`local`}function QC(e){return e.trim()}function $C(e){if(QC(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function ew(e){return e.scope===`project`?`Project scope`:`User scope`}function tw(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEB process`}function nw(e){return e.installedPath??`Installed path not reported by Pi`}function rw(e){return e.scope===`user`}function iw(e){if(!rw(e))return`Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view.`}function aw(e){return e.length>0&&e.every(rw)}function ow(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!aw(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function sw(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function cw(e,t=GC(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEB session`:`each idle PI WEB session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEB browser plugin changes`:`PI WEB browser plugin changes served by ${t.name}`}.`}function lw(e,t){let n=e.trim();return t.kind===`remote`?uw(n)?XC(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}function uw(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var dw=class extends v{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=KC(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
3044
+ `}};B([b({attribute:!1})],DC.prototype,`configResponse`,void 0),B([b({type:Boolean})],DC.prototype,`loading`,void 0),B([b({type:Boolean})],DC.prototype,`saving`,void 0),B([b()],DC.prototype,`error`,void 0),B([b()],DC.prototype,`savedMessage`,void 0),B([b()],DC.prototype,`targetLabel`,void 0),B([b({attribute:!1})],DC.prototype,`activeAgentProfile`,void 0),B([b({attribute:!1})],DC.prototype,`onReload`,void 0),B([b({attribute:!1})],DC.prototype,`onSave`,void 0),B([x()],DC.prototype,`agentDraft`,void 0),B([x()],DC.prototype,`agentDraftDirty`,void 0),B([x()],DC.prototype,`agentLocalError`,void 0),DC=B([y(`settings-sessiond-panel`)],DC);function OC(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function kC(e){return e.target instanceof HTMLInputElement?e.target.value:``}function AC(e){return e instanceof Error?e.message:String(e)}function jC(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function MC(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=CC(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-web restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEB cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function NC(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function PC(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function FC(e){return e.kind===`local`}function IC(e){return e.trim()}function LC(e){if(IC(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function RC(e){return e.scope===`project`?`Project scope`:`User scope`}function zC(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEB process`}function BC(e){return e.installedPath??`Installed path not reported by Pi`}function VC(e){return e.scope===`user`}function HC(e){if(!VC(e))return`Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view.`}function UC(e){return e.length>0&&e.every(VC)}function WC(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!UC(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function GC(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function KC(e,t=NC(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEB session`:`each idle PI WEB session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEB browser plugin changes`:`PI WEB browser plugin changes served by ${t.name}`}.`}function qC(e,t){let n=e.trim();return t.kind===`remote`?n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}var JC=class extends v{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=PC(t),r=this.packagesResponse!==void 0;return g`
3068
3045
  <settings-panel-frame
3069
3046
  heading="Pi packages"
3070
- .description=${fw(n)}
3047
+ .description=${YC(n)}
3071
3048
  actionLabel="Reload"
3072
- actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
3073
- .actionDisabled=${this.loading||this.isOperating||r}
3074
- .notices=${this.panelNotices(n,i)}
3049
+ actionTitle=${`Reload Pi packages from ${n}`}
3050
+ .actionDisabled=${this.loading||this.isOperating}
3051
+ .notices=${this.panelNotices(r)}
3075
3052
  .onAction=${this.onReload}
3076
3053
  >
3077
3054
  ${this.renderPanelContent(e,t,n)}
3078
3055
  </settings-panel-frame>
3079
- `}panelNotices(e,t){let n=[];return this.packageManagementUnavailable?n.push({type:`availability`,content:this.packageManagementUnavailableMessage(e)}):this.error!==``&&n.push({type:`error`,content:this.error}),this.operationMessage!==``&&n.push({type:`success`,content:this.operationMessage}),t&&n.push({type:`security`,content:g`<strong>Trusted code warning:</strong> Pi packages and PI WEB plugins can run with your user permissions. Install packages and enable plugins only from sources you trust.`}),n}renderPanelContent(e,t,n){return this.packageManagementUnavailable?null:this.packagesResponse===void 0?g`<div class="loading-card">${this.loading?`Loading Pi packages from ${n}…`:`Pi package list unavailable for ${n}. Use Reload to try again.`}</div>`:g`
3056
+ `}panelNotices(e){let t=[];return this.error!==``&&t.push({type:`error`,content:this.error}),this.operationMessage!==``&&t.push({type:`success`,content:this.operationMessage}),e&&t.push({type:`security`,content:g`<strong>Trusted code warning:</strong> Pi packages and PI WEB plugins can run with your user permissions. Install packages and enable plugins only from sources you trust.`}),t}renderPanelContent(e,t,n){return this.packagesResponse===void 0?g`<div class="loading-card">${this.loading?`Loading Pi packages from ${n}…`:`Pi package list unavailable for ${n}. Use Reload to try again.`}</div>`:g`
3080
3057
  ${this.renderInstallForm(n)}
3081
3058
  ${this.renderPackageList(e,t)}
3082
3059
  `}renderInstallForm(e){return g`
@@ -3084,12 +3061,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3084
3061
  <label for="package-source">Pi package source</label>
3085
3062
  <div class="install-row">
3086
3063
  <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
3087
- <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${sw(this.operation,`install`)?`Installing…`:`Install`}</button>
3064
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${GC(this.operation,`install`)?`Installing…`:`Install`}</button>
3088
3065
  </div>
3089
3066
  ${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
3090
3067
  <small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install &lt;source&gt;</code>. PI WEB does not ask you to choose an install location.</small>
3091
3068
  </form>
3092
- `}renderPackageList(e,t){let n=KC(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):ow(e),i=r!==void 0&&e.length>0;return g`
3069
+ `}renderPackageList(e,t){let n=PC(t),r=WC(e),i=r!==void 0&&e.length>0;return g`
3093
3070
  <section class="package-section" aria-label="Configured Pi packages">
3094
3071
  <div class="package-toolbar">
3095
3072
  <div>
@@ -3097,7 +3074,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3097
3074
  <p>This list comes from Pi's package manager settings on ${n}.</p>
3098
3075
  </div>
3099
3076
  <button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
3100
- ${sw(this.operation,`update-all`)?`Updating…`:`Update all`}
3077
+ ${GC(this.operation,`update-all`)?`Updating…`:`Update all`}
3101
3078
  </button>
3102
3079
  </div>
3103
3080
  ${i?g`<div class="action-note">${r}</div>`:null}
@@ -3108,20 +3085,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3108
3085
  <div class="package-list">
3109
3086
  ${e.map(e=>this.renderPackage(e))}
3110
3087
  </div>
3111
- `}renderPackage(e){let t=KC(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):iw(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=sw(this.operation,`update`,e.source),o=sw(this.operation,`remove`,e.source);return g`
3088
+ `}renderPackage(e){let t=HC(e),n=GC(this.operation,`update`,e.source),r=GC(this.operation,`remove`,e.source);return g`
3112
3089
  <article class=${`package-card${e.filtered?` filtered`:``}`}>
3113
3090
  <div class="package-main">
3114
3091
  <strong>${e.source}</strong>
3115
- <small>${ew(e)} · ${tw(e)}</small>
3116
- <small>Installed path: <code>${nw(e)}</code></small>
3117
- ${r===void 0?null:g`<small class="action-note">${r}</small>`}
3092
+ <small>${RC(e)} · ${zC(e)}</small>
3093
+ <small>Installed path: <code>${BC(e)}</code></small>
3094
+ ${t===void 0?null:g`<small class="action-note">${t}</small>`}
3118
3095
  </div>
3119
3096
  <div class="package-actions">
3120
- <button class="secondary" title=${r??`Update this Pi package`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage(e.source)}}>${a?`Updating…`:`Update`}</button>
3121
- <button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
3097
+ <button class="secondary" title=${t??`Update this Pi package`} ?disabled=${this.isOperating||t!==void 0} @click=${()=>{this.updatePackage(e.source)}}>${n?`Updating…`:`Update`}</button>
3098
+ <button class="danger" title="Remove this Pi package" ?disabled=${this.isOperating} @click=${()=>{this.removePackage(e)}}>${r?`Removing…`:`Remove`}</button>
3122
3099
  </div>
3123
3100
  </article>
3124
- `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=$C(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=QC(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??GC(void 0)}get packageManagementUnavailable(){return YC(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
3101
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=LC(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=IC(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??NC(void 0)}get isOperating(){return this.operation!==void 0}static{this.styles=h`
3125
3102
  :host { display: block; }
3126
3103
  .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
3127
3104
  .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
@@ -3156,10 +3133,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3156
3133
  .package-actions { justify-self: start; flex-wrap: wrap; }
3157
3134
  .package-main strong, .package-main small { white-space: normal; }
3158
3135
  }
3159
- `}};B([b({attribute:!1})],dw.prototype,`packagesResponse`,void 0),B([b({type:Boolean})],dw.prototype,`loading`,void 0),B([b({attribute:!1})],dw.prototype,`operation`,void 0),B([b({attribute:!1})],dw.prototype,`targetMachine`,void 0),B([b({attribute:!1})],dw.prototype,`managementSupport`,void 0),B([b()],dw.prototype,`error`,void 0),B([b()],dw.prototype,`operationMessage`,void 0),B([b({attribute:!1})],dw.prototype,`onReload`,void 0),B([b({attribute:!1})],dw.prototype,`onInstallPackage`,void 0),B([b({attribute:!1})],dw.prototype,`onRemovePackage`,void 0),B([b({attribute:!1})],dw.prototype,`onUpdatePackage`,void 0),B([x()],dw.prototype,`installSource`,void 0),B([x()],dw.prototype,`validationMessage`,void 0),dw=B([y(`settings-packages-panel`)],dw);function fw(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEB browser plugins.`}var pw=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
3136
+ `}};B([b({attribute:!1})],JC.prototype,`packagesResponse`,void 0),B([b({type:Boolean})],JC.prototype,`loading`,void 0),B([b({attribute:!1})],JC.prototype,`operation`,void 0),B([b({attribute:!1})],JC.prototype,`targetMachine`,void 0),B([b()],JC.prototype,`error`,void 0),B([b()],JC.prototype,`operationMessage`,void 0),B([b({attribute:!1})],JC.prototype,`onReload`,void 0),B([b({attribute:!1})],JC.prototype,`onInstallPackage`,void 0),B([b({attribute:!1})],JC.prototype,`onRemovePackage`,void 0),B([b({attribute:!1})],JC.prototype,`onUpdatePackage`,void 0),B([x()],JC.prototype,`installSource`,void 0),B([x()],JC.prototype,`validationMessage`,void 0),JC=B([y(`settings-packages-panel`)],JC);function YC(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEB browser plugins.`}var XC=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
3160
3137
  <settings-panel-frame
3161
3138
  heading="PI WEB plugins"
3162
- .description=${mw(this.targetLabel)}
3139
+ .description=${ZC(this.targetLabel)}
3163
3140
  actionLabel="Reload"
3164
3141
  actionTitle=${`Reload PI WEB plugins from ${this.targetLabel}`}
3165
3142
  .actionDisabled=${this.loading}
@@ -3205,10 +3182,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3205
3182
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
3206
3183
  .toggle { justify-self: start; }
3207
3184
  }
3208
- `}};B([b({attribute:!1})],pw.prototype,`pluginsResponse`,void 0),B([b({attribute:!1})],pw.prototype,`configResponse`,void 0),B([b({type:Boolean})],pw.prototype,`loading`,void 0),B([b({type:Boolean})],pw.prototype,`saving`,void 0),B([b()],pw.prototype,`error`,void 0),B([b()],pw.prototype,`savedMessage`,void 0),B([b()],pw.prototype,`targetLabel`,void 0),B([b({attribute:!1})],pw.prototype,`onReload`,void 0),B([b({attribute:!1})],pw.prototype,`onTogglePlugin`,void 0),pw=B([y(`settings-plugins-panel`)],pw);function mw(e){return g`Enable or disable discovered PI WEB browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}var hw={capture:!0},gw=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function _w(){return g`Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.`}var vw=class extends v{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=fS(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=nf(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!rf(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=Sw(this.actions),t=this.shortcutResolutions();return g`
3185
+ `}};B([b({attribute:!1})],XC.prototype,`pluginsResponse`,void 0),B([b({attribute:!1})],XC.prototype,`configResponse`,void 0),B([b({type:Boolean})],XC.prototype,`loading`,void 0),B([b({type:Boolean})],XC.prototype,`saving`,void 0),B([b()],XC.prototype,`error`,void 0),B([b()],XC.prototype,`savedMessage`,void 0),B([b()],XC.prototype,`targetLabel`,void 0),B([b({attribute:!1})],XC.prototype,`onReload`,void 0),B([b({attribute:!1})],XC.prototype,`onTogglePlugin`,void 0),XC=B([y(`settings-plugins-panel`)],XC);function ZC(e){return g`Enable or disable discovered PI WEB browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}var QC={capture:!0},$C=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function ew(){return g`Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.`}var tw=class extends v{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=$x(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=Jd(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!Yd(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=aw(this.actions),t=this.shortcutResolutions();return g`
3209
3186
  <settings-panel-frame
3210
3187
  heading="Keyboard shortcuts"
3211
- .description=${_w()}
3188
+ .description=${ew()}
3212
3189
  actionLabel="Reload"
3213
3190
  .actionDisabled=${this.loading}
3214
3191
  .notices=${this.panelNotices()}
@@ -3239,7 +3216,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3239
3216
  <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
3240
3217
  </div>
3241
3218
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
3242
- ${gw.map(e=>g`
3219
+ ${$C.map(e=>g`
3243
3220
  <label class="prompt-enter-option">
3244
3221
  <input
3245
3222
  type="radio"
@@ -3256,19 +3233,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3256
3233
  `)}
3257
3234
  </div>
3258
3235
  </section>
3259
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,pS(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=ww(e.id,n),i=Dw(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:$d(a),s=o?.ok===!0?o.shortcut:Ew(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=xw(t);return g`
3260
- <article class=${yw(t)}>
3236
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,eS(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=sw(e.id,n),i=uw(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Gd(a),s=o?.ok===!0?o.shortcut:lw(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=iw(t);return g`
3237
+ <article class=${nw(t)}>
3261
3238
  <div class="shortcut-main">
3262
3239
  <strong>${e.title}</strong>
3263
3240
  ${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
3264
3241
  <small class="shortcut-id">${e.id}</small>
3265
- <small>${e.shortcut!==void 0&&e.shortcut!==``?g`Default: <kbd>${tf(e.shortcut)}</kbd>`:`No default shortcut`}</small>
3242
+ <small>${e.shortcut!==void 0&&e.shortcut!==``?g`Default: <kbd>${qd(e.shortcut)}</kbd>`:`No default shortcut`}</small>
3266
3243
  </div>
3267
3244
  <div class="shortcut-editor">
3268
3245
  <div class="shortcut-status">
3269
- ${s!==void 0&&s!==``?g`<kbd>${tf(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
3270
- <small class=${u}>${Ow(u)}${l?` · Unsaved`:``}</small>
3271
- ${f===void 0?null:g`<small class=${bw(t)}>${f}</small>`}
3246
+ ${s!==void 0&&s!==``?g`<kbd>${qd(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
3247
+ <small class=${u}>${dw(u)}${l?` · Unsaved`:``}</small>
3248
+ ${f===void 0?null:g`<small class=${rw(t)}>${f}</small>`}
3272
3249
  </div>
3273
3250
  <label class="shortcut-input-label">
3274
3251
  <span>Shortcut</span>
@@ -3281,7 +3258,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3281
3258
  autocapitalize="off"
3282
3259
  spellcheck="false"
3283
3260
  ?disabled=${this.saving}
3284
- @input=${t=>{this.updateDraft(e.id,kw(t))}}
3261
+ @input=${t=>{this.updateDraft(e.id,fw(t))}}
3285
3262
  >
3286
3263
  </label>
3287
3264
  ${d===``?null:g`<small class="recording-hint">${d}</small>`}
@@ -3293,7 +3270,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3293
3270
  </div>
3294
3271
  </div>
3295
3272
  </article>
3296
- `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=ww(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${tf(t.tokens.join(` `))}. Press another key to add a sequence, or wait to finish.`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=$d(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?Tw(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Qd(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=$d(r);i.ok&&(e[t]=i.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError=``,this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(let t of this.renderRoot.querySelectorAll(`.shortcut-input`))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Yd)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||=(window.addEventListener(`keydown`,this.onRecordKeyDown,hw),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,hw),!1)}static{this.styles=h`
3273
+ `}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=sw(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${qd(t.tokens.join(` `))}. Press another key to add a sequence, or wait to finish.`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=Gd(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?cw(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Wd(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=Gd(r);i.ok&&(e[t]=i.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError=``,this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(let t of this.renderRoot.querySelectorAll(`.shortcut-input`))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Vd)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||=(window.addEventListener(`keydown`,this.onRecordKeyDown,QC),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,QC),!1)}static{this.styles=h`
3297
3274
  :host { display: block; }
3298
3275
  h3, p { margin: 0; }
3299
3276
  h3 { font-size: 13px; line-height: 1.3; }
@@ -3349,7 +3326,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3349
3326
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
3350
3327
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
3351
3328
  }
3352
- `}};B([b({attribute:!1})],vw.prototype,`actions`,void 0),B([b({attribute:!1})],vw.prototype,`configResponse`,void 0),B([b({type:Boolean})],vw.prototype,`loading`,void 0),B([b({type:Boolean})],vw.prototype,`saving`,void 0),B([b()],vw.prototype,`error`,void 0),B([b()],vw.prototype,`savedMessage`,void 0),B([b({attribute:!1})],vw.prototype,`onReload`,void 0),B([b({attribute:!1})],vw.prototype,`onSave`,void 0),B([x()],vw.prototype,`drafts`,void 0),B([x()],vw.prototype,`localError`,void 0),B([x()],vw.prototype,`promptEnterPreference`,void 0),B([x()],vw.prototype,`recording`,void 0),vw=B([y(`settings-shortcuts-panel`)],vw);function yw(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function bw(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function xw(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function Sw(e){let t=new Map;for(let n of[...e].sort(Cw)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function Cw(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function ww(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Tw(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Ew(e,t){let n=ww(e.id,t);if(n!==null)return n??e.shortcut}function Dw(e,t){let n=ww(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function Ow(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function kw(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function Aw(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${Mw(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB plugins: ${Mw(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function jw(e,t,n){if(YC(n))return{error:n.message??`Pi package management is not available on ${KC(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${KC(e)}: ${lw(Mw(t),e)}`}}}function Mw(e){return e instanceof Error?e.message:String(e)}function Nw(e,t){return{...e,config:Pw(e.config,t.config),effectiveConfig:Pw(e.effectiveConfig,t.effectiveConfig)}}function Pw(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function Fw(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function X(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function Iw(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:Vw(e)}:{state:`unknown`}}function Lw(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`Pi-compatible agent profile settings are not available on ${e.name}. Update and restart PI WEB on that machine, then try again.`}:{state:`unknown`,message:`Pi-compatible agent profile support could not be verified on ${e.name}. Reload machine status before changing the profile.`}}function Rw(e){return`${e.state}:${e.message??``}`}function zw(e){return e?.state===`unsupported`}function Bw(e){return e?.state===`supported`}function Vw(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEB on that machine, then try again.`}function Hw(e,t){let n=e.trim();return t.kind===`remote`?Uw(n)?Vw(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function Uw(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function Ww(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function Gw(e,t){return{...e,config:Kw(e.config,t.config),effectiveConfig:Kw(e.effectiveConfig,t.effectiveConfig)}}function Kw(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var Z=class extends v{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&Fw(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
3329
+ `}};B([b({attribute:!1})],tw.prototype,`actions`,void 0),B([b({attribute:!1})],tw.prototype,`configResponse`,void 0),B([b({type:Boolean})],tw.prototype,`loading`,void 0),B([b({type:Boolean})],tw.prototype,`saving`,void 0),B([b()],tw.prototype,`error`,void 0),B([b()],tw.prototype,`savedMessage`,void 0),B([b({attribute:!1})],tw.prototype,`onReload`,void 0),B([b({attribute:!1})],tw.prototype,`onSave`,void 0),B([x()],tw.prototype,`drafts`,void 0),B([x()],tw.prototype,`localError`,void 0),B([x()],tw.prototype,`promptEnterPreference`,void 0),B([x()],tw.prototype,`recording`,void 0),tw=B([y(`settings-shortcuts-panel`)],tw);function nw(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function rw(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function iw(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function aw(e){let t=new Map;for(let n of[...e].sort(ow)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function ow(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function sw(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function cw(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function lw(e,t){let n=sw(e.id,t);if(n!==null)return n??e.shortcut}function uw(e,t){let n=sw(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function dw(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function fw(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function pw(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${hw(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB plugins: ${hw(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function mw(e,t){try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${PC(e)}: ${qC(hw(t),e)}`}}}function hw(e){return e instanceof Error?e.message:String(e)}function gw(e,t){return{...e,config:_w(e.config,t.config),effectiveConfig:_w(e.effectiveConfig,t.effectiveConfig)}}function _w(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function vw(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function yw(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function bw(e,t){let n=e.trim();return t.kind===`remote`?n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function xw(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function Sw(e,t){return{...e,config:Cw(e.config,t.config),effectiveConfig:Cw(e.effectiveConfig,t.effectiveConfig)}}function Cw(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var Z=class extends v{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();e.has(`machine`)&&vw(e.get(`machine`)).id!==t.id&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t))}render(){return g`
3353
3330
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
3354
3331
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
3355
3332
  <header class="settings-header">
@@ -3380,9 +3357,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3380
3357
  .saving=${this.saving}
3381
3358
  .error=${this.sessiondError}
3382
3359
  .savedMessage=${this.savedMessage}
3383
- .targetLabel=${X(this.settingsTarget())}
3360
+ .targetLabel=${yw(this.settingsTarget())}
3384
3361
  .activeAgentProfile=${this.machineRuntime?.components?.sessiond.activeAgentProfile}
3385
- .agentProfileSupport=${this.agentProfileSettingsSupport()}
3386
3362
  .onReload=${()=>this.reloadSessiondState()}
3387
3363
  .onSave=${e=>this.saveSessiondConfig(e)}
3388
3364
  ></settings-sessiond-panel>
@@ -3401,7 +3377,6 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3401
3377
  <settings-packages-panel
3402
3378
  .packagesResponse=${this.packagesResponse}
3403
3379
  .targetMachine=${this.packageTarget()}
3404
- .managementSupport=${this.packageManagementSupport()}
3405
3380
  .loading=${this.packageLoading}
3406
3381
  .operation=${this.packageOperation}
3407
3382
  .error=${this.packageError}
@@ -3419,7 +3394,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3419
3394
  .saving=${this.saving}
3420
3395
  .error=${this.pluginError}
3421
3396
  .savedMessage=${this.savedMessage}
3422
- .targetLabel=${X(this.settingsTarget())}
3397
+ .targetLabel=${yw(this.settingsTarget())}
3423
3398
  .onReload=${()=>this.loadPluginsForTarget()}
3424
3399
  .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
3425
3400
  ></settings-plugins-panel>
@@ -3433,7 +3408,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3433
3408
  .error=${this.error}
3434
3409
  .machineError=${this.accessError}
3435
3410
  .savedMessage=${this.savedMessage}
3436
- .targetLabel=${X(this.settingsTarget())}
3411
+ .targetLabel=${yw(this.settingsTarget())}
3437
3412
  .onReload=${()=>this.loadConfig()}
3438
3413
  .onReloadMachine=${()=>this.loadAccessConfigForTarget()}
3439
3414
  .onSave=${e=>this.saveConfig(e)}
@@ -3444,7 +3419,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3444
3419
  <strong>${t}</strong>
3445
3420
  <small>${n}</small>
3446
3421
  </button>
3447
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await Aw({loadConfig:()=>ja.config(),loadPlugins:()=>Ma.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(zw(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${X(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await ja.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${X(e)}: ${Hw(qw(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(zw(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${X(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await ja.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${X(e)}: ${Hw(qw(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(zw(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${X(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([ja.config(e.id),Ma.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${Hw(qw(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEB plugins: ${Hw(qw(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEB plugin settings from ${X(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await jw(e,e=>Pa.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(zw(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${X(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${X(n)}. Reload before changing plugin enablement.`;return}let i=Ww(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await ja.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Gw(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEB plugin config on ${X(n)}: ${Hw(qw(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await ja.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${qw(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(zw(n)){this.accessError=n.message??`Selected-machine settings are not available on ${X(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await ja.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Nw(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${X(t)}: ${Hw(qw(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(zw(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${X(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!Bw(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${X(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await ja.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=LC(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${X(t)}: ${Hw(qw(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Pa.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Pa.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>Pa.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(YC(i))throw this.packageError=i.message??`Pi package management is not available on ${KC(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=ZC(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=cw(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${KC(n)}: ${lw(qw(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Ma.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${qw(e)}`}}async refreshPluginsForTarget(e){try{let t=await Ma.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEB plugins from ${X(e)}: ${Hw(qw(t),e)}`}}settingsTarget(){return Fw(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return Iw(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return Lw(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=Iw(t,e),r=this.selectedMachineSettingsSupport(t);return Rw(n)!==Rw(r)}packageManagementSupport(e=this.packageTarget()){return qC(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=qC(t,e),r=this.packageManagementSupport(t);return JC(n)===JC(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}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?.())}static{this.styles=h`
3422
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await pw({loadConfig:()=>ja.config(),loadPlugins:()=>Ma.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq;this.accessLoading=!0,this.accessError=``;try{let n=await ja.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${yw(e)}: ${bw(ww(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq;this.sessiondLoading=!0,this.sessiondError=``;try{let n=await ja.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${yw(e)}: ${bw(ww(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq;this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([ja.config(e.id),Ma.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${bw(ww(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEB plugins: ${bw(ww(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEB plugin settings from ${yw(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await mw(e,e=>Pa.packages(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget();if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${yw(n)}. Reload before changing plugin enablement.`;return}let r=xw(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await ja.saveConfig(r,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Sw(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEB plugin config on ${yw(n)}: ${bw(ww(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await ja.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${ww(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await ja.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=gw(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${yw(t)}: ${bw(ww(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await ja.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=TC(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${yw(t)}: ${bw(ww(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Pa.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Pa.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>Pa.update(e,t.id))}async runPiPackageMutation(e,t,n,r){if(this.saving)throw Error(`A settings operation is already running.`);let i=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(i,n))return;this.packagesResponse={packages:e.packages};let t=FC(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(i,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=KC(e.action,n)}catch(e){throw this.isCurrentPackageMutation(i,n)&&(this.packageError=`Failed to ${t} on ${PC(n)}: ${qC(ww(e),n)}`),e}finally{this.packageMutationSeq===i&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Ma.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${ww(e)}`}}async refreshPluginsForTarget(e){try{let t=await Ma.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEB plugins from ${yw(e)}: ${bw(ww(t),e)}`}}settingsTarget(){return vw(this.machine)}packageTarget(){return this.settingsTarget()}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}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?.())}static{this.styles=h`
3448
3423
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
3449
3424
  .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; }
3450
3425
  .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; }
@@ -3471,7 +3446,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3471
3446
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
3472
3447
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
3473
3448
  }
3474
- `}};B([b({attribute:!1})],Z.prototype,`section`,void 0),B([b({attribute:!1})],Z.prototype,`actions`,void 0),B([b({attribute:!1})],Z.prototype,`machine`,void 0),B([b({attribute:!1})],Z.prototype,`machineRuntime`,void 0),B([b({attribute:!1})],Z.prototype,`onNavigate`,void 0),B([b({attribute:!1})],Z.prototype,`onClose`,void 0),B([b({attribute:!1})],Z.prototype,`onConfigSaved`,void 0),B([b({attribute:!1})],Z.prototype,`onRefreshMachineRuntime`,void 0),B([x()],Z.prototype,`configResponse`,void 0),B([x()],Z.prototype,`accessConfigResponse`,void 0),B([x()],Z.prototype,`sessiondConfigResponse`,void 0),B([x()],Z.prototype,`pluginsResponse`,void 0),B([x()],Z.prototype,`selectedPluginConfigResponse`,void 0),B([x()],Z.prototype,`selectedPluginsResponse`,void 0),B([x()],Z.prototype,`packagesResponse`,void 0),B([x()],Z.prototype,`loading`,void 0),B([x()],Z.prototype,`accessLoading`,void 0),B([x()],Z.prototype,`sessiondLoading`,void 0),B([x()],Z.prototype,`pluginLoading`,void 0),B([x()],Z.prototype,`packageLoading`,void 0),B([x()],Z.prototype,`saving`,void 0),B([x()],Z.prototype,`packageOperation`,void 0),B([x()],Z.prototype,`error`,void 0),B([x()],Z.prototype,`accessError`,void 0),B([x()],Z.prototype,`sessiondError`,void 0),B([x()],Z.prototype,`pluginError`,void 0),B([x()],Z.prototype,`packageError`,void 0),B([x()],Z.prototype,`savedMessage`,void 0),B([x()],Z.prototype,`packageMessage`,void 0),Z=B([y(`settings-dialog`)],Z);function qw(e){return e instanceof Error?e.message:String(e)}var Jw=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to inspect files, Git, or terminals.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.find(e=>e.id===this.tool)??t[0];return g`
3449
+ `}};B([b({attribute:!1})],Z.prototype,`section`,void 0),B([b({attribute:!1})],Z.prototype,`actions`,void 0),B([b({attribute:!1})],Z.prototype,`machine`,void 0),B([b({attribute:!1})],Z.prototype,`machineRuntime`,void 0),B([b({attribute:!1})],Z.prototype,`onNavigate`,void 0),B([b({attribute:!1})],Z.prototype,`onClose`,void 0),B([b({attribute:!1})],Z.prototype,`onConfigSaved`,void 0),B([b({attribute:!1})],Z.prototype,`onRefreshMachineRuntime`,void 0),B([x()],Z.prototype,`configResponse`,void 0),B([x()],Z.prototype,`accessConfigResponse`,void 0),B([x()],Z.prototype,`sessiondConfigResponse`,void 0),B([x()],Z.prototype,`pluginsResponse`,void 0),B([x()],Z.prototype,`selectedPluginConfigResponse`,void 0),B([x()],Z.prototype,`selectedPluginsResponse`,void 0),B([x()],Z.prototype,`packagesResponse`,void 0),B([x()],Z.prototype,`loading`,void 0),B([x()],Z.prototype,`accessLoading`,void 0),B([x()],Z.prototype,`sessiondLoading`,void 0),B([x()],Z.prototype,`pluginLoading`,void 0),B([x()],Z.prototype,`packageLoading`,void 0),B([x()],Z.prototype,`saving`,void 0),B([x()],Z.prototype,`packageOperation`,void 0),B([x()],Z.prototype,`error`,void 0),B([x()],Z.prototype,`accessError`,void 0),B([x()],Z.prototype,`sessiondError`,void 0),B([x()],Z.prototype,`pluginError`,void 0),B([x()],Z.prototype,`packageError`,void 0),B([x()],Z.prototype,`savedMessage`,void 0),B([x()],Z.prototype,`packageMessage`,void 0),Z=B([y(`settings-dialog`)],Z);function ww(e){return e instanceof Error?e.message:String(e)}var Tw=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to inspect files, Git, or terminals.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.find(e=>e.id===this.tool)??t[0];return g`
3475
3450
  ${this.hideToolTabs?null:g`
3476
3451
  <header>
3477
3452
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -3501,32 +3476,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3501
3476
  <h2>${e.title}</h2>
3502
3477
  ${e.body===void 0?null:g`<p>${e.body}</p>`}
3503
3478
  </section>
3504
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let 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(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=em}};B([b({attribute:!1})],Jw.prototype,`workspace`,void 0),B([b({attribute:!1})],Jw.prototype,`panelContext`,void 0),B([b({attribute:!1})],Jw.prototype,`emptyState`,void 0),B([b()],Jw.prototype,`tool`,void 0),B([b({attribute:!1})],Jw.prototype,`panels`,void 0),B([b({type:Boolean})],Jw.prototype,`hideToolTabs`,void 0),B([b({attribute:!1})],Jw.prototype,`onSelectTool`,void 0),B([S(`.workspace-header-strip`)],Jw.prototype,`workspaceHeaderStrip`,void 0),B([x()],Jw.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([x()],Jw.prototype,`workspaceHeaderCanScrollRight`,void 0),Jw=B([y(`workspace-panel`)],Jw);var Yw=class extends v{constructor(...e){super(...e),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=Xw(this.machines),t=Zw(this.machine),n=$w(this.project),r=tT(this.workspace),i=rT(this.session);return g`
3479
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let 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(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Hp}};B([b({attribute:!1})],Tw.prototype,`workspace`,void 0),B([b({attribute:!1})],Tw.prototype,`panelContext`,void 0),B([b({attribute:!1})],Tw.prototype,`emptyState`,void 0),B([b()],Tw.prototype,`tool`,void 0),B([b({attribute:!1})],Tw.prototype,`panels`,void 0),B([b({type:Boolean})],Tw.prototype,`hideToolTabs`,void 0),B([b({attribute:!1})],Tw.prototype,`onSelectTool`,void 0),B([S(`.workspace-header-strip`)],Tw.prototype,`workspaceHeaderStrip`,void 0),B([x()],Tw.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([x()],Tw.prototype,`workspaceHeaderCanScrollRight`,void 0),Tw=B([y(`workspace-panel`)],Tw);var Ew=class extends v{constructor(...e){super(...e),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=Dw(this.machines),t=Ow(this.machine),n=Aw(this.project),r=Mw(this.workspace),i=Pw(this.session);return g`
3505
3480
  <nav class=${this.contextBarClass()} aria-label="Current location">
3506
3481
  <span class="context-bar-label">Location</span>
3507
3482
  <ol class="context-items" @scroll=${this.onContextScroll}>
3508
3483
  ${e?g`
3509
3484
  <li class="context-item">
3510
- <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${Qw(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
3485
+ <button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${kw(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
3511
3486
  <span class="context-kind">Machine</span>
3512
3487
  <span class="context-value">${t}</span>
3513
3488
  </button>
3514
3489
  </li>
3515
3490
  `:null}
3516
3491
  <li class="context-item">
3517
- <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${eT(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
3492
+ <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${jw(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
3518
3493
  <span class="context-kind">Project</span>
3519
3494
  <span class="context-value">${n}</span>
3520
3495
  </button>
3521
3496
  </li>
3522
3497
  <li class="context-item">
3523
- <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${nT(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
3498
+ <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${Nw(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
3524
3499
  <span class="context-kind">Workspace</span>
3525
3500
  <span class="context-value">${r}</span>
3526
3501
  </button>
3527
3502
  </li>
3528
3503
  <li class="context-item">
3529
- <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${iT(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
3504
+ <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${Fw(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
3530
3505
  <span class="context-kind">Session</span>
3531
3506
  <span class="context-value">${i}</span>
3532
3507
  </button>
@@ -3566,7 +3541,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3566
3541
  .context-kind { display: none; }
3567
3542
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
3568
3543
  button { cursor: pointer; }
3569
- `}};B([b({attribute:!1})],Yw.prototype,`machines`,void 0),B([b({attribute:!1})],Yw.prototype,`machine`,void 0),B([b({attribute:!1})],Yw.prototype,`project`,void 0),B([b({attribute:!1})],Yw.prototype,`workspace`,void 0),B([b({attribute:!1})],Yw.prototype,`session`,void 0),B([b({attribute:!1})],Yw.prototype,`refreshControl`,void 0),B([b({attribute:!1})],Yw.prototype,`onOpenSection`,void 0),B([b({attribute:!1})],Yw.prototype,`onShowActions`,void 0),B([S(`.context-items`)],Yw.prototype,`contextItems`,void 0),B([x()],Yw.prototype,`canScrollLeft`,void 0),B([x()],Yw.prototype,`canScrollRight`,void 0),Yw=B([y(`app-context-bar`)],Yw);function Xw(e){return e.length>1}function Zw(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function Qw(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function $w(e){return e?.name??`No project`}function eT(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function tT(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function nT(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function rT(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:M_(e.id)}function iT(e){return e===void 0?`No session selected`:e.path}var aT=class extends v{constructor(...e){super(...e),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(){let e=this.fallbackLabels();return g`
3544
+ `}};B([b({attribute:!1})],Ew.prototype,`machines`,void 0),B([b({attribute:!1})],Ew.prototype,`machine`,void 0),B([b({attribute:!1})],Ew.prototype,`project`,void 0),B([b({attribute:!1})],Ew.prototype,`workspace`,void 0),B([b({attribute:!1})],Ew.prototype,`session`,void 0),B([b({attribute:!1})],Ew.prototype,`refreshControl`,void 0),B([b({attribute:!1})],Ew.prototype,`onOpenSection`,void 0),B([b({attribute:!1})],Ew.prototype,`onShowActions`,void 0),B([S(`.context-items`)],Ew.prototype,`contextItems`,void 0),B([x()],Ew.prototype,`canScrollLeft`,void 0),B([x()],Ew.prototype,`canScrollRight`,void 0),Ew=B([y(`app-context-bar`)],Ew);function Dw(e){return e.length>1}function Ow(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function kw(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function Aw(e){return e?.name??`No project`}function jw(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function Mw(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function Nw(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function Pw(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:b_(e.id)}function Fw(e){return e===void 0?`No session selected`:e.path}var Iw=class extends v{constructor(...e){super(...e),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(){let e=this.fallbackLabels();return g`
3570
3545
  <div class=${this.frameClass()}>
3571
3546
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
3572
3547
  ${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
@@ -3578,7 +3553,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3578
3553
  `})}
3579
3554
  </div>
3580
3555
  </div>
3581
- `}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){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:g`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?g`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Yp(e.icon)}fallbackLabels(){let e=this.tabs.filter(e=>e.icon===void 0),t=new Map;for(let n of e){let e=this.initialsLabel(n.label);t.set(e,(t.get(e)??0)+1)}let n=new Map;for(let r of e){let e=this.initialsLabel(r.label);n.set(r.id,(t.get(e)??0)>1?this.fullFallbackLabel(r.label):e)}return n}initialsLabel(e){let t=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(e=>Array.from(e)[0]??``).join(``).toLocaleUpperCase();return t===``?`?`:t}fullFallbackLabel(e){let t=e.trim();return t===``?`?`:t}observeMobileTabs(){let 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(){let e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==n&&(this.canScrollLeft=n),this.canScrollRight!==r&&(this.canScrollRight=r)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=h`
3556
+ `}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){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:g`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?g`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Lp(e.icon)}fallbackLabels(){let e=this.tabs.filter(e=>e.icon===void 0),t=new Map;for(let n of e){let e=this.initialsLabel(n.label);t.set(e,(t.get(e)??0)+1)}let n=new Map;for(let r of e){let e=this.initialsLabel(r.label);n.set(r.id,(t.get(e)??0)>1?this.fullFallbackLabel(r.label):e)}return n}initialsLabel(e){let t=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(e=>Array.from(e)[0]??``).join(``).toLocaleUpperCase();return t===``?`?`:t}fullFallbackLabel(e){let t=e.trim();return t===``?`?`:t}observeMobileTabs(){let 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(){let e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==n&&(this.canScrollLeft=n),this.canScrollRight!==r&&(this.canScrollRight=r)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=h`
3582
3557
  :host { flex: 0 0 auto; min-width: 0; }
3583
3558
  .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); }
3584
3559
  .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; }
@@ -3605,12 +3580,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3605
3580
  .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; }
3606
3581
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
3607
3582
  }
3608
- `}};B([b({attribute:!1})],aT.prototype,`tabs`,void 0),B([b({attribute:!1})],aT.prototype,`selectedView`,void 0),B([b({attribute:!1})],aT.prototype,`onSelect`,void 0),B([S(`.mobile-tabs`)],aT.prototype,`mobileTabs`,void 0),B([x()],aT.prototype,`canScrollLeft`,void 0),B([x()],aT.prototype,`canScrollRight`,void 0),aT=B([y(`app-mobile-main-tabs`)],aT);var oT=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.open=!1,this.menuStyle=``,this.actionMenuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has(`machines`)&&this.openActionsMachineId!==void 0&&!this.machines.some(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=sT(e,this.statuses),n=e.name;return g`
3583
+ `}};B([b({attribute:!1})],Iw.prototype,`tabs`,void 0),B([b({attribute:!1})],Iw.prototype,`selectedView`,void 0),B([b({attribute:!1})],Iw.prototype,`onSelect`,void 0),B([S(`.mobile-tabs`)],Iw.prototype,`mobileTabs`,void 0),B([x()],Iw.prototype,`canScrollLeft`,void 0),B([x()],Iw.prototype,`canScrollRight`,void 0),Iw=B([y(`app-mobile-main-tabs`)],Iw);var Lw=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.open=!1,this.menuStyle=``,this.actionMenuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has(`machines`)&&this.openActionsMachineId!==void 0&&!this.machines.some(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=Rw(e,this.statuses),n=e.name;return g`
3609
3584
  <div class="machine-switcher">
3610
3585
  <button
3611
3586
  type="button"
3612
3587
  class="machine-switcher-button"
3613
- title=${lT(e)}
3588
+ title=${Bw(e)}
3614
3589
  aria-label=${this.machineSwitcherAriaLabel(e)}
3615
3590
  aria-expanded=${String(this.open)}
3616
3591
  @click=${e=>{this.toggleMenu(e.currentTarget)}}
@@ -3621,7 +3596,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3621
3596
  <span class="machine-switcher-kicker">Machine</span>
3622
3597
  <span class="machine-switcher-label">${n}</span>
3623
3598
  </span>
3624
- <span class=${`machine-status ${t}`}>${cT(t)}</span>
3599
+ <span class=${`machine-status ${t}`}>${zw(t)}</span>
3625
3600
  <span class="machine-chevron" aria-hidden="true">▾</span>
3626
3601
  </button>
3627
3602
  ${this.open?g`
@@ -3630,18 +3605,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3630
3605
  </div>
3631
3606
  `:null}
3632
3607
  </div>
3633
- `}renderMachineOption(e){let t=this.selected?.id===e.id,n=sT(e,this.statuses),r=g_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
3608
+ `}renderMachineOption(e){let t=this.selected?.id===e.id,n=Rw(e,this.statuses),r=i_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
3634
3609
  <div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
3635
3610
  <button
3636
3611
  type="button"
3637
3612
  class="machine-option-main"
3638
- title=${lT(e)}
3613
+ title=${Bw(e)}
3639
3614
  data-machine-id=${e.id}
3640
3615
  @click=${()=>{this.select(e)}}
3641
3616
  @keydown=${e=>{this.handleMachineOptionKeydown(e)}}
3642
3617
  >
3643
3618
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
3644
- <small>${e.kind===`local`?`Local Pi Web`:e.baseUrl??`Remote Pi Web`} · ${cT(n)}</small>
3619
+ <small>${e.kind===`local`?`Local Pi Web`:e.baseUrl??`Remote Pi Web`} · ${zw(n)}</small>
3645
3620
  </button>
3646
3621
  ${r?g`
3647
3622
  <div class="machine-option-actions">
@@ -3661,7 +3636,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3661
3636
  </div>
3662
3637
  `:null}
3663
3638
  </div>
3664
- `}renderActivity(e){let t=sT(e,this.statuses),n=t===`offline`||t===`error`?void 0:os(this.activities[e.id]),r=this.unreadMachineIds.has(e.id)?`Unread sessions on this machine`:void 0;return t_(n,n===`terminal`?`Machine terminal active`:`Machine active`,r)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=uT(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=uT(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Zg(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
3639
+ `}renderActivity(e){let t=Rw(e,this.statuses),n=t===`offline`||t===`error`?void 0:os(this.activities[e.id]),r=this.unreadMachineIds.has(e.id)?`Unread sessions on this machine`:void 0;return Ug(n,n===`terminal`?`Machine terminal active`:`Machine active`,r)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Vw(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Vw(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=zg(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
3665
3640
  :host { min-width: 0; display: block; }
3666
3641
  .machine-switcher { min-width: 0; }
3667
3642
  .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
@@ -3697,10 +3672,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3697
3672
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
3698
3673
  .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
3699
3674
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
3700
- `}};B([b({attribute:!1})],oT.prototype,`machines`,void 0),B([b({attribute:!1})],oT.prototype,`selected`,void 0),B([b({attribute:!1})],oT.prototype,`statuses`,void 0),B([b({attribute:!1})],oT.prototype,`activities`,void 0),B([b({attribute:!1})],oT.prototype,`unreadMachineIds`,void 0),B([b({attribute:!1})],oT.prototype,`onSelect`,void 0),B([b({attribute:!1})],oT.prototype,`onRemove`,void 0),B([b({attribute:!1})],oT.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],oT.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],oT.prototype,`open`,void 0),B([x()],oT.prototype,`menuStyle`,void 0),B([x()],oT.prototype,`openActionsMachineId`,void 0),B([x()],oT.prototype,`actionMenuStyle`,void 0),oT=B([y(`machine-switcher`)],oT);function sT(e,t){return t[e.id]?.status??e.status??`unknown`}function cT(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function lT(e){return e.baseUrl??e.name}function uT(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${dT(t.bottom)};`,`left: ${dT(r)};`,`width: ${dT(n)};`,`max-height: ${dT(i)};`].join(` `)}function dT(e){return`${String(Math.round(e))}px`}var Q=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=Qf,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){return g`
3675
+ `}};B([b({attribute:!1})],Lw.prototype,`machines`,void 0),B([b({attribute:!1})],Lw.prototype,`selected`,void 0),B([b({attribute:!1})],Lw.prototype,`statuses`,void 0),B([b({attribute:!1})],Lw.prototype,`activities`,void 0),B([b({attribute:!1})],Lw.prototype,`unreadMachineIds`,void 0),B([b({attribute:!1})],Lw.prototype,`onSelect`,void 0),B([b({attribute:!1})],Lw.prototype,`onRemove`,void 0),B([b({attribute:!1})],Lw.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],Lw.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],Lw.prototype,`open`,void 0),B([x()],Lw.prototype,`menuStyle`,void 0),B([x()],Lw.prototype,`openActionsMachineId`,void 0),B([x()],Lw.prototype,`actionMenuStyle`,void 0),Lw=B([y(`machine-switcher`)],Lw);function Rw(e,t){return t[e.id]?.status??e.status??`unknown`}function zw(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function Bw(e){return e.baseUrl??e.name}function Vw(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${Hw(t.bottom)};`,`left: ${Hw(r)};`,`width: ${Hw(n)};`,`max-height: ${Hw(i)};`].join(` `)}function Hw(e){return`${String(Math.round(e))}px`}var Q=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=Uf,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){return g`
3701
3676
  <header>
3702
3677
  <strong>PI WEB</strong>
3703
- ${pT(this.machines)?g`
3678
+ ${Ww(this.machines)?g`
3704
3679
  <machine-switcher
3705
3680
  .machines=${this.machines}
3706
3681
  .selected=${this.selectedMachine}
@@ -3718,7 +3693,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3718
3693
  <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
3719
3694
  </div>
3720
3695
  </header>
3721
- ${this.compact&&pT(this.machines)?g`
3696
+ ${this.compact&&Ww(this.machines)?g`
3722
3697
  <machine-list
3723
3698
  .machines=${this.machines}
3724
3699
  .selected=${this.selectedMachine}
@@ -3774,12 +3749,6 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3774
3749
  .selected=${this.selectedSession}
3775
3750
  .startingCount=${this.startingSessionCount}
3776
3751
  .canStart=${this.canStartSession}
3777
- .canDeleteArchived=${this.canDeleteArchivedSessions}
3778
- .canReload=${this.canReloadSessions}
3779
- .canCleanup=${this.canCleanupSessions}
3780
- .authoritativeSessionPersistence=${this.authoritativeSessionPersistence}
3781
- .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
3782
- .cleanupUnavailableMessage=${this.cleanupUnavailableMessage}
3783
3752
  .collapsible=${this.collapsible}
3784
3753
  .collapsed=${this.sessionsCollapsed}
3785
3754
  .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
@@ -3794,7 +3763,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3794
3763
  .onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
3795
3764
  .onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
3796
3765
  .onDetachParent=${e=>this.onDetachParentSession?.(e)}
3797
- .parentLocation=${this.parentSessionLocation??fT}
3766
+ .parentLocation=${this.parentSessionLocation??Uw}
3798
3767
  .onGoToParent=${this.onGoToParentSession===void 0?void 0:(e,t)=>this.onGoToParentSession?.(e,t)}
3799
3768
  .onMarkRead=${e=>this.onMarkSessionRead?.(e)}
3800
3769
  .onMarkReadMany=${e=>this.onMarkSessionsRead?.(e)}
@@ -3804,7 +3773,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3804
3773
  .onFocusNextSection=${()=>{this.focusNextFrom(`sessions`)}}
3805
3774
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
3806
3775
  ></session-list>
3807
- `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=mT(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(hT(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
3776
+ `}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=Gw(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Kw(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
3808
3777
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
3809
3778
  :host([compact]) { flex: 1 1 auto; }
3810
3779
  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); }
@@ -3812,22 +3781,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3812
3781
  machine-switcher { flex: 1 1 auto; min-width: 0; }
3813
3782
  :host([compact]) header { display: none; }
3814
3783
  .header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
3815
- 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); }
3816
- session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
3784
+ /* Expanded sections share the panel height equally, so collapsing one
3785
+ section distributes its space to every remaining section, not just the
3786
+ session list. Collapsed sections keep only their heading height. */
3787
+ machine-list, project-list, workspace-list, session-list { flex: 1 1 0px; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
3817
3788
  machine-list[collapsed],
3818
3789
  project-list[collapsed],
3819
3790
  workspace-list[collapsed],
3820
3791
  session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
3821
- :host([compact]) machine-list,
3822
- :host([compact]) project-list,
3823
- :host([compact]) workspace-list,
3824
- :host([compact]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
3825
- :host([compact]) machine-list[collapsed],
3826
- :host([compact]) project-list[collapsed],
3827
- :host([compact]) workspace-list[collapsed],
3828
- :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
3829
3792
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
3830
- `}};B([b({attribute:!1})],Q.prototype,`machines`,void 0),B([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([b({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([b({attribute:!1})],Q.prototype,`projects`,void 0),B([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([b({attribute:!1})],Q.prototype,`workspaces`,void 0),B([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`sessions`,void 0),B([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([b({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],Q.prototype,`unreadPresence`,void 0),B([b({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([b({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([b({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([b({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([b({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([b({attribute:!1})],Q.prototype,`parentSessionLocation`,void 0),B([b({attribute:!1})],Q.prototype,`onGoToParentSession`,void 0),B([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),B([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),B([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([S(`machine-list`)],Q.prototype,`machineList`,void 0),B([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([S(`project-list`)],Q.prototype,`projectList`,void 0),B([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([y(`app-navigation-panel`)],Q);var fT=()=>({kind:`unknown`});function pT(e){return e.length>1}function mT(e,t){let n=gT(t);return n[n.indexOf(e)-1]}function hT(e,t){let n=gT(t);return n[n.indexOf(e)+1]??`chat`}function gT(e){return tg.filter(t=>t!==`machines`||pT(e))}var _T=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),vT=420,yT=4,$=class extends v{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`Resize panel`,this.expandLabel=`Expand panel`,this.collapseLabel=`Collapse panel`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
3793
+ `}};B([b({attribute:!1})],Q.prototype,`machines`,void 0),B([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([b({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([b({attribute:!1})],Q.prototype,`projects`,void 0),B([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([b({attribute:!1})],Q.prototype,`workspaces`,void 0),B([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`sessions`,void 0),B([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([b({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],Q.prototype,`unreadPresence`,void 0),B([b({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([b({attribute:!1})],Q.prototype,`parentSessionLocation`,void 0),B([b({attribute:!1})],Q.prototype,`onGoToParentSession`,void 0),B([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),B([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),B([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([S(`machine-list`)],Q.prototype,`machineList`,void 0),B([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([S(`project-list`)],Q.prototype,`projectList`,void 0),B([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([y(`app-navigation-panel`)],Q);var Uw=()=>({kind:`unknown`});function Ww(e){return e.length>1}function Gw(e,t){let n=qw(t);return n[n.indexOf(e)-1]}function Kw(e,t){let n=qw(t);return n[n.indexOf(e)+1]??`chat`}function qw(e){return Uh.filter(t=>t!==`machines`||Ww(e))}var Jw=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),Yw=420,Xw=4,$=class extends v{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`Resize panel`,this.expandLabel=`Expand panel`,this.collapseLabel=`Collapse panel`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
3831
3794
  ${this.renderResizeHandle()}
3832
3795
  <button
3833
3796
  type="button"
@@ -3857,7 +3820,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3857
3820
  @dblclick=${e=>{this.onResizeDoubleClick(e)}}
3858
3821
  @keydown=${e=>{this.onResizeKeyDown(e)}}
3859
3822
  ></div>
3860
- `}resizeAriaValueNow(){return this.panelWidth===void 0?_:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=yT)&&(t.moved=!0,this.commitPanelWidth(yg(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!_T.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=bg(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=vT){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return xg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(xg(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=_g(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
3823
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?_:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Xw)&&(t.moved=!0,this.commitPanelWidth(sg(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Jw.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=cg(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=Yw){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return lg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(lg(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=ag(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
3861
3824
  :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
3862
3825
  :host([side="navigation"]) { grid-column: 2; }
3863
3826
  :host([side="workspace"]) { grid-column: 4; }
@@ -3876,7 +3839,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3876
3839
  @media (max-width: 760px) {
3877
3840
  :host([side="navigation"]) { display: none; }
3878
3841
  }
3879
- `}};B([b({reflect:!0})],$.prototype,`side`,void 0),B([b({type:Boolean,reflect:!0})],$.prototype,`collapsed`,void 0),B([b({type:Boolean})],$.prototype,`resizable`,void 0),B([b({type:Number})],$.prototype,`panelWidth`,void 0),B([b({type:Number})],$.prototype,`minWidth`,void 0),B([b({type:Number})],$.prototype,`maxWidth`,void 0),B([b()],$.prototype,`controls`,void 0),B([b()],$.prototype,`resizeLabel`,void 0),B([b()],$.prototype,`expandLabel`,void 0),B([b()],$.prototype,`collapseLabel`,void 0),B([b({attribute:!1})],$.prototype,`onToggle`,void 0),B([b({attribute:!1})],$.prototype,`onResizeStart`,void 0),B([b({attribute:!1})],$.prototype,`onResize`,void 0),B([b({attribute:!1})],$.prototype,`onResizeEnd`,void 0),B([b({attribute:!1})],$.prototype,`onReset`,void 0),$=B([y(`app-panel-edge-control`)],$);var bT=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
3842
+ `}};B([b({reflect:!0})],$.prototype,`side`,void 0),B([b({type:Boolean,reflect:!0})],$.prototype,`collapsed`,void 0),B([b({type:Boolean})],$.prototype,`resizable`,void 0),B([b({type:Number})],$.prototype,`panelWidth`,void 0),B([b({type:Number})],$.prototype,`minWidth`,void 0),B([b({type:Number})],$.prototype,`maxWidth`,void 0),B([b()],$.prototype,`controls`,void 0),B([b()],$.prototype,`resizeLabel`,void 0),B([b()],$.prototype,`expandLabel`,void 0),B([b()],$.prototype,`collapseLabel`,void 0),B([b({attribute:!1})],$.prototype,`onToggle`,void 0),B([b({attribute:!1})],$.prototype,`onResizeStart`,void 0),B([b({attribute:!1})],$.prototype,`onResize`,void 0),B([b({attribute:!1})],$.prototype,`onResizeEnd`,void 0),B([b({attribute:!1})],$.prototype,`onReset`,void 0),$=B([y(`app-panel-edge-control`)],$);var Zw=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
3880
3843
  <button
3881
3844
  class="app-refresh-button"
3882
3845
  title=${e}
@@ -3895,7 +3858,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3895
3858
  :host, :host * { -webkit-user-select: none; user-select: none; }
3896
3859
  .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; }
3897
3860
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
3898
- `}};B([b({attribute:!1})],bT.prototype,`onReload`,void 0),bT=B([y(`app-refresh-control`)],bT);var xT=900*1e3,ST=750,CT=[1e3,3e3,8e3,15e3,3e4],wT={capture:!0},TT=`auto:on`,ET=`auto:off`,DT=`theme:`,OT=Mo(`core:workspace.files`),kT=Mo(`core:workspace.git`),AT=Mo(`core:workspace.terminal`),jT=320,MT=2,NT=`(min-width: 1181px)`,PT=class extends v{constructor(...e){super(...e),this.state=bo(),this.sessionUnread=new Wf({onChange:e=>{this.syncUnreadPresence(),R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadPresence=Qf,this.unreadConnected=!1,this.notifications=new bd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Eu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new mu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new ls(()=>this.state,e=>{this.setState(e)},{api:La,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Eo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new ko(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Od(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Ed),this.projects=new ts(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Qo(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new ds(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new Go(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Zo(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Zd,this.realtime=new Wl,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Nd,this.terminalSelection=new Kd,this.appShell=new Jh(this),this.browserResume=new Xh({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new fg(this),this.panelResize=new gg(this),this.navigationSections=new lg(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=FT(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=yp()??hp,this.activeThemeId=mp,this.isRefreshingApp=!1,this.settingsSection=Lg(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=$a(void 0),this.sessionWarningVisibility=cp(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.parentSessionLocationFor=e=>wf(e,{workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId,projects:this.state.projects}),this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=pp(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=RT(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=up(this.sessionWarningVisibility,e===void 0?void 0:wo(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=R(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=LT(e,t);await this.updateComplete,!(!this.unreadConnected||RT(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);WT(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=$f({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:R(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});ap(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=LT(e,t);return RT(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0}connectedCallback(){super.connectedCallback(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,wT),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},xT),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,wT),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!UT(this.state,e))return;let t=this.state;this.state={...this.state,...e},RT(t)!==RT(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),zT(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),BT(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Mg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=ST){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>HT(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await ja.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=$a(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let 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(Mg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?qT():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let 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:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?qT():{selectedFilePath:Po(OT,`file`),selectedDiffPath:Po(kT,`diff`),selectedTerminalId:Po(AT,`terminal`)}}routeForSelectedMachine(e){let 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){Ng(e,{replace:!0}),Fo(OT,`file`,void 0,{replace:!0}),Fo(kT,`diff`,void 0,{replace:!0}),Fo(AT,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=YT(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=CT.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await QT(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Ng({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(Fd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Fd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ng(Id(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Fo(OT,`file`,e.selectedFilePath,{replace:!0}),Fo(kT,`diff`,e.selectedDiffPath,{replace:!0}),Fo(AT,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Pd(e.id);if(await this.restoreRouteFor(Id(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);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=R(this.state)){let n=JT(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Wg(e,{api:{runTerminalCommand:(e,n)=>za.runTerminalCommand(e,n,t),listCommandRuns:e=>za.listCommandRuns(e,t),getCommandRun:e=>za.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(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:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let 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){Fo(AT,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(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,Rg(e)}closeSettings(){this.settingsSection=void 0,Rg(void 0)}navigateSettings(e){this.settingsSection=e,Rg(e)}restoreSettingsRoute(){this.settingsSection=Lg()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:T(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Wl;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>VT(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):KT(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let 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){let t=R(this.state);try{let n=await za.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=GT(e),r=GT(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
3861
+ `}};B([b({attribute:!1})],Zw.prototype,`onReload`,void 0),Zw=B([y(`app-refresh-control`)],Zw);var Qw=900*1e3,$w=750,eT=[1e3,3e3,8e3,15e3,3e4],tT={capture:!0},nT=`auto:on`,rT=`auto:off`,iT=`theme:`,aT=Mo(`core:workspace.files`),oT=Mo(`core:workspace.git`),sT=Mo(`core:workspace.terminal`),cT=320,lT=2,uT=`(min-width: 1181px)`,dT=class extends v{constructor(...e){super(...e),this.state=bo(),this.sessionUnread=new Ff({onChange:e=>{this.syncUnreadPresence(),L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadPresence=Uf,this.unreadConnected=!1,this.notifications=new fd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new pu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new ls(()=>this.state,e=>{this.setState(e)},{api:La,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Eo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new ko(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new bd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new vd),this.projects=new ts(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Qo(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new ds(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new Go(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Zo(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Ud,this.realtime=new Jl,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Td,this.terminalSelection=new Rd,this.appShell=new Ih(this),this.browserResume=new Rh({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new eg(this),this.panelResize=new ig(this),this.navigationSections=new Zh(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=fT(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=up()??op,this.activeThemeId=ap,this.isRefreshingApp=!1,this.settingsSection=Tg(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=$a(void 0),this.sessionWarningVisibility=$f(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.parentSessionLocationFor=e=>gf(e,{workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId,projects:this.state.projects}),this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=ip(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=hT(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=tp(this.sessionWarningVisibility,e===void 0?void 0:wo(L(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=mT(e,t);await this.updateComplete,!(!this.unreadConnected||hT(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);xT(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Wf({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:L(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Xf(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=mT(e,t);return hT(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0}connectedCallback(){super.connectedCallback(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,tT),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.syncSessionUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Qw),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,tT),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!bT(this.state,e))return;let t=this.state;this.state={...this.state,...e},hT(t)!==hT(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),gT(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),_T(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=bg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.sessionUnread.refreshAll(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=$w){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=L(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>yT(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await ja.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=$a(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let 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(bg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?wT():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let 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:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?wT():{selectedFilePath:Po(aT,`file`),selectedDiffPath:Po(oT,`diff`),selectedTerminalId:Po(sT,`terminal`)}}routeForSelectedMachine(e){let 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){xg(e,{replace:!0}),Fo(aT,`file`,void 0,{replace:!0}),Fo(oT,`diff`,void 0,{replace:!0}),Fo(sT,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=ET(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=eT.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await kT(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),xg({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(Dd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Dd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){xg(Od(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Fo(aT,`file`,e.selectedFilePath,{replace:!0}),Fo(oT,`diff`,e.selectedDiffPath,{replace:!0}),Fo(sT,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Ed(e.id);if(await this.restoreRouteFor(Od(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);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=L(this.state)){let n=TT(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Mg(e,{api:{runTerminalCommand:(e,n)=>za.runTerminalCommand(e,n,t),listCommandRuns:e=>za.listCommandRuns(e,t),getCommandRun:e=>za.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((L(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:n?.terminalId},`core:workspace.terminal`),L(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let 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){Fo(sT,`terminal`,e,t)}terminalWorkspaceKey(e){return`${L(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,Eg(e)}closeSettings(){this.settingsSection=void 0,Eg(void 0)}navigateSettings(e){this.settingsSection=e,Eg(e)}restoreSettingsRoute(){this.settingsSection=Tg()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}connectRealtime(){let e=L(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessionUnread.refresh(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Jl;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.sessionUnread.refresh(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>vT(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):CT(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let 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){let t=L(this.state);try{let n=await za.terminals(e.projectId,e.id,t);if(L(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=ST(e),r=ST(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
3899
3862
  <workspace-panel
3900
3863
  id="workspace-panel"
3901
3864
  .workspace=${e}
@@ -3941,7 +3904,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3941
3904
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
3942
3905
  .onReset=${()=>{this.resetResizablePanel(`workspace`)}}
3943
3906
  ></app-panel-edge-control>
3944
- `}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-MT-jT);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(NT).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||T(e,w.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&T(e,w.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&T(e,w.sessionsClearQueue)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&T(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return tu(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&T(t,w.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return zf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await Ra.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${XT(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Mf(t.previewRequest)!==Mf(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await Ra.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${XT(e)}`})}}renderNavigationPanel(){return g`
3907
+ `}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-lT-cT);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(uT).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}selectedMachineRuntime(){return this.state.machineRuntimes[L(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=L(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await Ra.cleanupPreview(e,t);if(L(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){L(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${DT(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||wf(t.previewRequest)!==wf(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}let n=L(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await Ra.cleanup(e,n);if(L(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){L(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${DT(e)}`})}}renderNavigationPanel(){return g`
3945
3908
  <app-navigation-panel
3946
3909
  .machines=${this.state.machines}
3947
3910
  .selectedMachine=${this.state.selectedMachine}
@@ -3957,7 +3920,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3957
3920
  .workspacesByProjectId=${this.state.workspacesByProjectId}
3958
3921
  .workspaces=${this.state.workspaces}
3959
3922
  .selectedWorkspace=${this.state.selectedWorkspace}
3960
- .deletingWorkspaceIds=${Pp(this.state.workspaceDeletionRuns)}
3923
+ .deletingWorkspaceIds=${Tp(this.state.workspaceDeletionRuns)}
3961
3924
  .sessions=${this.state.sessions}
3962
3925
  .sessionStatuses=${this.state.sessionStatuses}
3963
3926
  .sessionActivities=${this.state.sessionActivities}
@@ -3967,12 +3930,6 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
3967
3930
  .selectedSession=${this.state.selectedSession}
3968
3931
  .startingSessionCount=${this.state.startingSessionCount}
3969
3932
  .canStartSession=${!!this.state.selectedWorkspace}
3970
- .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
3971
- .canReloadSessions=${this.canReloadSessions()}
3972
- .canCleanupSessions=${this.canCleanupSessions()}
3973
- .authoritativeSessionPersistence=${this.hasAuthoritativeSessionPersistence()}
3974
- .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
3975
- .cleanupUnavailableMessage=${this.sessionCleanupUnavailableMessage()}
3976
3933
  .collapsible=${!0}
3977
3934
  .compact=${this.appShell.isMobileNavigationLayout}
3978
3935
  .projectsCollapsed=${this.navigationSections.isCollapsed(`projects`)}
@@ -4008,15 +3965,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4008
3965
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
4009
3966
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
4010
3967
  ></app-navigation-panel>
4011
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async goToParentSession(e){e.kind===`workspace`&&await this.selectNavigationItem(`sessions`,`chat`,async()=>{let t=this.state.workspaces.find(t=>t.id===e.workspaceId);if(t!==void 0){await this.workspaces.selectWorkspace(t,{sessionId:e.sessionId});return}let n=this.state.projects.find(t=>t.id===e.projectId);n!==void 0&&await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId})})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!pT(this.state.machines)){await this.focusNavigationSection(`projects`);return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView(`navigation`),this.navigationSections.expand(e),await this.updateComplete,await QT(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await QT(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
3968
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async goToParentSession(e){e.kind===`workspace`&&await this.selectNavigationItem(`sessions`,`chat`,async()=>{let t=this.state.workspaces.find(t=>t.id===e.workspaceId);if(t!==void 0){await this.workspaces.selectWorkspace(t,{sessionId:e.sessionId});return}let n=this.state.projects.find(t=>t.id===e.projectId);n!==void 0&&await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId})})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!Ww(this.state.machines)){await this.focusNavigationSection(`projects`);return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView(`navigation`),this.navigationSections.expand(e),await this.updateComplete,await kT(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await kT(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=L(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&L(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
4012
3969
  <session-tree-navigator
4013
3970
  .tree=${e.treeDialog}
4014
3971
  .onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
4015
3972
  .onAbort=${()=>this.sessions.abortTreeNavigation()}
4016
3973
  .onCancel=${()=>{this.closeSessionTreeNavigator()}}
4017
3974
  ></session-tree-navigator>
4018
- `}visibleWorkspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}workspacePanelEmptyState(){let 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?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}mobilePanelBadge(e){let 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){let t=IT(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return zh(La,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=IT(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Fh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},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,workspaceUploadDefaultFolder:eo(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return Vg(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEB plugins`,()=>vh())}async loadPluginsForSelectedMachine(){let 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;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>vh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Ph({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!kd(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Fp(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await La.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${XT(e)}`})}}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(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Ip(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(Mp(t.id));if(R(this.state)!==e)return;let r=Np(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Lp(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Lp);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=R(this.state)){if(R(this.state)!==t)return;let n=JT(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Ip(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:ZT(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEB gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let 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=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id;this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:e.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:`${i}${a?` ✓ current`:``}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?ET:TT;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${DT}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${DT}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===TT||e===ET){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===TT},this.applyPreferredTheme(!0);return}if(!e.startsWith(DT))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,xp(t),e&&bp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Sp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return wp(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){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let 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(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=$T(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}renderChatView(e,t){return g`
4019
- <chat-view .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .activity=${e.activity} .pendingAsk=${e.pendingAsk} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${wo(R(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${td(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
3975
+ `}visibleWorkspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}workspacePanelEmptyState(){let 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?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}mobilePanelBadge(e){let 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){let t=pT(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return Dh(La,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=pT(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Ch({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},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,workspaceUploadDefaultFolder:eo(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return kg(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEB plugins`,()=>oh())}async loadPluginsForSelectedMachine(){let 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;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>oh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Sh({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!xd(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Ep(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=L(this.state);try{let t=await La.deleteWorkspace(e.projectId,e.id,n);if(L(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(L(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){L(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${DT(e)}`})}}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(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(L(this.state)!==t)return;let n=Dp(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=L(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(Cp(t.id));if(L(this.state)!==e)return;let r=wp(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Op(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Op);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=L(this.state)){if(L(this.state)!==t)return;let n=TT(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Dp(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),L(this.state)!==t)return;this.setState({workspaceDeletionRuns:OT(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEB gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let 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=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id;this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:e.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:`${i}${a?` ✓ current`:``}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?rT:nT;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${iT}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${iT}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===nT||e===rT){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===nT},this.applyPreferredTheme(!0);return}if(!e.startsWith(iT))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,fp(t),e&&dp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return pp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return hp(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){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let 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(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=AT(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}renderChatView(e,t){return g`
3976
+ <chat-view .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .activity=${e.activity} .pendingAsk=${e.pendingAsk} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${wo(L(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${qu(e.selectedNotificationInbox)} .onClearServerQueue=${this.handleClearServerQueue} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
4020
3977
  `}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return g`
4021
3978
  <status-bar .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
4022
3979
  `}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
@@ -4036,33 +3993,33 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
4036
3993
  .selectedView=${this.state.mainView}
4037
3994
  .onSelect=${e=>{this.selectMainView(e)}}
4038
3995
  ></app-mobile-main-tabs>
4039
- `}mobileMainTabs(){let e=P_(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:`Sessions`,icon:`navigation`,className:`navigation-tab`,...e===0?{}:{badge:e,badgeLabel:`${String(e)} unread`,badgeTone:`unread`}},{id:`chat`,label:`Chat`,icon:`chat`},...this.visibleWorkspacePanels().map(e=>{let t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return g`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){let e=this.state;return g`
3996
+ `}mobileMainTabs(){let e=S_(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:`Sessions`,icon:`navigation`,className:`navigation-tab`,...e===0?{}:{badge:e,badgeLabel:`${String(e)} unread`,badgeTone:`unread`}},{id:`chat`,label:`Chat`,icon:`chat`},...this.visibleWorkspacePanels().map(e=>{let t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return g`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){let e=this.state;return g`
4040
3997
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
4041
3998
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
4042
3999
  ${this.renderNavigationPanelEdgeControl()}
4043
- <main class=${pg(e.mainView)}>
4000
+ <main class=${tg(e.mainView)}>
4044
4001
  ${this.renderContextBar()}
4045
4002
  ${this.renderMobileMainTabs()}
4046
4003
  ${e.error?g`<div class="error">${e.error}</div>`:null}
4047
4004
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
4048
4005
  ${e.selectedSession?g`
4049
4006
  ${this.renderChatView(e,e.selectedSession)}
4050
- <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking}></prompt-editor>
4007
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${L(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking}></prompt-editor>
4051
4008
  ${this.renderStatusBar(e)}
4052
4009
  ${e.commandDialog===void 0?null:g`<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>`}
4053
4010
  ${e.modelDialog===void 0?null:g`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${e=>{this.pickModel(e)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`}
4054
4011
  ${e.thinkingDialog===void 0?null:g`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${e=>{this.pickThinking(e)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`}
4055
- ${e.authDialog===void 0?null:g`<auth-dialog .state=${e.authDialog} .onChooseMethod=${e=>{this.auth.chooseLoginMethod(e)}} .onSelectProvider=${(e,t)=>{this.auth.selectLoginProvider(e,t)}} .onApiKeyInput=${e=>{this.auth.updateApiKey(e)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${e=>{this.auth.logoutProvider(e)}} .onOAuthInput=${e=>{this.auth.updateOAuthInput(e)}} .onOAuthRespond=${e=>{this.auth.respondOAuth(e)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`}
4012
+ ${e.authDialog===void 0?null:g`<auth-dialog .state=${e.authDialog} .onChooseMethod=${e=>{this.auth.chooseLoginMethod(e)}} .onSelectProvider=${(e,t)=>{this.auth.selectLoginProvider(e,t)}} .onLogoutProvider=${e=>{this.auth.logoutProvider(e)}} .onOAuthInput=${e=>{this.auth.updateOAuthInput(e)}} .onOAuthRespond=${e=>{this.auth.respondOAuth(e)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`}
4056
4013
  `:g`<div class="empty">${this.sessionEmptyMessage()}</div>`}
4057
4014
  </main>
4058
4015
  ${this.renderWorkspacePanelEdgeControl()}
4059
4016
  ${this.renderWorkspacePanel()}
4060
4017
  ${e.actionPaletteOpen?g`<action-palette .actions=${this.getActions()} .onRun=${e=>{this.setState({actionPaletteOpen:!1}),this.runAction(e)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
4061
4018
  ${this.renderSessionTreeNavigator(e)}
4062
- ${e.projectDialogOpen?g`<project-dialog .machineId=${R(e)} .onSubmit=${(e,t)=>this.projects.addProject(e,t)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
4019
+ ${e.projectDialogOpen?g`<project-dialog .machineId=${L(e)} .onSubmit=${(e,t)=>this.projects.addProject(e,t)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
4063
4020
  ${e.machineDialogOpen?g`<machine-dialog .error=${e.error} .onSubmit=${e=>this.submitMachineDialog(e)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
4064
- ${this.sessionCleanupDialog===void 0?null:g`<session-cleanup-dialog .canCleanup=${this.canCleanupSessions()} .unavailableMessage=${this.sessionCleanupUnavailableMessage()} .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??``} .onPreview=${e=>{this.previewSessionCleanup(e)}} .onRun=${e=>{this.runSessionCleanup(e)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`}
4021
+ ${this.sessionCleanupDialog===void 0?null:g`<session-cleanup-dialog .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??``} .onPreview=${e=>{this.previewSessionCleanup(e)}} .onRun=${e=>{this.runSessionCleanup(e)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`}
4065
4022
  ${e.themeDialog===void 0?null:g`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${e=>{this.pickTheme(e)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`}
4066
4023
  ${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
4067
4024
  </div>
4068
- `}static{this.styles=$p}};B([x()],PT.prototype,`state`,void 0),B([S(`chat-view`)],PT.prototype,`chatView`,void 0),B([S(`prompt-editor`)],PT.prototype,`promptEditor`,void 0),B([S(`app-navigation-panel`)],PT.prototype,`navigationPanel`,void 0),B([S(`#navigation-panel`)],PT.prototype,`navigationPanelFrame`,void 0),B([S(`#workspace-panel`)],PT.prototype,`workspacePanelFrame`,void 0),B([x()],PT.prototype,`unreadSessionIds`,void 0),B([x()],PT.prototype,`unreadPresence`,void 0),B([x()],PT.prototype,`activeThemeId`,void 0),B([x()],PT.prototype,`isRefreshingApp`,void 0),B([x()],PT.prototype,`sessionCleanupDialog`,void 0),B([x()],PT.prototype,`settingsSection`,void 0),B([x()],PT.prototype,`shortcutConfig`,void 0),B([x()],PT.prototype,`workspaceUploadDefaultFolder`,void 0),PT=B([y(`pi-web-app`)],PT);function FT(){let e=new jh;return e.register({id:`core`,plugin:ch}),e.register({id:`themes`,plugin:fh}),e}function IT(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function LT(e,t){return JSON.stringify([e,t.id,t.cwd])}function RT(e){let t=e.selectedSession;return t===void 0?void 0:LT(R(e),t)}function zT(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function BT(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function VT(e,t){return HT(e,t)}function HT(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function UT(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function WT(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function GT(e){return xo(e.status,e.activity)}function KT(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function qT(){return{}}function JT(e,t){return JSON.stringify([e,t])}function YT(e){return CT[Math.min(e,CT.length-1)]??3e4}function XT(e){return e instanceof Error?e.message:String(e)}function ZT(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function QT(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function $T(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{h as _,B as a,qa as c,x as d,b as f,g,Ye as h,v_ as i,za as l,v as m,fv as n,Jd as o,y as p,uv as r,qd as s,dv as t,S as u};
4025
+ `}static{this.styles=Vp}};B([x()],dT.prototype,`state`,void 0),B([S(`chat-view`)],dT.prototype,`chatView`,void 0),B([S(`prompt-editor`)],dT.prototype,`promptEditor`,void 0),B([S(`app-navigation-panel`)],dT.prototype,`navigationPanel`,void 0),B([S(`#navigation-panel`)],dT.prototype,`navigationPanelFrame`,void 0),B([S(`#workspace-panel`)],dT.prototype,`workspacePanelFrame`,void 0),B([x()],dT.prototype,`unreadSessionIds`,void 0),B([x()],dT.prototype,`unreadPresence`,void 0),B([x()],dT.prototype,`activeThemeId`,void 0),B([x()],dT.prototype,`isRefreshingApp`,void 0),B([x()],dT.prototype,`sessionCleanupDialog`,void 0),B([x()],dT.prototype,`settingsSection`,void 0),B([x()],dT.prototype,`shortcutConfig`,void 0),B([x()],dT.prototype,`workspaceUploadDefaultFolder`,void 0),dT=B([y(`pi-web-app`)],dT);function fT(){let e=new yh;return e.register({id:`core`,plugin:Xm}),e.register({id:`themes`,plugin:eh}),e}function pT(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function mT(e,t){return JSON.stringify([e,t.id,t.cwd])}function hT(e){let t=e.selectedSession;return t===void 0?void 0:mT(L(e),t)}function gT(e,t){return e.machines!==t.machines}function _T(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function vT(e,t){return yT(e,t)}function yT(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function bT(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function xT(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function ST(e){return xo(e.status,e.activity)}function CT(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function wT(){return{}}function TT(e,t){return JSON.stringify([e,t])}function ET(e){return eT[Math.min(e,eT.length-1)]??3e4}function DT(e){return e instanceof Error?e.message:String(e)}function OT(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function kT(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function AT(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{h as _,B as a,qa as c,x as d,b as f,g,Ye as h,o_ as i,za as l,v as m,ev as n,Bd as o,y as p,Q_ as r,zd as s,$_ as t,S as u};