@jmfederico/pi-web 1.202606.6 → 1.202607.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 (103) hide show
  1. package/README.md +87 -293
  2. package/dist/cli.js +25 -7
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/assets/CodeViewer-tXF3UTsY.js +4 -0
  5. package/dist/client/assets/TerminalPanel-D_ihiWAt.js +187 -0
  6. package/dist/client/assets/UnifiedDiffViewer-BziirXBJ.js +39 -0
  7. package/dist/client/assets/index-Brfk1lwl.js +2950 -0
  8. package/dist/client/assets/vendor-editor-core-vUi74DnD.js +12 -0
  9. package/dist/client/assets/vendor-editor-languages-DoaXUodB.js +46 -0
  10. package/dist/client/assets/vendor-editor-legacy-CYBnW6ZU.js +1 -0
  11. package/dist/client/assets/vendor-terminal-BrP-ENHg.css +1 -0
  12. package/dist/client/assets/vendor-terminal-D8k4UKM2.js +35 -0
  13. package/dist/client/index.html +6 -3
  14. package/dist/config.js +33 -1
  15. package/dist/config.js.map +1 -1
  16. package/dist/docker/piWebDockerCommandPlan.js +211 -0
  17. package/dist/docker/piWebDockerCommandPlan.js.map +1 -0
  18. package/dist/pi-web-plugins/updates/pi-web-plugin.js +15 -5
  19. package/dist/pi-web-plugins/updates/updatesLogic.js +37 -5
  20. package/dist/piWebVersionReport.js +4 -0
  21. package/dist/piWebVersionReport.js.map +1 -1
  22. package/dist/plugin-api.d.ts +30 -2
  23. package/dist/server/app.js +32 -5
  24. package/dist/server/app.js.map +1 -1
  25. package/dist/server/browserMessageProjection.js +56 -0
  26. package/dist/server/browserMessageProjection.js.map +1 -0
  27. package/dist/server/configRoutes.js +112 -2
  28. package/dist/server/configRoutes.js.map +1 -1
  29. package/dist/server/machines/machineClient.js +51 -13
  30. package/dist/server/machines/machineClient.js.map +1 -1
  31. package/dist/server/machines/machineProxyRoutes.js +72 -4
  32. package/dist/server/machines/machineProxyRoutes.js.map +1 -1
  33. package/dist/server/machines/machineService.js +4 -26
  34. package/dist/server/machines/machineService.js.map +1 -1
  35. package/dist/server/piPackageRoutes.js +87 -0
  36. package/dist/server/piPackageRoutes.js.map +1 -0
  37. package/dist/server/piPackageService.js +69 -0
  38. package/dist/server/piPackageService.js.map +1 -0
  39. package/dist/server/piWebPluginService.js +43 -8
  40. package/dist/server/piWebPluginService.js.map +1 -1
  41. package/dist/server/piWebStatus.js +57 -0
  42. package/dist/server/piWebStatus.js.map +1 -1
  43. package/dist/server/realtime/sessionEventHub.js +2 -1
  44. package/dist/server/realtime/sessionEventHub.js.map +1 -1
  45. package/dist/server/sessions/attachmentService.js +69 -11
  46. package/dist/server/sessions/attachmentService.js.map +1 -1
  47. package/dist/server/sessions/builtinCommands.js +1 -1
  48. package/dist/server/sessions/builtinCommands.js.map +1 -1
  49. package/dist/server/sessions/piSessionManagerGateway.js +20 -2
  50. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
  51. package/dist/server/sessions/piSessionService.js +905 -73
  52. package/dist/server/sessions/piSessionService.js.map +1 -1
  53. package/dist/server/sessions/sessionArchiveStore.js +51 -22
  54. package/dist/server/sessions/sessionArchiveStore.js.map +1 -1
  55. package/dist/server/sessions/sessionCleanup.js +157 -0
  56. package/dist/server/sessions/sessionCleanup.js.map +1 -0
  57. package/dist/server/sessions/sessionCommandService.js +16 -0
  58. package/dist/server/sessions/sessionCommandService.js.map +1 -1
  59. package/dist/server/sessions/sessionNameGenerator.js +27 -44
  60. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  61. package/dist/server/sessions/sessionRoutes.js +55 -1
  62. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  63. package/dist/server/sessions/spawnSessionTool.js +9 -4
  64. package/dist/server/sessions/spawnSessionTool.js.map +1 -1
  65. package/dist/server/sessions/spawnSubsessionTool.js +28 -18
  66. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -1
  67. package/dist/server/workspaceExplorerRoutes.js +55 -3
  68. package/dist/server/workspaceExplorerRoutes.js.map +1 -1
  69. package/dist/server/workspaces/fileContentService.js +112 -1
  70. package/dist/server/workspaces/fileContentService.js.map +1 -1
  71. package/dist/server/workspaces/fileSuggestions.js +7 -3
  72. package/dist/server/workspaces/fileSuggestions.js.map +1 -1
  73. package/dist/server/workspaces/pathSafety.js +16 -1
  74. package/dist/server/workspaces/pathSafety.js.map +1 -1
  75. package/dist/server/workspaces/projectPiWebConfig.js +6 -1
  76. package/dist/server/workspaces/projectPiWebConfig.js.map +1 -1
  77. package/dist/shared/activity.js +0 -15
  78. package/dist/shared/activity.js.map +1 -1
  79. package/dist/shared/apiTypes.d.ts +146 -7
  80. package/dist/shared/apiTypes.js +5 -0
  81. package/dist/shared/apiTypes.js.map +1 -1
  82. package/dist/shared/capabilities.js +29 -2
  83. package/dist/shared/capabilities.js.map +1 -1
  84. package/dist/shared/federatedRoutes.js +15 -0
  85. package/dist/shared/federatedRoutes.js.map +1 -1
  86. package/dist/shared/piWebStatusParsing.js +20 -8
  87. package/dist/shared/piWebStatusParsing.js.map +1 -1
  88. package/dist/shared/promptAttachments.js +30 -11
  89. package/dist/shared/promptAttachments.js.map +1 -1
  90. package/dist/shared/thinkingLevels.d.ts +1 -1
  91. package/dist/shared/thinkingLevels.js +1 -1
  92. package/dist/shared/thinkingLevels.js.map +1 -1
  93. package/docs/config.md +62 -14
  94. package/docs/plugins.md +155 -17
  95. package/package.json +35 -31
  96. package/dist/client/assets/CodeViewer-Bv8l_MFi.js +0 -4
  97. package/dist/client/assets/TerminalPanel-BZKsaE9s.js +0 -126
  98. package/dist/client/assets/index-C9oPLpm7.js +0 -2408
  99. package/dist/client/assets/vendor-editor-core-Bc1A7SO7.js +0 -12
  100. package/dist/client/assets/vendor-editor-languages-D0CnB2js.js +0 -26
  101. package/dist/client/assets/vendor-editor-legacy-B4QLsWF8.js +0 -1
  102. package/dist/client/assets/vendor-terminal-DDGTF8rc.css +0 -1
  103. package/dist/client/assets/vendor-terminal-DjQ08hXu.js +0 -16
@@ -1,2408 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Bv8l_MFi.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BZKsaE9s.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as xo,w as nt,J as qi,R as La,S as ja,G as Na,U as za,V as Fa,A as Ba,W as Ua,X as Ha,Y as qa,Z as ko,x as $o,_ as Ka}from"./vendor-editor-core-Bc1A7SO7.js";import{m as Va,i as Ga,d as Qa}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const si=globalThis,Ls=si.ShadowRoot&&(si.ShadyCSS===void 0||si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,js=Symbol(),Po=new WeakMap;let rn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==js)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(Ls&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Po.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Po.set(i,t))}return t}toString(){return this.cssText}};const Za=e=>new rn(typeof e=="string"?e:e+"",void 0,js),O=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new rn(i,e,js)},Ja=(e,t)=>{if(Ls)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=si.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Ro=Ls?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Za(i)})(e):e;const{is:Xa,defineProperty:Ya,getOwnPropertyDescriptor:el,getOwnPropertyNames:tl,getOwnPropertySymbols:il,getPrototypeOf:sl}=Object,Ei=globalThis,Io=Ei.trustedTypes,ol=Io?Io.emptyScript:"",rl=Ei.reactiveElementPolyfillSupport,Et=(e,t)=>e,di={toAttribute(e,t){switch(t){case Boolean:e=e?ol:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Ns=(e,t)=>!Xa(e,t),Co={attribute:!0,type:String,converter:di,reflect:!1,useDefault:!1,hasChanged:Ns};Symbol.metadata??=Symbol("metadata"),Ei.litPropertyMetadata??=new WeakMap;let dt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=Co){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Ya(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=el(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Co}static _$Ei(){if(this.hasOwnProperty(Et("elementProperties")))return;const t=sl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Et("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Et("properties"))){const i=this.properties,s=[...tl(i),...il(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(Ro(o))}else t!==void 0&&i.push(Ro(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ja(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:di).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:di;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ns)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};dt.elementStyles=[],dt.shadowRootOptions={mode:"open"},dt[Et("elementProperties")]=new Map,dt[Et("finalized")]=new Map,rl?.({ReactiveElement:dt}),(Ei.reactiveElementVersions??=[]).push("2.1.2");const zs=globalThis,Mo=e=>e,pi=zs.trustedTypes,Ao=pi?pi.createPolicy("lit-html",{createHTML:e=>e}):void 0,nn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,an="?"+Be,nl=`<${an}>`,Xe=document,Wt=()=>Xe.createComment(""),_t=e=>e===null||typeof e!="object"&&typeof e!="function",Fs=Array.isArray,al=e=>Fs(e)||typeof e?.[Symbol.iterator]=="function",Ki=`[
3
- \f\r]`,St=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,To=/-->/g,Eo=/>/g,qe=RegExp(`>|${Ki}(?:([^\\s"'>=/]+)(${Ki}*=${Ki}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Do=/'/g,Wo=/"/g,ln=/^(?:script|style|textarea|title)$/i,cn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=cn(1),he=cn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),_o=new WeakMap,Qe=Xe.createTreeWalker(Xe,129);function dn(e,t){if(!Fs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ao!==void 0?Ao.createHTML(t):t}const ll=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=St;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===St?u[1]==="!--"?n=To:u[1]!==void 0?n=Eo:u[2]!==void 0?(ln.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??St,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?Wo:Do):n===Wo||n===Do?n=qe:n===To||n===Eo?n=St:(n=qe,o=void 0);const v=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===St?c+nl:h>=0?(s.push(p),c.slice(0,h)+nn+c.slice(h)+Be+v):c+Be+(h===-2?a:v)}return[dn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ot{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=ll(t,i);if(this.el=Ot.createElement(p,s),Qe.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Qe.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(nn)){const f=u[n++],v=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?dl:P[1]==="?"?pl:P[1]==="@"?hl:Di}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(ln.test(o.tagName)){const h=o.textContent.split(Be),f=h.length-1;if(f>0){o.textContent=pi?pi.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],Wt()),Qe.nextNode(),c.push({type:2,index:++r});o.append(h[f],Wt())}}}else if(o.nodeType===8)if(o.data===an)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Xe.createElement("template");return s.innerHTML=t,s}}function ft(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=_t(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ft(e,o._$AS(e,t.values),o,s)),t}class cl{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Xe).importNode(i,!0);Qe.currentNode=o;let r=Qe.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new mt(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new ul(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Qe.nextNode(),n++)}return Qe.currentNode=Xe,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class mt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ft(this,t,i),_t(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):al(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&_t(this._$AH)?this._$AA.nextSibling.data=t:this.T(Xe.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ot.createElement(dn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new cl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=_o.get(t.strings);return i===void 0&&_o.set(t.strings,i=new Ot(t)),i}k(t){Fs(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new mt(this.O(Wt()),this.O(Wt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Mo(t).nextSibling;Mo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Di=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=ft(this,t,i,0),n=!_t(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=ft(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!_t(p)||p!==this._$AH[c],p===F?t=F:t!==F&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},dl=class extends Di{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},pl=class extends Di{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},hl=class extends Di{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=ft(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},ul=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){ft(this,t)}};const fl={I:mt},gl=zs.litHtmlPolyfillSupport;gl?.(Ot,mt),(zs.litHtmlVersions??=[]).push("3.3.3");const ml=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new mt(t.insertBefore(Wt(),r),r,void 0,i??{})}return o._$AI(e),o};const Bs=globalThis;let C=class extends dt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=ml(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};C._$litElement$=!0,C.finalized=!0,Bs.litElementHydrateSupport?.({LitElement:C});const vl=Bs.litElementPolyfillSupport;vl?.({LitElement:C});(Bs.litElementVersions??=[]).push("4.2.2");const D=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const bl={attribute:!0,type:String,converter:di,reflect:!1,hasChanged:Ns},wl=(e=bl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?wl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const yl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return yl(i,s,{get(){return r(this)}})}}async function S(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Sl(n)??o.statusText)}const r=await o.json();return t(r)}function Sl(e){if(xl(e))return typeof e.error=="string"?e.error:void 0}function xl(e){return typeof e=="object"&&e!==null}const Ze={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},kl=Object.values(Ze),$l=new Set(kl);function Pl(e){return typeof e=="string"&&$l.has(e)}function ht(e,t){return e?.capabilities?.includes(t)===!0}function ut(e){return typeof e=="object"&&e!==null}function y(e){if(!ut(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function le(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Rl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Il(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Cl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:Rl(t.messages),start:le(t,"start"),total:le(t,"total")}}function Ml(e){const t=y(e);return N(pn)(t.machines)}function pn(e){const t=y(e),i=El(t,"kind"),s=$(t,"baseUrl"),o=hn(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Al(e){const t=y(e),i=hn(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:hi(t.web)},...t.sessiond===void 0?{}:{sessiond:hi(t.sessiond)},...s===void 0?{}:{error:s}}}function Tl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:fn(t.components)},...t.capabilities===void 0?{}:{capabilities:Us(t.capabilities)},...i===void 0?{}:{error:i}}}function El(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function hn(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Oo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Dl(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function ms(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:le(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function xt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:le(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Wl)(t.queuedMessages),...b("messageCount",Pe(t,"messageCount")),tokens:_l(t.tokens),cost:le(t,"cost"),...Ol(t.model),...Ql(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Wl(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function _l(e){const t=y(e);return{input:le(t,"input"),output:le(t,"output"),cacheRead:le(t,"cacheRead"),cacheWrite:le(t,"cacheWrite"),total:le(t,"total")}}function un(e){const t=y(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",Pe(t,"contextWindow")),...b("reasoning",t.reasoning)}}function Ol(e){return e===void 0?{}:{model:un(e)}}function Ll(e){const t=y(e);return{models:N(un)(t.models)}}function jl(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Nl(e){const t=y(e);return{levels:N(jl)(t.levels)}}function zl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Fl(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Bl(e){const t=y(e),i=t.source===void 0?void 0:Fl(t.source);return{configured:E(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function Ul(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:zl(t.authType),status:Bl(t.status)}}function Hl(e){const t=y(e);return{providers:N(Ul)(t.providers)}}function Vt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:ql(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Kl(t.auth)),...b("prompt",Vl(t.prompt)),...b("select",Gl(t.select))}}function ql(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Kl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function Vl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Gl(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(mn)(t.options)}}function Ql(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Ho(t,"tokens"),contextWindow:le(t,"contextWindow"),percent:Ho(t,"percent")}}}function Zl(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...b("description",$(t,"description"))}}function vs(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Jl(e){const t=y(e);return{path:m(t,"path"),entries:N(Xl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function Xl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...b("size",Pe(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function Yl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",ec(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:le(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function ec(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function tc(e){const t=y(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",Pe(t,"ahead")),...b("behind",Pe(t,"behind")),files:N(ic)(t.files)}}function ic(e){const t=y(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Lo(t.index),workingTree:Lo(t.workingTree)}}function Lo(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function sc(e){const t=y(e);return{...b("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Vi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...b("exitCode",Pe(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Dt(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:oc(t.status),...b("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:rc(t.metadata,"metadata")}}function oc(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function rc(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function nc(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ac(e){const t=y(e);return{workspaces:N(nc)(t.workspaces),generatedAt:m(t,"generatedAt")}}function jo(e){const t=y(e);return{path:m(t,"path"),exists:E(t,"exists"),config:No(t.config),effectiveConfig:No(t.effectiveConfig),envOverrides:gc(t.envOverrides)}}function No(e){const t=y(e);return{...b("host",$(t,"host")),...b("port",Pe(t,"port")),...b("allowedHosts",lc(t.allowedHosts)),...b("shortcuts",uc(t.shortcuts)),...b("plugins",fc(t.plugins)),...b("pathAccess",cc(t.pathAccess)),...b("maxUploadBytes",Pe(t,"maxUploadBytes")),...b("spawnSessions",Uo(t,"spawnSessions")),...b("subsessions",Uo(t,"subsessions"))}}function lc(e){if(e!==void 0){if(e===!0)return!0;if(pc(e))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function cc(e){if(e===void 0)return;if(!ut(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",dc(t,"pathAccess.allowedPaths"))}}function dc(e,t){if(e!==void 0){if(hc(e))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function pc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function hc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}function uc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function fc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!ut(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!ut(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function gc(e){const t=y(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function mc(e){const t=y(e);return{plugins:N(vc)(t.plugins)}}function vc(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:bc(t.scope),machineSpecific:wc(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function bc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function wc(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function yc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:xc(t.components),release:$c(t.release),commands:Pc(t.commands),messages:N(Rc)(t.messages)}}function Sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fn(t.components),capabilities:Us(t.capabilities)}}function xc(e){const t=y(e);return{web:hi(t.web),sessiond:hi(t.sessiond)}}function fn(e){const t=y(e);return{web:zo(t.web),sessiond:zo(t.sessiond)}}function zo(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Us(t.capabilities),...b("error",$(t,"error"))}}function hi(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...b("installation",kc(t.installation)),...b("error",$(t,"error"))}}function kc(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function $c(e){const t=y(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function Pc(e){const t=y(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function Rc(e){const t=y(e);return{id:m(t,"id"),severity:Ic(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function gn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Us(e){if(!Array.isArray(e)||!e.every(Pl))throw new Error("Invalid PI WEB capabilities");return e}function Ic(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Fo(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(mn)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...Cc(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function mn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function Cc(e){return e===void 0?{}:{session:ms(e)}}function Gt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Mc(e){const t=y(e);return N(Ac)(t.attachments)}function Ac(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:le(t,"size")}}function bs(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Tc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Ec(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Bo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Il(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Dc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Wc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function _c(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Oc(e){if(y(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Uo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Ho(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function b(e,t){return t===void 0?{}:{[e]:t}}function Lc(e){return typeof e=="string"?e:e.id}function jc(e){return typeof e=="string"?void 0:e.cwd}function Nc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function zc(e,t,i="local"){const s=new URLSearchParams,o=jc(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Lc(e))}/messages${r===""?"":`?${r}`}`}function Fc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const A=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Bc(e){return typeof e=="string"?e:e.id}function vn(e){return typeof e=="string"?void 0:e.cwd}function bn(e,t="local"){return`${A(t)}/sessions/${encodeURIComponent(Bc(e))}`}function V(e,t,i="local"){return`${bn(e,i)}/${t}`}function Qt(e,t,i="local"){return`${V(e,t,i)}${wn(e)}`}function Uc(e,t="local"){return`${bn(e,t)}${wn(e)}`}function wn(e){const t=vn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=vn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const yn={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${A(e)}/pi-web/status`,yc),piWebRuntime:()=>S("/api/pi-web/runtime",Sc)},Hc={machines:()=>S("/api/machines",Ml),addMachine:e=>S("/api/machines",pn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>S(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>S(`/api/machines/${encodeURIComponent(e)}/health`,Al),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,Tl)},ui={config:()=>S("/api/config",jo),saveConfig:e=>S("/api/config",jo,{method:"PUT",body:JSON.stringify({config:e})})},ws={plugins:()=>S("/api/plugins",mc)},Sn={workspaceActivity:(e="local")=>S(`${A(e)}/activity`,ac)},qc={projects:(e="local")=>S(`${A(e)}/projects`,N(Oo)),addProject:(e,t,i,s="local")=>S(`${A(s)}/projects`,Oo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${A(t)}/projects/${encodeURIComponent(e)}`,bs,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${A(t)}/project-directories?q=${encodeURIComponent(e)}`,N(vs))},ys={workspaces:(e,t="local")=>S(`${A(t)}/projects/${e}/workspaces`,N(Dl)),deleteWorkspace:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Dt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Jl),workspaceFile:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Yl)},Kc={sessions:(e,t="local")=>S(`${A(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ms)),startSession:(e,t="local")=>S(`${A(t)}/sessions`,ms,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(zc(e,t,i),Cl),status:(e,t="local")=>S(Qt(e,"status",t),xt),models:(e,t="local")=>S(Qt(e,"models",t),Ll),setModel:(e,t,i,s="local")=>S(V(e,"model",s),xt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(V(e,"model/cycle",i),xt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Qt(e,"thinking-levels",t),Nl),setThinkingLevel:(e,t,i="local")=>S(V(e,"thinking-level",i),xt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(V(e,"thinking-level/cycle",t),xt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>S(Qt(e,"commands",t),N(Zl)),prompt:(e,t,i,s="local",o)=>S(V(e,"prompt",s),Gt,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>S(V(e,"attachments",i),Mc,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>S(V(e,"shell",i),Gt,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>S(V(e,"commands/run",i),Fo,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(V(e,"commands/respond",s),Fo,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(V(e,"abort",t),Tc,{method:"POST",body:Q(e)}),stop:(e,t="local")=>S(V(e,"stop",t),Ec,{method:"POST",body:Q(e)}),archive:(e,t="local")=>S(V(e,"archive",t),Bo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>S(V(e,"archive-tree",t),Bo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>S(V(e,"restore",t),Dc,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>S(Uc(e,t),Wc,{method:"DELETE"}),detachParent:(e,t="local")=>S(V(e,"detach-parent",t),_c,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>S(V(e,"reload",t),Oc,{method:"POST",body:Q(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return S(`${A(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Hl)},saveApiKey:(e,t,i="local")=>S(`${A(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${A(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${A(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>S(`${A(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},pt={terminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Vi)),startTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Vi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,bs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,bs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Vi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Dt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${A(t)}/terminal-command-runs${Gc(e)}`,N(Dt)),getCommandRun:(e,t="local")=>Vc(e,t),cancelCommandRun:(e,t="local")=>S(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Dt,{method:"POST"})};async function Vc(e,t){const i=await fetch(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Qc(s)??i.statusText)}return Dt(await i.json())}}function Gc(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Qc(e){if(!Zc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Zc(e){return typeof e=="object"&&e!==null}const Jc={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?S(`${A(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,N(vs)):(s.set("cwd",e),S(`${A(i.machineId)}/files?${s.toString()}`,N(vs)))}},Xc={gitStatus:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,tc),gitDiff:(e,t,i,s="local")=>S(Nc(s,e,t,i),sc)},j={...yn,...Hc,...ui,...ws,...Sn,...qc,...ys,...Kc,...pt,...Jc,...Xc};function Yc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${qs()}${Hs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function $w(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${qs()}${Hs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function ed(e="local"){return new WebSocket(`${qs()}${Hs(e)}/events`)}function Hs(e){return`/api/machines/${encodeURIComponent(e)}`}function qs(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function oi(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function td(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ye(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function xn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const kn="local";function Gi(e,t){return`${e}:${t}`}function $n(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??kn}class id{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Sn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,sd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=od(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function sd(e){const t={};for(const i of e.workspaces)xn(i)&&(t[i.cwd]=i);return t}function od(e,t){const i={...e};return xn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class rd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??j,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=nd(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function nd(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Nt(e){return e.replaceAll(":",".")}function ad(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Qi(e,t){const i=ad(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function xe(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));ld(o,s)}function ld(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const qo=Nt("core:workspace.files");class cd{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await j.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await j.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:pd(this.getState().expandedDirs,t)});return}try{const o=await j.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),xe(qo,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await j.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(dd(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),xe(qo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function dd(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function pd(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Ko=Nt("core:workspace.git");class hd{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await j.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),xe(Ko,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),xe(Ko,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([j.gitDiff(i.id,s.id,{path:t},g(this.getState())),j.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class ud{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await j.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Vo(this.getState().machineActivities,o),machineRuntimes:Vo(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...oi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await j.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await j.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Zi(this.getState().machineStatuses,t.id),machineRuntimes:Zi(this.getState().machineRuntimes,t.id),machineActivities:Zi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await j.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>j.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>j.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Zi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Vo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class fd{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await j.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await j.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await j.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Ss="pi-web:cached-new-sessions:v1",gd="browserCachedNew",vt="local";function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Go(e,t=vt,i=zt()){if(e.messageCount!==0||e.archived===!0)return;const s=Ks(i).filter(o=>o.id!==e.id||o.machineId!==t);Vs([xs(e,t),...s],i)}function xs(e,t=vt){return{...e,browserCachedNew:!0,machineId:t}}function Qo(e,t=vt,i=zt()){const s=Ks(i).filter(o=>o.id!==e||o.machineId!==t);Vs(s,i)}function md(e,t,i=vt,s=zt()){const o=new Set(t.map(c=>c.id)),r=Ks(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Vs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ee(e){return e===void 0?!1:wd(e)&&e.browserCachedNew===!0}function vd(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:vt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ks(e=zt()){try{const t=e?.getItem(Ss);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>bd(s)):[]}catch{return[]}}function Vs(e,t=zt()){try{e.length===0?t?.removeItem(Ss):t?.setItem(Ss,JSON.stringify(e))}catch{}}function bd(e){if(!yd(e))return[];const t=at(e,"id"),i=at(e,"path"),s=at(e,"cwd"),o=at(e,"created"),r=at(e,"modified"),n=at(e,"firstMessage"),a=Sd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Ji(e,"name"),p=Ji(e,"parentSessionPath"),u=Ji(e,"machineId")??vt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function wd(e){return gd in e}function yd(e){return typeof e=="object"&&e!==null}function at(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ji(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Sd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function xd(e){return jd(e.flatMap(Gs)).filter(t=>t.parts.length>0)}function Te(e,t){return{role:e,parts:[{type:"text",text:t}]}}function kt(e,t){const i=Ad(t);return i===void 0?e:{...e,meta:i}}function kd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Te(t,i)]}function $d(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Gs(e){if(Rd(e))return[e];if(W(e,"role")==="bashExecution")return[kt(Dd(e),e)];const t=Wd(W(e,"role")),i=_d(fe(e,"content"),e),s=t==="user"?Id(i):void 0;if(s!==void 0)return s.map(p=>kt(p,e));const o=Md(e);if(t==="tool")return[kt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[kt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Pd(e);return c===void 0?a:[...a,kt(c,e)]}function Pd(e){if(W(e,"role")!=="assistant"||W(e,"stopReason")!=="error")return;const t=W(e,"errorMessage")?.trim();return Te("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Rd(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Id(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Cd(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Cd(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Md(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ad(e){const t=Td(fe(e,"timestamp")),i=Ed(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Td(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Ed(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Dd(e){const t=W(e,"command")??"",i=ri(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",gi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${gi(o)}`),ri(e,"cancelled")===!0&&i.push("","cancelled"),ri(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function Wd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function _d(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=W(i,"type"),o=W(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=W(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=W(i,"name")??"tool",n=fe(i,"arguments"),a=W(i,"id"),c=r==="read"?Ld(W(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:Ft(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=W(i,"data"),n=W(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return Zo(i)}).map(i=>i.type==="text"&&W(t,"role")==="toolResult"?Od(i.text,t):i):Zo(e)}function Od(e,t){const i=W(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:W(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ri(t,"isError")===!0}}function Ld(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function jd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Nd(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&zd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function Nd(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function zd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=fi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function fi(e){const t=fe(e,"preview");if(!Qs(t))return;const i=W(t,"diff"),s=W(t,"error"),o=Bd(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Zo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Ft(e)}]:[{type:"text",text:gi(e)}]}function Ft(e){if(!Qs(e))return gi(e);const t=W(e,"command");if(t!==void 0)return t;const i=W(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${Fd(n)}`).join(" · ")}function Fd(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function Qs(e){return typeof e=="object"&&e!==null}function fe(e,t){return Qs(e)?e[t]:void 0}function W(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function ri(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function Bd(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function gi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Ud="pi-web:prompt-draft:";function mi(e){return`${Ud}${e}`}function Wi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Pn(e,t=Wi()){try{return t?.getItem(mi(e))??""}catch{return""}}function vi(e,t,i=Wi()){try{t?i?.setItem(mi(e),t):i?.removeItem(mi(e))}catch{}}function Zs(e,t=Wi()){try{t?.removeItem(mi(e))}catch{}}function Hd(e,t,i=Wi()){const s=Pn(e,i);s!==""&&(vi(t,s,i),Zs(e,i))}function qd(e,t){return Te("bash",`${t===!0?`excluded from context
6
-
7
- `:""}$ ${e}`)}function Kd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Te("bash",t)];const o=Gd(s.text)?"":`
8
-
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Vd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
10
-
11
- `)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash command failed"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`full output: ${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
-
13
- ${o.join(`
14
- `)}`}]}]}function Gd(e){const t=e.lastIndexOf(`
15
-
16
- `),i=e.lastIndexOf("$ ");return t>i}function Qd(e,t){if(t.type==="message.append")return cp(e,t.message);if(t.type==="assistant.delta")return kd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return $d(e,t.text);if(t.type==="tool.start")return ep(e,t);if(t.type==="tool.update")return In(e,t.toolCallId,i=>tp(i,t));if(t.type==="tool.end")return Rn(e,t.toolCallId,t.toolName,Ft(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,qd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Kd(e,t.chunk);if(t.type==="shell.end")return Vd(e,t);if(t.type==="command.output")return[...e,Te(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Te("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Zd(e,t.message)}function Zd(e,t){const i=ip(t);if(i!==void 0)return Rn(e,i.toolCallId,i.toolName,Ft(i.content),i.text,i.isError,i.content,i.details);const s=Gs(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Xd(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Jd(r,n),e)}function Jd(e,t){const i=sp(e,t);if(i.length>0)return op(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||lp(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Xd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Yd(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function ep(e,t){const i=t.toolName==="read"?Yd(Je(t.args,"path")):void 0;if(i!==void 0)return dp(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Ft(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function tp(e,t){const i=fi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Rn(e,t,i,s,o,r,n,a){const c=In(e,t,h=>{const f=fi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=fi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function In(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function ip(e){if(Je(e,"role")!=="toolResult")return;const t=Je(e,"toolCallId"),i=wi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Je(e,"toolName")??"tool",text:Cn(i),isError:fp(e,"isError")===!0,content:i,details:wi(e,"details")}}function Cn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Cn).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=Je(e,"text")??Je(e,"content")??Je(e,"output");if(t!==void 0)return t}return""}function sp(e,t){const i=bi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=An(e)+1;for(let n=e.length-1;n>=r;n--){const a=bi(e[n]);if(a.length===0)continue;const c=o-a.length;if(!(c<0)&&ap(a,i.slice(c,o))&&(s.unshift(n),o=c,o===0))return s}return[]}function op(e,t,i){const s=rp(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const c=e[a];c!==void 0&&!r.has(a)&&n.push(c)}return n}function rp(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return np(e[o])?[o,...t]:t}function np(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function bi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function ap(e,t){return e.length===t.length&&e.every((i,s)=>Mn(i,t[s]))}function Mn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Jo(e.path)===Jo(t.path)||e.name===t.name}function Jo(e){return e.replace(/\\/g,"/")}function lp(e,t){return Xo(e)===Xo(t)}function Xo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
-
19
- `)}function cp(e,t){const i=Gs(t);return i.length===0?e:[...e,...i]}function dp(e,t){const i=e.at(-1);return pp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function pp(e,t){const i=bi(t);if(t.role!=="skill"||i.length===0)return!1;const s=An(e)+1;return i.every(o=>hp(e,o,s))}function hp(e,t,i){for(let s=e.length-1;s>=i;s--)if(bi(e[s]).some(o=>Mn(o,t)))return!0;return!1}function An(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function up(e){return typeof e=="object"&&e!==null}function wi(e,t){return up(e)?e[t]:void 0}function Je(e,t){const i=wi(e,t);return typeof i=="string"?i:void 0}function fp(e,t){const i=wi(e,t);return typeof i=="boolean"?i:void 0}const gp="pi-web:chat-history:v2:",mp=1800*1e3;function vp(e){try{const t=sessionStorage.getItem(yi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!kp(i))return;if(Date.now()-i.savedAt>mp){sessionStorage.removeItem(yi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function bp(e,t){try{sessionStorage.setItem(yi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function wp(e){try{sessionStorage.removeItem(yi(e))}catch{}}function yp(e,t){if(e===void 0||!ks(e))return t;if(!ks(t))return e;if(Sp(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return Yo(o,i,e),Yo(o,i,t),xp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Sp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function xp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Yo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function yi(e){return`${gp}${e}`}function kp(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&ks({messages:t,start:i,total:s})}function ks(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some($p)}function $p(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Pp={read:vp,write:bp,remove:wp};class Rp{constructor(t=Pp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return er(this.rawHistoryPage(t))}mergeHistory(t,i){const s=yp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),er(s)}applyLiveEvent(t,i){return Qd(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function er(e){const t=e?.start??0;return{messages:xd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Tn(e,t=e.length){const i=e.slice(0,t),s=Ip(i,t);if(s!==void 0)return s;const o=Cp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
- `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function En(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Ip(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Cp(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),o=tr(s,"@ "),r=tr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function tr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Mp(e[i-1]))return i;return-1}function Mp(e){return e===" "||e===" "}function Js(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Tp(e).startsWith("/")?{kind:"command"}:Tn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Ap(e){return Js(e).kind==="shell"}function Tp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class Ep{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Wn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Yc(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Dn(t);Dp(i)&&this.onEvent?.(i)}}class ir{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Wn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=ed(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Dn(t);_p(i)&&this.onEvent?.(i)}}function Dp(e){const t=Xs(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function Wp(e){const t=Xs(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function _p(e){const t=Xs(e);return Wp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Xs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Dn(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Wn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Bt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class _i{constructor(t,i,s=Bt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of Op(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Ys(e){return typeof e=="string"&&e!==""?e:void 0}function Op(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!Lp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function Lp(e){return!jp(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function jp(e){return typeof e=="object"&&e!==null}class Np{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const zp="pi-web:session-selection:v1";class Fp{constructor(t=Bt()){this.sessionIdsByCwd=new _i(zp,Ys,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Bp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Hp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function Up(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Hp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function qp(e,t,i){return $s(e,[t],i)}function $s(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Kp(e,t,i){return Ps(e,t,[i])}function Ps(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const $t=100;class Vp{constructor(t,i,s,o=new Np,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Ep,this.api=r.api??j,this.transcripts=r.transcripts??new Rp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Up(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Go(s,i);const o=xs(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Bp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:$t},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:$t},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ee(t)&&ih(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Ap(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=g(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(v=>En(v.path,!1)).join(" "),f=t===""?h:`${t}
23
-
24
- ${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:_n(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Te("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=qp(i.sessions,t.id,new Date().toISOString()),o=Kp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ee(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=$s(o.sessions,s,new Date().toISOString()),n=Ps(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=sr(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=or(o);if(r.length>0){const n=this.getState(),a=$s(n.sessions,r,new Date().toISOString()),c=Ps(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=sr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!ht(o,Ze.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=or(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Qo(t.id,g(this.getState())),Zs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||ee(t)||t.archived===!0)return;const i=g(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!ht(s,Ze.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:$t},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=Qp(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return $n(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);Go(o,s),Hd(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Qo(t.id,s);const r=xs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(vd(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Te(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&vi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ye(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Yp(i,t.sessionId,t.messageCount),...s?{sessionActivities:Gp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(eh(t))return}if(th(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Gp(e,t){return _n(e,t)}function _n(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function sr(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function or(e){return e.filter(Zp).map(t=>t.value)}function Qp(e){return e.filter(Jp).map(t=>Xp(t.reason))}function Zp(e){return e.status==="fulfilled"}function Jp(e){return e.status==="rejected"}function Xp(e){return e instanceof Error?e.message:String(e)}function Yp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function eh(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function th(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function ih(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class sh{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const oh="pi-web:workspace-selection:v1";class rh{constructor(t=Bt()){this.workspaceIdsByProject=new _i(oh,Ys,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function nh(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class ah{constructor(t,i,s,o,r=new sh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??j}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...oi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Gi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...oi()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=nh(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Gi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Gi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...oi()});try{const o=md(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=ch(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function lh(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function ch(e){return e.find(t=>t.isMain)??e[0]}const dh="pi-web:machine-navigation:v1";class ph{constructor(t=Bt()){this.snapshotsByMachine=new _i(dh,uh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?ar(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,ar(t))}forget(t){this.snapshotsByMachine.delete(t)}}function hh(e){return{machineId:e,surface:{}}}function rr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??kn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function nr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function ar(e){return{...e,surface:{...e.surface}}}function uh(e){if(!Ln(e))return;const t=Oe(e,"machineId");if(t===void 0)return;const i=On(Oe(e,"tool")),s=gh(Oe(e,"view"));return{machineId:t,projectId:Oe(e,"projectId"),workspaceId:Oe(e,"workspaceId"),sessionId:Oe(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:fh(e.surface)}}function fh(e){return Ln(e)?{selectedFilePath:Oe(e,"selectedFilePath"),selectedDiffPath:Oe(e,"selectedDiffPath"),selectedTerminalId:Oe(e,"selectedTerminalId")}:{}}function gh(e){return e==="navigation"||e==="chat"?e:On(e)}function On(e){return mh(e)?e:void 0}function mh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Oe(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Ln(e){return typeof e=="object"&&e!==null}const vh="pi-web:terminal-selection:v1";class bh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(vh,Ys,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Pw(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Rw(e){return e.find(t=>!t.exited)??e[0]}const jn=1200,wh=["mod","alt","shift"];class yh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=zn(t);if(o===void 0)return!1;const r=eo(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Lt(o))return!1}else if(!Lt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Ah(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>to(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},jn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function eo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Sh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(Rs)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort($h),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Ph(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:lr(u),v=h?[...a.get(p)??[]].sort(Rs).map(lr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Xi(e){return Fn(e,{requireFirstChordActivator:!0})}function Nn(e){const t=Fn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ni(e){return Nn(e).map(t=>t.split("+").map(Un).join("+")).join(" ")}function zn(e){if(e.isComposing)return;const t=Ch(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function Lt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Sh(e,t,i){const s=xh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Nn(o),n=r[0];if(!(n===void 0||!Lt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:kh(r),order:i}}function xh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function kh(e){return e.join("\0")}function lr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Rs(e,t){return cr(e.source)-cr(t.source)||dr(e.action.id,t.action.id)||dr(e.action.title,t.action.title)||e.order-t.order}function $h(e,t){return e.tokens.length-t.tokens.length||Rs(e,t)}function Ph(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&to(e.tokens,i.tokens))}function cr(e){switch(e){case"custom":return 0;case"default":return 1}}function dr(e,t){return e<t?-1:e>t?1:0}function Fn(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Rh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Rh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=Ih(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Un(n)} modifiers.`};i.add(n);continue}const a=Bn(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...wh.filter(r=>i.has(r)),s].join("+")}}function Ih(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function Bn(e){const t=Mh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Ch(e){if(e===" ")return"space";const t=e.toLowerCase();return Bn(t)}function Mh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Un(e){return e==="mod"?pr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?pr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Ah(e,t){return e.length===t.length&&to(e,t)}function to(e,t){return t.every((i,s)=>e[s]===i)}function pr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const io="themes:classic",Th="themes:pi-web-dark",Eh={themeId:Th,auto:!0},Hn="pi-web-app-theme",Dh=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],Wh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function _h(){try{const e=window.localStorage.getItem(Hn);return e===null?void 0:zh(e)}catch{return}}function Oh(e){try{window.localStorage.setItem(Hn,JSON.stringify(e))}catch{}}function Lh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Dh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function jh(e){const t=Nh(e.themes,e.fallbackThemeId??io),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=qn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function Nh(e,t=io){return e.find(i=>i.id===t)??e[0]}function qn(e,t){return e.find(i=>i.light===t||i.dark===t)}function zh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Fh(i)?i:void 0}catch{return}}function Fh(e){if(!Bh(e))return!1;const t=e.themeId,i=e.auto;return Uh(t)&&typeof i=="boolean"}function Bh(e){return typeof e=="object"&&e!==null}function Uh(e){return typeof e=="string"&&Wh.test(e)}const Hh="workspace.delete",qh="pi.operation",Kh="target.workspaceId";function Vh(e){return{...e===void 0?{}:{projectId:e},metadata:{[qh]:Hh}}}function Gh(e){const t={};for(const i of e){const s=Is(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function Qh(e){return Object.entries(e).filter(([,t])=>Si(t)).map(([t])=>t)}function Kn(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&Si(i)}function Is(e){return e.metadata[Kh]}function Si(e){return e.status==="queued"||e.status==="running"}function Zh(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the PI WEB color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:hr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Pt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:hr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Pt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Jh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Pt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Xh,run:e=>e.archiveSession()},{id:"session.reload",title:"Reload Session",description:"Re-read the selected session from disk to pick up entries written by another process",group:"Session",enabled:eu,run:e=>e.reloadSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Yh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ye(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Pt(e){return e.state.selectedWorkspace!==void 0}function hr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Jh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Kn(e.state,t)}function Xh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function Yh(e){return ee(e.state.selectedSession)}function eu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[g(e.state)];return i?.ok!==!0||!ht(i,Ze.sessionsReload)?!1:!Ye(e.state.status,e.state.activity)}const tu="modulepreload",iu=function(e){return"/"+e},ur={},Vn=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=iu(p),p in ur)return;ur[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":tu,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},su=10*1024*1024,ou="10 MB";function ru(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ai(e)}function ai(e){switch(e){case"navigation":return he`
25
- <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
26
- <circle cx="6" cy="7" r="1.5"></circle>
27
- <path d="M10 7h8"></path>
28
- <circle cx="6" cy="12" r="1.5"></circle>
29
- <path d="M10 12h8"></path>
30
- <circle cx="6" cy="17" r="1.5"></circle>
31
- <path d="M10 17h8"></path>
32
- </svg>
33
- `;case"chat":return he`
34
- <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
35
- <path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
36
- <path d="M8 9h8"></path>
37
- <path d="M8 13h5"></path>
38
- </svg>
39
- `;case"files":return he`
40
- <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
41
- <path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
42
- </svg>
43
- `;case"git":return he`
44
- <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
45
- <circle cx="6" cy="6" r="2"></circle>
46
- <circle cx="18" cy="6" r="2"></circle>
47
- <circle cx="12" cy="18" r="2"></circle>
48
- <path d="M8 6h6"></path>
49
- <path d="M6 8v2a6 6 0 0 0 6 6"></path>
50
- <path d="M18 8v2a6 6 0 0 1-6 6"></path>
51
- </svg>
52
- `;case"terminal":return he`
53
- <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
54
- <rect x="3" y="5" width="18" height="14" rx="2"></rect>
55
- <path d="m7 10 3 3-3 3"></path>
56
- <path d="M12 16h5"></path>
57
- </svg>
58
- `}}function nu(){return[{id:"workspace.files",title:"Files",icon:ai("files"),order:10,render:au},{id:"workspace.git",title:"Git",icon:ai("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:hu},{id:"workspace.terminal",title:"Terminal",icon:ai("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:pu}]}function au(e){return l`
59
- <section class="toolbar">
60
- <strong>Files</strong>
61
- ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
62
- <button @click=${e.onRefreshFiles}>Refresh</button>
63
- </section>
64
- <section class="split">
65
- <div class="list tree">
66
- ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Gn(e,t,0))}
67
- </div>
68
- <div class="viewer">
69
- ${cu(e)}
70
- </div>
71
- </section>
72
- `}function Gn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
73
- <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{lu(e,t)}}>
74
- <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
75
- <span>${t.name}</span>
76
- </button>
77
- ${o?s.map(n=>Gn(e,n,i+1)):null}
78
- `}function lu(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function cu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?du(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${Cs(t.size)}</p>`:(Qn(),l`
79
- <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
80
- <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
81
- `)}function du(e,t){const i=`${t.mimeType??"image"} · ${Cs(t.size)}`;if(t.size>su)return l`
82
- <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
83
- <p class="muted">Image too large to preview: ${Cs(t.size)} · limit ${ou}</p>
84
- `;const s=Fc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
85
- <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
86
- <div class="image-preview">
87
- <img src=${s} alt=${t.path} decoding="async" />
88
- </div>
89
- `}function pu(e){return gu(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function hu(e){const t=e.gitStatus;return l`
90
- <section class="toolbar">
91
- <strong>Git</strong>
92
- ${e.gitStale?l`<span class="stale">stale</span>`:null}
93
- <button @click=${e.onRefreshGit}>Refresh</button>
94
- </section>
95
- <section class="split">
96
- <div class="list">
97
- ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
98
- <p class="summary">${mu(t)}</p>
99
- ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
100
- <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
101
- <span>${vu(i.index,i.workingTree)}</span>
102
- <span>${i.path}</span>
103
- </button>
104
- `)}
105
- `:l`<p class="muted">Not a git repository.</p>`}
106
- </div>
107
- <div class="viewer">
108
- ${uu(e)}
109
- </div>
110
- </section>
111
- `}function uu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
112
- <div class=${s.length===1?"diffs single":"diffs"}>
113
- ${s.map(o=>fu(o))}
114
- </div>
115
- `}function fu(e){return Qn(),l`
116
- <section class="diff-section">
117
- <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
118
- <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
119
- </section>
120
- `}function Qn(){Vn(()=>import("./CodeViewer-Bv8l_MFi.js"),__vite__mapDeps([0,1,2,3]))}function gu(){Vn(()=>import("./TerminalPanel-BZKsaE9s.js"),__vite__mapDeps([4,5,6,1,2]))}function mu(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function vu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Cs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Yi(t)} KB`;const i=t/1024;return i<1024?`${Yi(i)} MB`:`${Yi(i/1024)} GB`}function Yi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const bu={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Zh(),workspacePanels:nu()}})},wu={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},yu={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Su={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},xu={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:yu},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Su},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:wu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ku=/^[a-z][a-z0-9.-]*$/u;function $u(e){return ku.test(e)}const Pu="machine.";function Ru(e,t){if(e==="")throw new Error("Machine id is required");if(!$u(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Pu}${Iu(e)}.${t}`}function Iu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function fr(e="/pi-web-plugins/manifest.json",t={}){const i=await Cu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=Tu(n,r);s.push({id:t.machineId===void 0?o.id:Ru(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function Cu(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return Mu(await t.json())}}function Mu(e){if(!xi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!xi(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:Au(t.machineSpecific)}})}}function Au(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function Tu(e,t){if(!xi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Eu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Eu(e){return xi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function xi(e){return typeof e=="object"&&e!==null}const Du=/^[a-z][a-z0-9.-]*$/u,Wu=/^[a-z][a-z0-9.-]*$/u,Zn=new WeakMap,Jn=new WeakMap;class _u{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&Nu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Fu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=Ou(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(es(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(es(c,t)):void 0},render:c=>i.render(es(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Du.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Wu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${zu(i)}`);return i}}function Ou(e,t){return Zn.get(e)?.(t)??e}function es(e,t){return Jn.get(e)?.(t)??e}function Lu(e,t){return Zn.set(e,t),e}function ju(e,t){return Jn.set(e,t),e}function Nu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function zu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Fu(e){return e.state.selectedMachine?.id??"local"}const Bu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Uu(){return typeof window>"u"||!("matchMedia"in window)?[]:Bu.map(e=>window.matchMedia(e))}function gr(e,t=Hu()){return e.some(i=>i.matches)||qu(t)}function Hu(){return typeof navigator>"u"?void 0:navigator}function qu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Ku=250;class Vu{constructor(t=Gu()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},Ku)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Gu(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Qu="(max-width: 760px)";class Zu{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=gr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Ju(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Uu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Vu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=gr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Ju(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Qu)}const ki=["machines","projects","workspaces","sessions"];function Xu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function so(e,t){if(e!=="none")return e??Xu(t)}function Yu(e,t){return t.isMobileLayout?so(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function ef(e,t,i){return so(e,i.state)===t?"none":t}function tf(e,t,i){return i?t:e}function sf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),nf(i)}function of(e){return ki[ki.indexOf(e)+1]}class rf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return so(this.expanded,this.getState())}isCollapsed(t){return Yu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(ef(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(sf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(tf(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=of(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){af(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function nf(e){const t=new Set(e);return ki.filter(i=>t.has(i))}function af(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class lf{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Xn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Xn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ms="pi-web:panel-sizes:v1",cf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class df{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??oo(),this.panelSizes=ff(this.storage)}hostConnected(){}constraints(t){return Ut(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=vf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=bf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){gf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${vr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${vr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ut(e){return cf[e]}function pf(e,t,i){return e==="navigation"?i-t:t-i}function hf(e,t,i,s,o=Ut(e)){return ue(e,t+pf(e,i,s),o)}function uf(e,t,i,s={}){const o=s.constraints??Ut(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=wf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ut(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function ff(e=oo()){try{const t=e?.getItem(Ms);if(t==null||t==="")return{};const i=JSON.parse(t);return mf(i)}catch{return{}}}function gf(e,t=oo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ms);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(Ms,JSON.stringify(i))}catch{}}function mf(e){if(!yf(e)||e.version!==1)return{};const t={},i=mr(e.navigationPanelWidth),s=mr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function mr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function vf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function bf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function wf(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function vr(e){return`${String(Math.round(e))}px`}function oo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yf(e){return typeof e=="object"&&e!==null}function br(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Sf(e.get("tool")),view:xf(e.get("view"))}}function ts(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Sf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function xf(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function Yn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function wr(){return kf(new URLSearchParams(window.location.search).get("settings"))}function is(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function kf(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function $f(e,t){return t===void 0?e:e.map(i=>Rf(i,t))}function Pf(e,t){const i=new Set(eo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return $f(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ea(s):s)}function Rf(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ea(e):{...e,shortcut:i}}function ea(e){const t={...e};return delete t.shortcut,t}function If(e,t){const i=t.api??pt,s=t.pollIntervalMs??1e3,o=t.setTimeout??Mf(),r=t.clearTimeout??Af();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:Cf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Cf(e,t,i,s,o){return yr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&yr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function yr(e){return e.status==="succeeded"||e.status==="failed"}function Mf(){return(e,t)=>globalThis.setTimeout(e,t)}function Af(){return e=>{globalThis.clearTimeout(e)}}function Tf(e,t){return t[e.path]}function Ef(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Df(e,t,i){return ia(Wf(e,t,i))}function ta(e){return ia(Object.values(e??{}))}function ia(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Wf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Zt=0,_f=120;function Ht(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?sa():Of(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Zt,f=i.top-c-Zt;return[...h<_f&&f>h?[`bottom: ${lt(r-i.top+Zt)};`,`max-height: ${lt(Math.max(0,f))};`]:[`top: ${lt(i.bottom+Zt)};`,`max-height: ${lt(Math.max(0,h))};`],`right: ${lt(Math.max(0,o-u))};`,`max-width: ${lt(Math.max(0,u-n))};`].join(" ")}function Of(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():sa()}function sa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function lt(e){return`${String(Math.round(e))}px`}function oa(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Oi(e,t="Active"){const i=oa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Lf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ra(e){return e.composedPath().some(t=>jf(t,Lf))}function jf(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Li(e,t){ra(e)||t()}function ji(e,t){return ra(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Sr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Sr(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{xr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{xr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function Ni(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Sr(e,t){const i=aa(e),s=la(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||na(i,o+t)}function xr(e,t){const i=aa(e);i.length!==0&&na(i,t<0?i.length-1:t)}function na(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function aa(e){const t=la(e)?.getRootNode();return t===void 0||!Nf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Nf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function la(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const zf=O`
121
- /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
122
- :host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
123
- :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
124
- @media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
125
- :host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
126
- }
127
- .shell { --navigation-panel-size: 340px; --workspace-panel-size: minmax(360px, 42vw); --navigation-panel-width: var(--navigation-panel-size); --workspace-panel-width: var(--workspace-panel-size); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(320px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
128
- aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
129
- aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
130
- 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); }
131
- .header-actions { display: flex; align-items: center; gap: 8px; }
132
- project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
133
- session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
134
- main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
135
- .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); }
136
- .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; }
137
- .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
138
- .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
139
- .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
140
- .context-bar-label { display: none; }
141
- .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
142
- .context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
143
- .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
144
- .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; padding: 0 8px 0 0; pointer-events: none; }
145
- .context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
146
- .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
147
- .context-chip:hover { background: var(--pi-surface-hover); }
148
- .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
149
- .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
150
- .context-kind { display: none; }
151
- .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
152
- app-mobile-main-tabs { display: none; }
153
- .mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
154
- .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; }
155
- .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
156
- .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
157
- .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
158
- .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
159
- .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
160
- .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
161
- .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
162
- .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
163
- .navigation-panel-edge, .workspace-panel-edge { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
164
- .navigation-panel-edge { grid-column: 2; }
165
- .workspace-panel-edge { grid-column: 4; }
166
- .navigation-panel-edge-button, .workspace-panel-edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
167
- .navigation-panel-edge-button:hover, .navigation-panel-edge-button:focus-visible, .workspace-panel-edge-button:hover, .workspace-panel-edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
168
- .shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
169
- .shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
170
- .navigation-panel-edge-icon, .workspace-panel-edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
171
- workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
172
- @media (min-width: 1181px) {
173
- .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
174
- .shell.navigation-panel-collapsed > aside { display: none; }
175
- .shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
176
- .shell.workspace-panel-collapsed > workspace-panel { display: none; }
177
- }
178
- @media (max-width: 1180px) {
179
- .shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
180
- .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
181
- .shell.navigation-panel-collapsed > aside { display: none; }
182
- aside { grid-row: 1 / 3; }
183
- .navigation-panel-edge { grid-row: 1 / 3; }
184
- main { grid-column: 3; grid-row: 1 / 3; }
185
- app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
186
- .mobile-tabs-frame { display: flex; }
187
- .shell.workspace-view main { grid-row: 1; min-height: auto; }
188
- .shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
189
- .shell:not(.workspace-view) > workspace-panel { display: none; }
190
- .workspace-panel-edge { display: none; }
191
- main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
192
- main.workspace-view .empty { display: none; }
193
- main.workspace-view { overflow: hidden; }
194
- }
195
- @media (max-width: 760px) {
196
- .shell { grid-template-columns: minmax(0, 1fr); }
197
- aside, .navigation-panel-edge { display: none; }
198
- main, .shell.workspace-view > workspace-panel { grid-column: 1; }
199
- .context-bar { display: flex; }
200
- .mobile-navigation-tab { display: block; }
201
- main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
202
- main.navigation-view .empty { display: none; }
203
- main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
204
- main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
205
- main.navigation-view .mobile-navigation-panel project-list,
206
- main.navigation-view .mobile-navigation-panel workspace-list,
207
- main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
208
- main.navigation-view .mobile-navigation-panel project-list[collapsed],
209
- main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
210
- main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
211
- }
212
- status-bar { flex: 0 0 auto; }
213
- chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
214
- prompt-editor { flex: 0 0 auto; }
215
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
216
- .empty { margin: auto; color: var(--pi-muted); }
217
- .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
218
- `,Ff=O`
219
- :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
220
- header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
221
- .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
222
- .workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
223
- .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
224
- .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
225
- .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
226
- .workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
227
- .tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
228
- .tabs button { flex: 0 0 auto; white-space: nowrap; }
229
- .tabs button.icon-tab { min-width: 34px; }
230
- button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
231
- button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
232
- .tab-icon { flex: 0 0 auto; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
233
- .tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
234
- .tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
235
- .tab-label { min-width: 0; }
236
- .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
237
- @container (max-width: 430px) {
238
- .tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
239
- .tabs button.icon-tab .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
240
- }
241
- .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
242
- .empty-state { box-sizing: border-box; width: min(100%, 380px); margin: auto; padding: 24px; display: grid; gap: 8px; color: var(--pi-muted); text-align: center; }
243
- .empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
244
- .empty-state p { margin: 0; line-height: 1.45; }
245
- small, .muted { color: var(--pi-muted); }
246
- @media (max-width: 1180px) { header { display: none; } }
247
- .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
248
- .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
249
- .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
250
- .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
251
- .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
252
- .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
253
- .toolbar button { margin-left: auto; }
254
- .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
255
- .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
256
- .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
257
- .row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
258
- .row:hover, .row.selected { background: var(--pi-selection-bg); }
259
- .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
260
- .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
261
- .viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
262
- .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
263
- .diffs.single { grid-template-rows: minmax(0, 1fr); }
264
- .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
265
- .diff-section:last-child { border-bottom: 0; }
266
- .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
267
- .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
268
- code-viewer { flex: 1 1 auto; min-height: 0; }
269
- .image-preview { flex: 1 1 auto; min-height: 0; box-sizing: border-box; display: flex; align-items: center; justify-content: center; overflow: auto; padding: 16px; }
270
- .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
271
- pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
272
- p { margin: 10px; }
273
- `,zi=O`
274
- :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
275
- :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
276
- section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
277
- h2 { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
278
- .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
279
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
280
- section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
281
- .subheading { margin-top: 14px; }
282
- .section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-align: left; text-transform: inherit; }
283
- .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
284
- .section-title { display: grid; gap: 2px; min-width: 0; }
285
- .section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
286
- .section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
287
- .section-toggle small { display: inline; color: inherit; font-size: inherit; }
288
- .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
289
- .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
290
- .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
291
- .action-row.archived .action-main { color: var(--pi-muted); }
292
- .action-main { position: relative; box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 22px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
293
- .action-name { display: -webkit-box; max-height: 2.5em; overflow: hidden; overflow-wrap: anywhere; line-height: 1.25; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
294
- .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
295
- .workspace-row .action-main { border-radius: 8px 0 0 8px; }
296
- .workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
297
- .workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
298
- .workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
299
- .workspace-secondary { margin-top: 3px; }
300
- .workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
301
- .workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
302
- .workspace-menu-actions button.danger { color: var(--pi-danger); }
303
- .workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
304
- .workspace-menu-details { display: grid; gap: 6px; margin: 0; }
305
- .workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
306
- .workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
307
- .workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
308
- .tree-marker { color: var(--pi-dim); margin-right: 5px; }
309
- .badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
310
- .action-activity { position: absolute; top: 5px; right: 6px; z-index: 1; display: grid; place-items: center; width: 10px; height: 10px; }
311
- .action-activity .activity-indicator { margin: 0; vertical-align: 0; }
312
- .activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
313
- .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
314
- .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
315
- /* Client-side sending (upload in flight); distinct from server activity, which propagates to workspace/machine rows. */
316
- .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
317
- .action-menu { position: relative; align-self: stretch; }
318
- .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
319
- .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
320
- .action-menu-panel { position: fixed; z-index: 50; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
321
- .action-menu-panel button { display: block; width: 100%; text-align: left; white-space: normal; overflow-wrap: anywhere; border: 0; background: transparent; color: var(--pi-text); }
322
- .action-menu-panel button:hover { background: var(--pi-selection-bg); }
323
- button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
324
- button:disabled { opacity: .5; cursor: not-allowed; }
325
- small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
326
- .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
327
- .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
328
- .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
329
- .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
330
- .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
331
- .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
332
- .workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
333
- @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
334
- `,Bf=O`
335
- :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
336
- .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
337
- .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
338
- .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
339
- .activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
340
- .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
341
- .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
342
- .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
343
- .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
344
- .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
345
- .msg.assistant { background: var(--pi-surface); }
346
- .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
347
- .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
348
- .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
349
- .msg.system { color: var(--pi-danger); }
350
- .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
351
- .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
352
- .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
353
- .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
354
- .msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
355
- .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
356
- .msg.event-group > summary .label { margin: 0; }
357
- .group-body { padding: 0 12px 12px; }
358
- .chat-image { display: block; max-width: 100%; max-height: 320px; margin: 8px 0 0; border: 1px solid var(--pi-border-muted); border-radius: 8px; object-fit: contain; }
359
- .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
360
- .group-msg.tool { color: var(--pi-warning); }
361
- .group-msg.tool-execution-shell { color: var(--pi-text); }
362
- .group-msg.system { color: var(--pi-danger); }
363
- .group-msg.bash { color: var(--pi-success); }
364
- .history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
365
- .history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
366
- .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
367
- .history-load-button:disabled { cursor: default; opacity: .55; }
368
- .queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
369
- .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
370
- .queued-header strong { color: var(--pi-warning); }
371
- .queued-header small { color: var(--pi-muted); }
372
- .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
373
- .queued-message:first-of-type { padding-top: 0; border-top: 0; }
374
- .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
375
- .session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
376
- .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
377
- .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
378
- .session-activity strong { color: var(--pi-purple); }
379
- .session-activity.receiving strong { color: var(--pi-success); }
380
- .session-activity span, .session-activity small { color: var(--pi-muted); }
381
- .history-boundary small { color: var(--pi-dim); }
382
- .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
383
- .msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
384
- .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
385
- .msg.assistant > .msg-header .label { color: var(--pi-text-secondary); }
386
- .msg.user > .msg-header .label { color: var(--pi-accent); }
387
- .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
388
- .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
389
- .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
390
- .group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
391
- .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
392
- .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
393
- .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
394
- .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
395
- .msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
396
- .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
397
- .msg-header .label { margin: 0; }
398
- .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
399
- .msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
400
- .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
401
- @media (hover: none) {
402
- .msg-actions { opacity: 1; }
403
- .msg-meta { opacity: .75; max-width: 26px; }
404
- .msg-meta::before { content: "ⓘ"; font-size: 13px; }
405
- .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
406
- .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
407
- }
408
- formatted-text.part { display: block; }
409
- .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
410
- .part + .part { margin-top: 10px; }
411
- .tool-line { color: var(--pi-warning); }
412
- .summary { color: var(--pi-muted); margin-left: 6px; }
413
- .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
414
- .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
415
- .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
416
- .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
417
- .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
418
- summary { cursor: pointer; color: var(--pi-muted); }
419
- pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
420
- .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
421
- @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
422
- `,Uf=O`
423
- :host { display: block; }
424
- .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
425
- p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
426
- :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
427
- ul, ol { padding-left: 22px; }
428
- li + li { margin-top: 3px; }
429
- code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
430
- .code-block-wrapper { position: relative; }
431
- .code-block-wrapper pre { margin: 0; padding-right: 40px; }
432
- pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
433
- pre code { border: 0; padding: 0; background: transparent; }
434
- .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
435
- .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
436
- blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
437
- a { color: var(--pi-accent); }
438
- h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
439
- h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
440
- h1 { font-size: 20px; }
441
- h2 { font-size: 17px; }
442
- h3 { font-size: 15px; }
443
- h4 { font-size: 14px; }
444
- table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
445
- th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
446
- th { background: var(--pi-surface); }
447
- `,Hf=O`
448
- :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
449
- .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
450
- span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
451
- .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
452
- .activity.active { color: var(--pi-success); }
453
- .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
454
- .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
455
- .muted { color: var(--pi-dim); }
456
- @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
457
- `,qf=O`
458
- :host { display: block; }
459
- .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
460
- 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; }
461
- button:last-child { border-bottom: 0; }
462
- button.selected, button:hover { background: var(--pi-selection-bg); }
463
- span { color: var(--pi-muted); font-size: 12px; }
464
- small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
465
- `,ca=O`
466
- :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
467
- .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
468
- section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
469
- header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
470
- .options { min-height: 0; overflow: auto; outline: none; }
471
- button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
472
- header button { font-size: 20px; color: var(--pi-muted); }
473
- input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
474
- input:focus { border-color: var(--pi-accent); }
475
- .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
476
- .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
477
- small { display: block; margin-top: 4px; color: var(--pi-muted); }
478
- .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
479
- `,Kf=O`
480
- :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
481
- .backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
482
- 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; }
483
- header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
484
- input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
485
- input::placeholder { color: var(--pi-dim); }
486
- button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
487
- header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
488
- .options { flex: 1 1 auto; min-height: 0; overflow: auto; }
489
- .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
490
- .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
491
- .main { min-width: 0; }
492
- strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
493
- small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
494
- .group { grid-column: 1 / -1; font-size: 12px; }
495
- kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
496
- .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
497
- `,Vf=O`
498
- :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
499
- footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
500
- footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
501
- .editor-wrap { position: relative; min-width: 0; }
502
- .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
503
- .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
504
- .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
505
- .select-model { max-width: min(42vw, 320px); }
506
- .icon-button { flex: 0 0 auto; display: inline-grid; place-items: center; width: 36px; height: 36px; padding: 0; }
507
- .icon-button .prompt-action-icon, .icon-button .prompt-thinking-gauge { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
508
- .icon-button .prompt-action-icon-filled { fill: currentColor; stroke: none; }
509
- .send-button:not(:disabled) { color: var(--pi-accent, var(--pi-text)); }
510
- .stop-button:not(:disabled) { color: var(--pi-danger); }
511
- .select-thinking .prompt-thinking-gauge .gauge-bar { fill: currentColor; stroke: none; opacity: .28; }
512
- .select-thinking .prompt-thinking-gauge .gauge-bar-active { opacity: 1; }
513
- .editor-attach { position: absolute; right: 8px; bottom: 8px; z-index: 2; width: 30px; height: 30px; }
514
- .editor-attach .prompt-action-icon { width: 16px; height: 16px; }
515
- textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
516
- textarea { overflow-y: auto; padding: 8px; }
517
- .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
518
- .markdown-editor .cm-content { min-height: 38px; padding: 8px 44px 8px 8px; caret-color: var(--pi-text); }
519
- .markdown-editor .cm-line { padding: 0; }
520
- .markdown-editor .cm-placeholder { color: var(--pi-dim); }
521
- .markdown-editor .cm-focused { outline: none; }
522
- .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
523
- .mode-hint { position: absolute; right: 46px; bottom: 8px; max-width: calc(100% - 54px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
524
- .attachments { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 8px; }
525
- .attachment-chip { position: relative; width: 56px; height: 56px; border: 1px solid var(--pi-border); border-radius: 8px; overflow: hidden; background: var(--pi-bg); }
526
- .attachment-chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
527
- .attachment-remove { position: absolute; top: 1px; right: 1px; width: 18px; height: 18px; padding: 0; line-height: 16px; border-radius: 50%; border: 1px solid var(--pi-border); background: var(--pi-surface); color: var(--pi-text); font-size: 13px; cursor: pointer; }
528
- .attachment-delivery select { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; font: 12px system-ui, sans-serif; }
529
- .attachment-error { flex-basis: 100%; color: var(--pi-danger); font-size: 12px; }
530
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
531
- button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
532
- @media (max-width: 640px) {
533
- footer { gap: 8px; padding: 8px; }
534
- .actions { gap: 6px; }
535
- .compact-status { flex: 1 1 220px; gap: 4px; }
536
- .select-model { max-width: min(58vw, 260px); }
537
- button { padding: 6px 8px; }
538
- }
539
- @media (max-width: 430px) {
540
- .compact-status { flex-basis: 170px; font-size: 11px; }
541
- .select-model { max-width: 48vw; }
542
- button { padding: 5px 7px; }
543
- .icon-button { width: 34px; height: 34px; }
544
- }
545
- `;var Gf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Gf(t,i,o),o};let J=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
546
- <section>
547
- <h2>${this.renderHeading()}</h2>
548
- ${this.collapsed?null:l`
549
- <div class="list-body">
550
- ${this.machines.map(e=>this.renderMachine(e))}
551
- </div>
552
- `}
553
- </section>
554
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=da(e)&&this.onRemove!==void 0;return l`
555
- <div
556
- class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
557
- tabindex="0"
558
- title=${e.baseUrl??e.name}
559
- @click=${o=>{Li(o,()=>this.onSelect?.(e))}}
560
- @keydown=${o=>{this.handleMachineKeydown(o,e)}}
561
- >
562
- <div class="action-main">
563
- <span class="action-name machine-primary"><span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${i}</small>
564
- ${this.renderActivity(e)}
565
- </div>
566
- ${s?this.renderMachineMenu(e):null}
567
- </div>
568
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return Oi(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=Zf(e.id);return l`
569
- <div class="action-menu">
570
- <button
571
- class="action-menu-toggle"
572
- title="Machine actions"
573
- aria-label=${`Actions for ${e.name}`}
574
- aria-expanded=${String(t)}
575
- aria-controls=${i}
576
- @click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
577
- >⋯</button>
578
- ${t?l`
579
- <div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
580
- <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
581
- </div>
582
- `:null}
583
- </div>
584
- `}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[zi,O`
585
- .machine-row.no-actions .action-main { border-radius: 8px; }
586
- .machine-primary { display: flex; align-items: baseline; gap: 6px; }
587
- .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
588
- .machine-menu-panel button.danger { color: var(--pi-danger); }
589
- .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
590
- `];ae([d({attribute:!1})],J.prototype,"machines",2);ae([d({attribute:!1})],J.prototype,"selected",2);ae([d({attribute:!1})],J.prototype,"statuses",2);ae([d({attribute:!1})],J.prototype,"activities",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([d({attribute:!1})],J.prototype,"onSelect",2);ae([d({attribute:!1})],J.prototype,"onRemove",2);ae([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ae([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ae([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);ae([w()],J.prototype,"openMenuMachineId",2);ae([w()],J.prototype,"menuStyle",2);J=ae([D("machine-list")],J);function da(e){return e.kind==="remote"}function Zf(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Jf=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Jf(t,i,o),o};let G=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
591
- <section>
592
- <h2>${this.renderHeading()}</h2>
593
- ${this.collapsed?null:l`
594
- <div class="list-body">
595
- ${this.projects.map(e=>l`
596
- <div
597
- class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
598
- tabindex="0"
599
- title=${e.path}
600
- @click=${t=>{Li(t,()=>this.onSelect?.(e))}}
601
- @keydown=${t=>{this.handleProjectKeydown(t,e)}}
602
- >
603
- <div class="action-main">
604
- <span class="action-name">${e.name}</span><small>${e.path}</small>
605
- ${this.renderActivity(e)}
606
- </div>
607
- <div class="action-menu">
608
- <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${e.name}`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
609
- ${this.openMenuProjectId===e.id?l`
610
- <div class="action-menu-panel" style=${this.menuStyle}>
611
- <button title="Close project" @click=${()=>{this.close(e)}}>Close</button>
612
- </div>
613
- `:null}
614
- </div>
615
- </div>
616
- `)}
617
- </div>
618
- `}
619
- </section>
620
- `}handleProjectKeydown(e,t){ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Df(e,this.workspacesByProjectId[e.id]??[],this.activities);return Oi(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
621
-
622
- This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};G.styles=zi;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([w()],G.prototype,"openMenuProjectId",2);ie([w()],G.prototype,"menuStyle",2);G=ie([D("project-list")],G);function kr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Yf(t)}`)}function Yf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&eg(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function eg(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var tg=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var o=s>1?void 0:s?ig(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tg(t,i,o),o};let q=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
623
- <section>
624
- <h2>${this.renderHeading()}</h2>
625
- ${this.collapsed?null:l`
626
- <div class="list-body">
627
- ${this.workspaces.map(e=>{const t=sg(e),i=this.workspaceLabelItems(e);return l`
628
- <div
629
- class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
630
- tabindex="0"
631
- title=${t}
632
- @click=${s=>{Li(s,()=>this.onSelect?.(e))}}
633
- @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
634
- >
635
- <div class="action-main">
636
- ${this.renderWorkspaceMain(t,i,e)}
637
- </div>
638
- ${this.renderWorkspaceMenu(t,i,e)}
639
- </div>
640
- `})}
641
- </div>
642
- `}
643
- </section>
644
- `}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Ef(Tf(e,this.activities));return Oi(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
645
- <span class="workspace-primary">
646
- <span class="workspace-primary-label">${e}</span>
647
- ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
648
- </span>
649
- ${t.length===0?null:l`
650
- <small class="workspace-secondary">
651
- <span class="workspace-label">${kr(t)}</span>
652
- </small>
653
- `}
654
- ${this.renderActivity(i)}
655
- `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=rg(i.id);return l`
656
- <div class="action-menu">
657
- <button
658
- class="action-menu-toggle"
659
- title="Workspace actions and details"
660
- aria-label=${`Actions and details for ${e}`}
661
- aria-expanded=${String(s)}
662
- aria-controls=${o}
663
- @click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}
664
- >⋯</button>
665
- ${s?l`
666
- <div class="action-menu-panel workspace-menu-panel" id=${o} style=${this.menuStyle} @click=${r=>{r.stopPropagation()}}>
667
- ${this.renderWorkspaceActions(i)}
668
- ${this.renderWorkspaceDetails(e,t,i)}
669
- </div>
670
- `:null}
671
- </div>
672
- `}renderWorkspaceActions(e){if(!og(e))return;const t=this.isDeleting(e);return l`
673
- <div class="workspace-menu-actions">
674
- <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
675
- </div>
676
- `}renderWorkspaceDetails(e,t,i){return l`
677
- <dl class="workspace-menu-details">
678
- <div class="workspace-detail-row">
679
- <dt>${i.branch===void 0?"Workspace":"Branch"}</dt>
680
- <dd>${e}</dd>
681
- </div>
682
- <div class="workspace-detail-row">
683
- <dt>Path</dt>
684
- <dd title=${i.path}>${i.path}</dd>
685
- </div>
686
- ${t.length===0?null:l`
687
- <div class="workspace-detail-row">
688
- <dt>Details</dt>
689
- <dd><span class="workspace-label">${kr(t)}</span></dd>
690
- </div>
691
- `}
692
- </dl>
693
- `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=zi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([w()],q.prototype,"openMenuWorkspaceId",2);X([w()],q.prototype,"menuStyle",2);q=X([D("workspace-list")],q);function sg(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function og(e){return e.isGitWorktree&&!e.isMain}function rg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var ng=Object.defineProperty,ag=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var o=s>1?void 0:s?ag(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ng(t,i,o),o};function Rt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=dg(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>It(r)==="current"),s=pa(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=lg(this.sessions);return l`
694
- <section>
695
- ${this.renderHeading(e.length+s.length,i)}
696
- ${this.collapsed?null:l`
697
- <div class="list-body">
698
- ${this.renderCurrentSelectionToolbar(i)}
699
- ${e.map(r=>this.renderSession(r,o.get(r.session.id)??0,"current"))}
700
- ${s.length>0?l`
701
- ${this.renderArchivedHeading(s.map(r=>r.session))}
702
- ${this.archivedExpanded?l`
703
- ${this.renderArchivedSelectionToolbar(s.map(r=>r.session))}
704
- ${s.map(r=>this.renderSession(r,o.get(r.session.id)??0,"archived"))}
705
- `:null}
706
- `:null}
707
- </div>
708
- `}
709
- </section>
710
- `}renderHeading(e,t){if(!this.collapsible)return l`
711
- <h2>
712
- Sessions
713
- ${this.renderCurrentSelectionButton(t)}
714
- <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
715
- </h2>
716
- `;const i=this.selected===void 0?"No session selected":Rt(this.selected),s=this.selected?.path??i;return l`
717
- <h2>
718
- <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span>${this.collapsed?l`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
719
- ${this.renderCurrentSelectionButton(t)}
720
- <small class="section-count">${e}</small>
721
- <button ?disabled=${!this.canStart} @click=${o=>{o.stopPropagation(),this.onStart?.()}}>+</button>
722
- </h2>
723
- `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<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=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
724
- <h2 class="subheading">
725
- <button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span></button>
726
- ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close archived session selection":"Select archived sessions"} aria-label=${t?"Close archived session selection":"Select archived sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
727
- <small class="section-count">${e.length}</small>
728
- </h2>
729
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ee(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
730
- <div class="bulk-row selecting">
731
- <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"Clear visible":"Select visible"}</button>
732
- <small>${t.length} selected${o!==t.length?l` · ${o} visible`:null}</small>
733
- <button ?disabled=${i.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>Archive selected</button>
734
- <button @click=${()=>{this.clearSelection("current")}}>Clear</button>
735
- <button @click=${()=>{this.closeSelection("current")}}>Done</button>
736
- </div>
737
- `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("archived"))return null;const t=this.selectedSessions("archived"),i=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),s=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
738
- <div class="bulk-row selecting">
739
- <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!i)}}>${i?"Clear visible":"Select visible"}</button>
740
- <small>${t.length} selected${s!==t.length?l` · ${s} visible`:null}</small>
741
- <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>
742
- <button @click=${()=>{this.clearSelection("archived")}}>Clear</button>
743
- <button @click=${()=>{this.closeSelection("archived")}}>Done</button>
744
- ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
745
- </div>
746
- `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=It(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
747
- <div
748
- class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
749
- style=${`--depth:${String(o)}`}
750
- tabindex="0"
751
- title=${s.path}
752
- @click=${p=>{Li(p,()=>{this.activateSessionRow(s,i)})}}
753
- @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
754
- >
755
- <div class="action-main ${n?"selecting":""}">
756
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Rt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
757
- <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Rt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} messages</small>
758
- ${this.renderActivity(s)}
759
- </div>
760
- <div class="action-menu">
761
- <button class="action-menu-toggle" title="Session actions" @click=${p=>{p.stopPropagation(),this.toggleMenu(s.id,p.currentTarget)}}>⋯</button>
762
- ${this.openMenuSessionId===s.id?l`
763
- <div class="action-menu-panel" style=${this.menuStyle}>
764
- ${ee(s)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:s.archived===!0?l`
765
- <button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(s)}}>Restore</button>
766
- <button class="danger" title=${this.canDeleteArchived?"Permanently delete archived session":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(s)}}>Delete archived session</button>
767
- `:l`
768
- <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
769
- ${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(s,t)}}>Archive with descendants (${t})</button>`:null}
770
- ${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
771
- ${this.canReload?l`<button title=${Ye(this.statuses[s.id],this.activities[s.id])?"Stop current session activity before reloading":"Reload session from disk"} ?disabled=${Ye(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(s)}}>Reload</button>`:null}
772
- `}
773
- </div>
774
- `:null}
775
- </div>
776
- </div>
777
- `}handleSessionKeydown(e,t,i){ji(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&It(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${Rt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${Rt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=ss(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=ss(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>It(i)===e).map(i=>i.id);this.selectedSessionIds=ss(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&It(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){const t=cg(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Oi(t,t==="sending"?"Sending message":"Session active")}};R.styles=[zi,O`
778
- h2 { min-height: 30px; }
779
- h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
780
- .bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
781
- .bulk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 6px; }
782
- .bulk-row button { padding: 5px 7px; font-size: 12px; }
783
- .bulk-row small { display: inline; min-width: 0; color: var(--pi-muted); }
784
- .bulk-row .capability-hint { flex: 1 0 100%; color: var(--pi-warning); }
785
- .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); }
786
- button.danger, .action-menu-panel button.danger { color: var(--pi-danger); }
787
- button.danger:hover, .action-menu-panel button.danger:hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
788
- .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
789
- .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
790
- .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
791
- `];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([w()],R.prototype,"openMenuSessionId",2);M([w()],R.prototype,"menuStyle",2);M([w()],R.prototype,"archivedExpanded",2);M([w()],R.prototype,"selectionScopes",2);M([w()],R.prototype,"selectedSessionIds",2);R=M([D("session-list")],R);function It(e){return e.archived===!0?"archived":"current"}function ss(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function lg(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function cg(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Ye(t,i)?"session":void 0}function dg(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return pa(e.filter(s=>i.has(s.id)))}function pa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const ro={CHILD:2,ELEMENT:6},no=e=>(...t)=>({_$litDirective$:e,values:t});let ao=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:pg}=fl,$r=e=>e,Pr=()=>document.createComment(""),Ct=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(Pr(),o),n=s.insertBefore(Pr(),o);i=new pg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=$r(c).nextSibling;$r(s).insertBefore(c,o),c=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),hg={},ug=(e,t=hg)=>e._$AH=t,fg=e=>e._$AH,os=e=>{e._$AR(),e._$AA.remove()};const Rr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},gg=no(class extends ao{constructor(e){if(super(e),e.type!==ro.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=fg(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=Ve(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=Ve(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Ve(o[h],r[P]),Ct(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=Ve(o[f],r[v]),Ct(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=Rr(n,v,P),u=Rr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const H=u.get(n[v]),rt=H!==void 0?o[H]:null;if(rt===null){const wt=Ct(e,o[h]);Ve(wt,r[v]),c[v]=wt}else c[v]=Ve(rt,r[v]),Ct(e,o[h],rt),o[H]=null;v++}else os(o[f]),f--;else os(o[h]),h++;for(;v<=P;){const H=Ct(e,c[P+1]);Ve(H,r[v]),c[v++]=H}for(;h<=f;){const H=o[h++];H!==null&&os(H)}return this.ut=n,ug(e,c),Ue}}),mg="pi-web:chat-groups:",vg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Ir(e));return t===null||t===""?void 0:wg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Ir(e),JSON.stringify(t))}catch{}}};class bg{constructor(t=vg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Cr(r,this.openGroupKeys)&&Cr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Ir(e){return`${mg}${e}`}function wg(e){if(Array.isArray(e))return{open:rs(e),closedDefaultOpen:[]};if(yg(e))return{open:Array.isArray(e.open)?rs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?rs(e.closedDefaultOpen):[]}}function rs(e){return e.filter(t=>typeof t=="string")}function Cr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function yg(e){return typeof e=="object"&&e!==null}function Sg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>Mr(a,v)),u=a.parts.filter(v=>!Mr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function xg(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function Mr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const kg=30;function $g(e,t){const i=Rg(Mg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Pg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ig(s,t.markerOffset);return}e.scrollTop=Cg(e.scrollHeight,t.distanceFromBottom)}function Rg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function Ig(e,t){return e-t}function Cg(e,t){return Math.max(0,e-t)}function Mg(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const Ag=600,Tg=1;function Eg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Dg(e)||Wg(e)}function Dg(e){return e.scrollTop<(e.topThreshold??Math.max(Ag,e.clientHeight))}function Wg(e){return e.scrollHeight<=e.clientHeight+Tg}const _g="pi-web:chat-scroll:",Og=180,Lg=48,jg=2,Ng={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},zg={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Fg{constructor(t=Ng,i=zg){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=Og){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=jg){if(t===""||i===void 0||!as(i))return"skipped";try{if(ua(i,o)){const a={mode:"bottom"};return this.storage.setItem(ns(t),JSON.stringify(a)),"saved"}const r=Hg(i,s);if(r===void 0)return"skipped";const n=Ug(i,r);return this.storage.setItem(ns(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!as(i))return{status:"skipped"};const r=qg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(ns(t));if(i===null||i==="")return;const s=JSON.parse(i);return Bg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!as(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ns(e){return`${_g}${e}`}function Bg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function as(e){return e.clientHeight>0&&e.scrollHeight>0}function ha(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ua(e,t=Lg){return ha(e)<t}function Ug(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:lo(t)??"",offset:t.getBoundingClientRect().top-i}}function Hg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(lo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Ar(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function qg(e,t){return e.find(i=>lo(i)===t)}function lo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var Kg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,co=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kg(t,i,o),o};let jt=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Tr(this.positionPercent),t=Tr(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
792
- <div
793
- class="meter"
794
- style=${`--position:${e.toFixed(2)}%;`}
795
- role="meter"
796
- aria-label=${i}
797
- aria-valuemin="0"
798
- aria-valuemax="100"
799
- aria-valuenow=${String(Math.round(e))}
800
- title=${i}
801
- >
802
- <div class="track" aria-hidden="true">
803
- <div class="progress"></div>
804
- <div class="marker"></div>
805
- </div>
806
- </div>
807
- `}};jt.styles=O`
808
- :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
809
- :host(:hover), :host(:focus-within) { opacity: .92; }
810
- .meter { height: 100%; }
811
- .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
812
- .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
813
- .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
814
- `;co([d({type:Number})],jt.prototype,"positionPercent",2);co([d({type:Number})],jt.prototype,"loadedPercent",2);jt=co([D("conversation-meter")],jt);function Tr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class As extends ao{constructor(t){if(super(t),this.it=F,t.type!==ro.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}As.directiveName="unsafeHTML",As.resultType=1;const Gg=no(As);function po(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var it=po();function fa(e){it=e}var Ge={exec:()=>null};function ct(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(Z.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var Qg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Z={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ct(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ct(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ct(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ct(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ct(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ct(e=>new RegExp(`^ {0,${e}}>`))},Zg=/^(?:[ \t]*(?:\n|$))+/,Jg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Xg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Yg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ho=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ga=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ma=I(ga).replace(/bull/g,ho).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),em=I(ga).replace(/bull/g,ho).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),uo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,tm=/^[^\n]+/,fo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,im=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sm=I(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ho).getRegex(),Fi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",go=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,om=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",go).replace("tag",Fi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),va=I(uo).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),rm=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",va).getRegex(),mo={blockquote:rm,code:Jg,def:im,fences:Xg,heading:Yg,hr:qt,html:om,lheading:ma,list:sm,newline:Zg,paragraph:va,table:Ge,text:tm},Er=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),nm={...mo,lheading:em,table:Er,paragraph:I(uo).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex()},am={...mo,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",go).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(uo).replace("hr",qt).replace("heading",` *#{1,6} *[^
815
- ]`).replace("lheading",ma).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,cm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ba=/^( {2,}|\\)\n(?!\s*$)/,dm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,bt=/[\p{P}\p{S}]/u,Bi=/[\s\p{P}\p{S}]/u,vo=/[^\s\p{P}\p{S}]/u,pm=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Bi).getRegex(),wa=/(?!~)[\p{P}\p{S}]/u,hm=/(?!~)[\s\p{P}\p{S}]/u,um=/(?:[^\s\p{P}\p{S}]|~)/u,fm=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Qg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ya=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gm=I(ya,"u").replace(/punct/g,bt).getRegex(),mm=I(ya,"u").replace(/punct/g,wa).getRegex(),Sa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",vm=I(Sa,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),bm=I(Sa,"gu").replace(/notPunctSpace/g,um).replace(/punctSpace/g,hm).replace(/punct/g,wa).getRegex(),wm=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),ym=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,bt).getRegex(),Sm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",xm=I(Sm,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),km=I(/\\(punct)/,"gu").replace(/punct/g,bt).getRegex(),$m=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Pm=I(go).replace("(?:-->|$)","-->").getRegex(),Rm=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Pm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),$i=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Im=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",$i).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xa=I(/^!?\[(label)\]\[(ref)\]/).replace("label",$i).replace("ref",fo).getRegex(),ka=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",fo).getRegex(),Cm=I("reflink|nolink(?!\\()","g").replace("reflink",xa).replace("nolink",ka).getRegex(),Dr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bo={_backpedal:Ge,anyPunctuation:km,autolink:$m,blockSkip:fm,br:ba,code:cm,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:gm,emStrongRDelimAst:vm,emStrongRDelimUnd:wm,escape:lm,link:Im,nolink:ka,punctuation:pm,reflink:xa,reflinkSearch:Cm,tag:Rm,text:dm,url:Ge},Mm={...bo,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",$i).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$i).getRegex()},Ts={...bo,emStrongRDelimAst:bm,emStrongLDelim:mm,delLDelim:ym,delRDelim:xm,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Dr).getRegex()},Am={...Ts,br:I(ba).replace("{2,}","*").getRegex(),text:I(Ts.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Jt={normal:mo,gfm:nm,pedantic:am},Mt={normal:bo,gfm:Ts,breaks:Am,pedantic:Mm},Tm={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Wr=e=>Tm[e];function Ae(e,t){if(t){if(Z.escapeTest.test(e))return e.replace(Z.escapeReplace,Wr)}else if(Z.escapeTestNoEncode.test(e))return e.replace(Z.escapeReplaceNoEncode,Wr);return e}function _r(e){try{e=encodeURI(e).replace(Z.percentDecode,"%")}catch{return null}return e}function Or(e,t){let i=e.replace(Z.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(Z.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(Z.slashPipe,"|");return s}function Fe(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Lr(e){let t=e.split(`
816
- `),i=t.length-1;for(;i>=0&&Z.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
817
- `)}function Em(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function Dm(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function jr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function Wm(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
818
- `).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
819
- `)}var Pi=class{options;rules;lexer;constructor(e){this.options=e||it}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Lr(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=Wm(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=Fe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Fe(t[0],`
820
- `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Fe(t[0],`
821
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Fe(t[0],`
822
- `).split(`
823
- `),s="",o="",r=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
824
- `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
825
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
826
- ${p}`:p,o=o?`${o}
827
- ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let v=f,P=v.raw+`
828
- `+i.join(`
829
- `),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-v.raw.length)+H.raw,o=o.substring(0,o.length-v.text.length)+H.text;break}else if(f?.type==="list"){let v=f,P=v.raw+`
830
- `+i.join(`
831
- `),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-f.raw.length)+H.raw,o=o.substring(0,o.length-v.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
832
- `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Dm(t[2].split(`
833
- `,1)[0],t[1].length),f=e.split(`
834
- `,1)[0],v=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):v?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),v&&this.rules.other.blankLine.test(f)&&(p+=f+`
835
- `,e=e.substring(f.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),rt=this.rules.other.hrRegex(P),wt=this.rules.other.fencesBeginRegex(P),So=this.rules.other.headingBeginRegex(P),_a=this.rules.other.htmlBeginRegex(P),Oa=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Hi=e.split(`
836
- `,1)[0],yt;if(f=Hi,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),yt=f):yt=f.replace(this.rules.other.tabCharGlobal," "),wt.test(f)||So.test(f)||_a.test(f)||Oa.test(f)||H.test(f)||rt.test(f))break;if(yt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
837
- `+yt.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||wt.test(h)||So.test(h)||rt.test(h))break;u+=`
838
- `+f}v=!f.trim(),p+=Hi+`
839
- `,e=e.substring(Hi.length+1),h=yt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Lr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Fe(t[0],`
840
- `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Or(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
841
- `):[],r={type:"table",raw:Fe(t[0],`
842
- `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Or(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Fe(t[0],`
843
- `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
844
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Fe(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=Em(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),jr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return jr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},ke=class Es{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||it,this.options.tokenizer=this.options.tokenizer||new Pi,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:Z,block:Jt.normal,inline:Mt.normal};this.options.pedantic?(i.block=Jt.pedantic,i.inline=Mt.pedantic):this.options.gfm&&(i.block=Jt.gfm,this.options.breaks?i.inline=Mt.breaks:i.inline=Mt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Jt,inline:Mt}}static lex(t,i){return new Es(i).lex(t)}static lexInline(t,i){return new Es(i).inlineTokens(t)}lex(t){t=t.replace(Z.carriageReturn,`
845
- `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Z.tabCharGlobal," ").replace(Z.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
846
- `:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
847
- `)?"":`
848
- `)+r.raw,a.text+=`
849
- `+r.text,this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
850
- `)?"":`
851
- `)+r.raw,a.text+=`
852
- `+r.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},i.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),i.push(r);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
853
- `)?"":`
854
- `)+r.raw,a.text+=`
855
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
856
- `)?"":`
857
- `)+r.raw,a.text+=`
858
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Ri=class{options;parser;constructor(e){this.options=e||it}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Z.notSpaceStart)?.[0],o=e.replace(Z.endingNewline,"")+`
859
- `;return s?'<pre><code class="language-'+Ae(s)+'">'+(i?o:Ae(o,!0))+`</code></pre>
860
- `:"<pre><code>"+(i?o:Ae(o,!0))+`</code></pre>
861
- `}blockquote({tokens:e}){return`<blockquote>
862
- ${this.parser.parse(e)}</blockquote>
863
- `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
864
- `}hr(e){return`<hr>
865
- `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let o=t?"ol":"ul",r=t&&i!==1?' start="'+i+'"':"";return"<"+o+r+`>
866
- `+s+"</"+o+`>
867
- `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
868
- `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
869
- `}table(e){let t="",i="";for(let o=0;o<e.header.length;o++)i+=this.tablecell(e.header[o]);t+=this.tablerow({text:i});let s="";for(let o=0;o<e.rows.length;o++){let r=e.rows[o];i="";for(let n=0;n<r.length;n++)i+=this.tablecell(r[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
870
- <thead>
871
- `+t+`</thead>
872
- `+s+`</table>
873
- `}tablerow({text:e}){return`<tr>
874
- ${e}</tr>
875
- `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
876
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Ae(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=_r(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ae(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=_r(e);if(o===null)return Ae(i);e=o;let r=`<img src="${e}" alt="${Ae(i)}"`;return t&&(r+=` title="${Ae(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ae(e.text)}},wo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class Ds{options;renderer;textRenderer;constructor(t){this.options=t||it,this.options.renderer=this.options.renderer||new Ri,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new wo}static parse(t,i){return new Ds(i).parse(t)}static parseInline(t,i){return new Ds(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},Tt=class{options;block;constructor(e){this.options=e||it}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},_m=class{defaults=po();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ri;TextRenderer=wo;Lexer=ke;Tokenizer=Pi;Hooks=Tt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ri(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Pi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new Tt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];Tt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&Tt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
877
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ae(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},et=new _m;function T(e,t){return et.parse(e,t)}T.options=T.setOptions=function(e){return et.setOptions(e),T.defaults=et.defaults,fa(T.defaults),T};T.getDefaults=po;T.defaults=it;T.use=function(...e){return et.use(...e),T.defaults=et.defaults,fa(T.defaults),T};T.walkTokens=function(e,t){return et.walkTokens(e,t)};T.parseInline=et.parseInline;T.Parser=$e;T.parser=$e.parse;T.Renderer=Ri;T.TextRenderer=wo;T.Lexer=ke;T.lexer=ke.lex;T.Tokenizer=Pi;T.Hooks=Tt;T.parse=T;T.options;T.setOptions;T.use;T.walkTokens;T.parseInline;$e.parse;ke.lex;const $a=new T.Renderer;$a.html=({text:e})=>jm(e);const Om=300,At=new Map;function Lm(e){const t=At.get(e);if(t!==void 0)return t;const i=T.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$a}),s=Nm(i);if(At.set(e,s),At.size>Om){const o=At.keys().next().value;o!==void 0&&At.delete(o)}return s}function jm(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Nm(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!zm(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function zm(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,Pa=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};let Ii=class extends C{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${Gg(Lm(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="Copy code block",s.setAttribute("aria-label","Copy code block");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Um(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"Copied code block":t==="failed"?"Failed to copy code block":"Copy code block";e.title=s,e.setAttribute("aria-label",s)}};Ii.styles=Uf;Pa([d()],Ii.prototype,"text",2);Ii=Pa([D("formatted-text")],Ii);async function Um(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var Hm=Object.defineProperty,qm=Object.getOwnPropertyDescriptor,Kt=(e,t,i,s)=>{for(var o=s>1?void 0:s?qm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hm(t,i,o),o};const Nr=180;let tt=class extends C{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=Km(e.args),s=Vm(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Gm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
878
- <section class=${`tool-card ${e.status}`}>
879
- <div class="tool-header">
880
- <div class="tool-title">
881
- <span class="status-icon" aria-hidden="true">${Zm(e.status)}</span>
882
- <strong>${e.toolName}</strong>
883
- ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
884
- </div>
885
- <div class="tool-meta">
886
- ${zr(e)===void 0?null:l`<span>${zr(e)}</span>`}
887
- ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
888
- <span class="status-label">${Jm(e.status)}</span>
889
- </div>
890
- </div>
891
-
892
- ${a?l`<p class="notice">Applied diff differs from the preview.</p>`:null}
893
- ${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
894
- ${r===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(r,s===void 0?"Preview diff":"Applied diff")}
895
- ${!t&&r===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
896
- </section>
897
- `}renderTextBody(e,t){return e===void 0||e===""?null:l`
898
- <details class="text-body" ?open=${t}>
899
- <summary>Result</summary>
900
- <pre>${e}</pre>
901
- </details>
902
- `}renderDiffBody(e,t){const i=e.split(`
903
- `),s=!this.showFullDiff&&i.length>Nr,o=s?i.slice(0,Nr):i;return l`
904
- <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
905
- <summary>
906
- <span>${t}</span>
907
- <small>${String(i.length)} ${i.length===1?"line":"lines"}</small>
908
- </summary>
909
- <div class="diff-toolbar">
910
- <span>${s?`Showing ${String(o.length)} of ${String(i.length)} lines`:"Full diff"}</span>
911
- <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
912
- </div>
913
- <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Qm(r)}>${r}</span>`)}</code></pre>
914
- ${s?l`
915
- <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
916
- Show all ${String(i.length)} diff lines
917
- </button>
918
- `:null}
919
- </details>
920
- `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};tt.styles=O`
921
- :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
922
- .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
923
- .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
924
- .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
925
- .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
926
- .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
927
- .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
928
- .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
929
- strong { color: var(--pi-text); }
930
- .path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
931
- .summary { color: var(--pi-muted); font-family: inherit; }
932
- .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
933
- .diff-stats { display: inline-flex; gap: 3px; }
934
- .added, .diff .added { color: var(--pi-success); }
935
- .removed, .diff .removed { color: var(--pi-danger); }
936
- .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
937
- .notice { margin: 0; color: var(--pi-warning); }
938
- .muted { margin: 0; color: var(--pi-muted); }
939
- .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
940
- .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
941
- .text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
942
- .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
943
- .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
944
- .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
945
- .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
946
- .diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
947
- .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
948
- button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
949
- button:hover, button:focus { border-color: var(--pi-accent); }
950
- .diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
951
- .diff-content { display: block; width: max-content; min-width: 100%; }
952
- .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
953
- .diff .context { color: var(--pi-muted); }
954
- .diff .hunk { color: var(--pi-accent); }
955
- .diff .file { color: var(--pi-dim); }
956
- .diff .meta { color: var(--pi-dim); }
957
- .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
958
- .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
959
- .show-more { justify-self: start; }
960
- `;Kt([d({attribute:!1})],tt.prototype,"execution",2);Kt([w()],tt.prototype,"showFullDiff",2);Kt([w()],tt.prototype,"copied",2);Kt([w()],tt.prototype,"diffOpen",2);tt=Kt([D("tool-execution-view")],tt);function Km(e){return Ws(e,"path")??Ws(e,"file_path")}function zr(e){if(e.toolName!=="edit")return;const t=li(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof li(e.args,"oldText")=="string"&&typeof li(e.args,"newText")=="string")return"1 edit"}function Vm(e){return Ws(e,"diff")}function Gm(e){let t=0,i=0;for(const s of e.split(`
961
- `))Ra(s)?t++:Ia(s)&&i++;return{added:t,removed:i}}function Qm(e){return Ra(e)?"added":Ia(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Ra(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ia(e){return e.startsWith("-")&&!e.startsWith("---")}function Zm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Jm(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Xm(e){return typeof e=="object"&&e!==null}function li(e,t){return Xm(e)?e[t]:void 0}function Ws(e,t){const i=li(e,t);return typeof i=="string"?i:void 0}var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ym(t,i,o),o};const tv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),iv=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ls=["You opened this chat while the assistant was already replying. The complete answer will appear shortly.","We joined mid-sentence. Holding the curtain until the full reply is ready.","The assistant started before this tab arrived. We’ll show the full answer when it lands.","Catching the reply in one piece — no spoilers, no half-answers.","The tokens are still assembling themselves. Full answer incoming.","We arrived fashionably late to this response. The complete version will appear soon."];function Fr(){return ls[Math.floor(Math.random()*ls.length)]??ls[0]}function Br(e){return ci(e,0,100)}function ci(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let z=class extends C{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new bg,this.scrollController=new Fg,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
962
- <div class="chat-wrap">
963
- ${this.renderConversationRail()}
964
- <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
965
- ${this.renderHistoryBoundary()}
966
- ${gg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
967
- ${this.renderQueuedMessages()}
968
- ${this.renderSessionActivity()}
969
- </div>
970
- ${this.renderActivityDock()}
971
- </div>
972
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Sg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
973
- <div class="activity-dock active" aria-live="polite">
974
- <span class="dot"></span>
975
- <span class="activity-text">Sending your message…</span>
976
- </div>
977
- `;const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
978
- <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
979
- <span class="dot"></span>
980
- <span class="activity-text">${this.activityText(e)}</span>
981
- </div>
982
- `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
983
- <aside class="queued-messages" aria-live="polite">
984
- <div class="queued-header">
985
- <strong>Queued messages</strong>
986
- <small>${e.length} pending · Stop clears the queue</small>
987
- </div>
988
- ${e.map((t,i)=>l`
989
- <div class="queued-message">
990
- <span class="queued-kind">${t.kind==="steer"?"Steer":"Follow-up"} ${String(i+1)}</span>
991
- <formatted-text .text=${t.text}></formatted-text>
992
- </div>
993
- `)}
994
- </aside>
995
- `}renderSessionActivity(){return this.isReceivingPartialStream?l`
996
- <aside class="session-activity receiving" aria-live="polite">
997
- <strong>Catching up…</strong>
998
- <span>${this.currentPartialStreamNoticeBody()}</span>
999
- </aside>
1000
- `:this.isCompacting?l`
1001
- <aside class="session-activity compacting" aria-live="polite">
1002
- <strong>Compacting history…</strong>
1003
- <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
1004
- ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
1005
- </aside>
1006
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Fr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Fr(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;return t===void 0||e!=="idle"&&t.phase==="idle"?e:t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?Br(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=ci(this.currentConversationIndex??t,0,e-1);return Br(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
1007
- <div class="history-boundary">
1008
- <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
1009
- <span>Scroll up to load earlier messages</span>
1010
- ${e}
1011
- </div>
1012
- `:this.messages.length?l`<div class="history-boundary"><span>Beginning of session</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.loadedRawMessageEnd(),i=Math.max(this.messageTotal,t);return l`<small>Showing messages ${e}–${t} of ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
1013
- ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
1014
- <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
1015
- ${i?null:this.renderMessageHeader(e,String(t))}
1016
- ${e.parts.map(s=>this.renderPart(s,e))}
1017
- </article>
1018
- `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const o=this.groupDisclosureKey(t,i,s),r=this.disclosures.isOpen(o,s);return l`
1019
- ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
1020
- <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
1021
- <summary>
1022
- <b class="label">${s?"live events":"events"}</b>
1023
- <span>${xg(e)}</span>
1024
- </summary>
1025
- <div class="group-body">
1026
- ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
1027
- <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
1028
- ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
1029
- ${n.parts.map(p=>this.renderPart(p,n))}
1030
- </section>
1031
- `})}
1032
- </div>
1033
- </details>
1034
- `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
1035
- <div class="msg-header">
1036
- <b class="label">${e.role}</b>
1037
- <div class="msg-header-trailing">
1038
- ${this.renderMessageActions(e,t)}
1039
- <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
1040
- </div>
1041
- </div>
1042
- `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1043
- <div class="msg-actions" aria-label="Message actions">
1044
- <button type="button" class="msg-action" title=${i?"Copied":"Copy message"} aria-label=${`${i?"Copied":"Copy"} ${e.role} message`} @click=${s=>{this.copyMessage(e,t,s)}}>
1045
- <span aria-hidden="true">${i?"✓":"⧉"}</span>
1046
- </button>
1047
- </div>
1048
- `}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
1049
-
1050
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:tv.format(t),full:iv.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1051
- <details class="part skill-invocation">
1052
- <summary><b>[skill]</b> ${e.name}</summary>
1053
- <small>${e.location}</small>
1054
- <formatted-text .text=${e.content}></formatted-text>
1055
- </details>
1056
- `:e.type==="skillRead"?l`
1057
- <div class="part skill-read">
1058
- <strong>Loaded ${e.name}</strong>
1059
- <small>read ${e.path}</small>
1060
- </div>
1061
- `:e.type==="image"?l`<img class="part chat-image" src=${`data:${e.mimeType};base64,${e.data}`} alt="attached image" loading="lazy" />`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
1062
- <details class="part" ?open=${e.isError}>
1063
- <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1064
- <formatted-text .text=${e.text}></formatted-text>
1065
- </details>
1066
- `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&Eg({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?ua(e):!0}isAtBottom(){const e=this.chat;return e?ha(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return $g(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Pg(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<kg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=ci(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ci(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Ar(e,t)??Ar(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};z.styles=Bf;U([d({attribute:!1})],z.prototype,"messages",2);U([d()],z.prototype,"sessionId",2);U([d({type:Number})],z.prototype,"messageStart",2);U([d({type:Number})],z.prototype,"messageEnd",2);U([d({type:Number})],z.prototype,"messageTotal",2);U([d({type:Boolean})],z.prototype,"hasMore",2);U([d({type:Boolean})],z.prototype,"loadingMore",2);U([d({type:Boolean})],z.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],z.prototype,"isSendingPrompt",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Number})],z.prototype,"pendingMessageCount",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"activity",2);U([d({attribute:!1})],z.prototype,"onLoadMore",2);U([B(".chat")],z.prototype,"chat",2);U([w()],z.prototype,"pinnedToBottom",2);U([w()],z.prototype,"expandedMetaKey",2);U([w()],z.prototype,"copiedMessageKey",2);U([w()],z.prototype,"currentConversationIndex",2);U([w()],z.prototype,"loadMoreRequested",2);z=U([D("chat-view")],z);const sv=["image/jpeg","image/png","image/gif","image/webp"],ov=new Set(sv);function rv(e){return typeof e=="string"&&ov.has(e)}function nv(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const av="Only PNG, JPEG, GIF, and WebP images are supported.",lv="Failed to read an attachment.";async function cv(e,t){const i=[];let s;for(const o of e){if(!rv(o.type)){s=av;continue}try{const r=await t(o);i.push({name:dv(o),mimeType:o.type,data:r,size:o.size})}catch{s=lv}}return{attachments:i,...s===void 0?{}:{error:s}}}function dv(e){return e.name!==""?e.name:`pasted-image.${nv(e.type)}`}const Ca="pi-web:attachment-delivery";function Ma(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function pv(e=Ma()){try{return e?.getItem(Ca)==="folder"?"folder":"inline"}catch{return"inline"}}function hv(e,t=Ma()){try{t?.setItem(Ca,e)}catch{}}function uv(){return he`
1067
- <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1068
- <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
1069
- </svg>
1070
- `}function Aa(){return he`
1071
- <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1072
- <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1073
- <path d="M21 3 11.5 12.5"></path>
1074
- </svg>
1075
- `}function fv(){return he`
1076
- <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1077
- <path d="M4 7h11"></path>
1078
- <path d="M4 12h7"></path>
1079
- <path d="M4 17h7"></path>
1080
- <path d="m15 14 5 3-5 3z"></path>
1081
- </svg>
1082
- `}function gv(){return Aa()}function mv(){return he`
1083
- <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1084
- <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1085
- </svg>
1086
- `}function vv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,f=20-h,v=p<e.filled;return he`<rect class=${v?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${f} width=${n} height=${h} rx="1"></rect>`});return he`
1087
- <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1088
- ${a}
1089
- </svg>
1090
- `}const bv=["off","minimal","low","medium","high","xhigh"];function _s(e){return e===void 0||e===""?"off":e}function wv(e,t){const i=t.length>=2?t:bv,s=i.length-1,o=_s(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class yv extends ao{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===ro.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const yo=no(yv);var Sv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Ui=(e,t,i,s)=>{for(var o=s>1?void 0:s?xv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sv(t,i,o),o};let gt=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1091
- <div class="menu">
1092
- ${this.items.map((e,t)=>l`
1093
- <button class=${t===this.selectedIndex?"selected":""} ${yo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1094
- <strong>${e.insertText}</strong>
1095
- <span>${e.detail}</span>
1096
- ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1097
- </button>
1098
- `)}
1099
- </div>
1100
- `:null}};gt.styles=qf;Ui([d({attribute:!1})],gt.prototype,"items",2);Ui([d({type:Number})],gt.prototype,"selectedIndex",2);Ui([d({attribute:!1})],gt.prototype,"onPick",2);gt=Ui([D("autocomplete-menu")],gt);var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,L=(e,t,i,s)=>{for(var o=s>1?void 0:s?$v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kv(t,i,o),o};let _=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=pv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new xo,this.readOnlyCompartment=new xo}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Xt(i,t);s!==void 0&&vi(s,this.draft);const o=Xt(this.machineId,this.sessionId);this.draft=o!==void 0?Pn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=Js(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1101
- <footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
1102
- <div class="editor-wrap">
1103
- <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
1104
- <input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${o=>{this.handleFileInput(o)}} />
1105
- <button class="editor-attach icon-button" ?disabled=${s} title="Attach images" aria-label="Attach images" @click=${()=>{this.attachmentInput?.click()}}>${uv()}</button>
1106
- ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1107
- ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1108
- ${this.renderAttachments()}
1109
- <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${o=>{this.pick(o)}}></autocomplete-menu>
1110
- </div>
1111
- <div class="actions">
1112
- ${this.renderCompactStatus()}
1113
- <button class="icon-button send-button" ?disabled=${s} title=${i?"Queue until the current activity finishes":"Send message"} aria-label=${i?"Queue message":"Send message"} @click=${()=>{this.send("followUp")}}>${i?fv():Aa()}</button>
1114
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send("steer")}}>${gv()}</button>`:null}
1115
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${mv()}</button>
1116
- </div>
1117
- </footer>
1118
- `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"no model",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1119
- <div class="compact-status" aria-label="Session status">
1120
- <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1121
- <button class="select-thinking icon-button" title=${`Thinking level: ${_s(e.thinkingLevel)}`} aria-label=${`Thinking level: ${_s(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${vv(wv(e.thinkingLevel,this.availableThinkingLevels))}</button>
1122
- </div>
1123
- `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:l`
1124
- <div class="attachments" aria-label="Pending attachments">
1125
- ${this.attachments.map(e=>l`
1126
- <div class="attachment-chip" title=${e.name}>
1127
- <img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />
1128
- <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
1129
- </div>
1130
- `)}
1131
- ${this.attachments.length>0?l`
1132
- <label class="attachment-delivery" title="How attachments are delivered to the agent">
1133
- <select .value=${this.attachmentDelivery} @change=${e=>{this.changeDelivery(e)}}>
1134
- <option value="inline">Attach to message</option>
1135
- <option value="folder">Save to .pi-web/attachments</option>
1136
- </select>
1137
- </label>
1138
- `:null}
1139
- ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1140
- </div>
1141
- `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",hv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Ur(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=Ur(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await cv(e,Iv);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new nt({parent:this.editorHost,state:qi.create({doc:this.draft,extensions:[La(),Va(),ja(),Na.of(" "),za(Ka,{fallback:!0}),nt.lineWrapping,nt.contentAttributes.of(e=>Av(e.state.sliceDoc(0,e.state.selection.main.head))),Fa("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(nt.editable.of(!this.disabled)),this.readOnlyCompartment.of(qi.readOnly.of(this.disabled)),nt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ba.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Ga(e)||qa(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>ko.shift?.(e)??!1},{key:"Backspace",run:e=>Qa(e)},...Ua,...Ha])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:$o.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(nt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(qi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Xt(this.machineId,this.sessionId);t!==void 0&&vi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await j.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(Pv);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await j.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(Rv);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=En(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Tn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):ko.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:$o.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=Xt(this.machineId,this.sessionId);e!==void 0&&Zs(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};_.styles=Vf;L([d({type:Boolean})],_.prototype,"disabled",2);L([d()],_.prototype,"sessionId",2);L([d()],_.prototype,"cwd",2);L([d()],_.prototype,"machineId",2);L([d()],_.prototype,"projectId",2);L([d()],_.prototype,"workspaceId",2);L([d({type:Boolean})],_.prototype,"workspaceScopedFileSuggestions",2);L([d({type:Boolean})],_.prototype,"canSteer",2);L([d({type:Boolean})],_.prototype,"isCompacting",2);L([d({type:Boolean})],_.prototype,"canStop",2);L([d({attribute:!1})],_.prototype,"status",2);L([d({type:Boolean})],_.prototype,"sending",2);L([d({attribute:!1})],_.prototype,"onSend",2);L([d({attribute:!1})],_.prototype,"onStop",2);L([d({attribute:!1})],_.prototype,"onSelectModel",2);L([d({attribute:!1})],_.prototype,"onSelectThinking",2);L([d({attribute:!1})],_.prototype,"availableThinkingLevels",2);L([B(".markdown-editor")],_.prototype,"editorHost",2);L([B(".attachment-input")],_.prototype,"attachmentInput",2);L([w()],_.prototype,"draft",2);L([w()],_.prototype,"completions",2);L([w()],_.prototype,"selectedIndex",2);L([w()],_.prototype,"attachments",2);L([w()],_.prototype,"attachmentDelivery",2);L([w()],_.prototype,"attachmentError",2);_=L([D("prompt-editor")],_);function Xt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return $n(e,t)}function Pv(){return[]}function Rv(){return[]}function Ur(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function Iv(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("Failed to read file"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("Unexpected file reader result"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const Cv={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Mv={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Av(e){return Js(e).kind==="normal"?Cv:Mv}function Yt(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function Tv(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,Ta=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ev(t,i,o),o};let Ci=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Yt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Yt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1142
- <div class="bar">
1143
- <span>↑${Yt(s.input)}</span>
1144
- <span>↓${Yt(s.output)}</span>
1145
- <span class="context">${i}</span>
1146
- <span>${Tv(e.cost)}</span>
1147
- ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1148
- </div>
1149
- `}};Ci.styles=Hf;Ta([d({attribute:!1})],Ci.prototype,"status",2);Ci=Ta([D("status-bar")],Ci);var Wv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?_v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wv(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1150
- <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1151
- <section @mousedown=${t=>{t.stopPropagation()}}>
1152
- <header>
1153
- <strong>${this.title}</strong>
1154
- <button @click=${()=>this.onCancel?.()}>×</button>
1155
- </header>
1156
- ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1157
- <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1158
- ${e.map((t,i)=>l`
1159
- <button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1160
- <span>${t.label}</span>
1161
- ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1162
- </button>
1163
- `)}
1164
- ${e.length===0?l`<div class="empty">No matching options</div>`:null}
1165
- </div>
1166
- </section>
1167
- </div>
1168
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=ca;Ne([d()],Re.prototype,"title",2);Ne([d({type:Boolean})],Re.prototype,"searchable",2);Ne([d({attribute:!1})],Re.prototype,"options",2);Ne([d({attribute:!1})],Re.prototype,"selectedValue",2);Ne([d({attribute:!1})],Re.prototype,"onPick",2);Ne([d({attribute:!1})],Re.prototype,"onCancel",2);Ne([w()],Re.prototype,"selectedIndex",2);Ne([w()],Re.prototype,"query",2);Re=Ne([D("command-picker")],Re);var Ov=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?Lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ov(t,i,o),o};let Le=class extends C{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1169
- <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1170
- <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1171
- <header>
1172
- <input
1173
- .value=${this.queryText}
1174
- placeholder="Search actions..."
1175
- @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
1176
- >
1177
- <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
1178
- </header>
1179
- <div class="options">
1180
- ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1181
- <button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1182
- <span class="main">
1183
- <strong>${t.title}</strong>
1184
- ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1185
- </span>
1186
- ${t.shortcut!==void 0?l`<kbd>${ni(t.shortcut)}</kbd>`:null}
1187
- ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1188
- </button>
1189
- `)}
1190
- </div>
1191
- </section>
1192
- </div>
1193
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Le.styles=Kf;st([d({attribute:!1})],Le.prototype,"actions",2);st([d({attribute:!1})],Le.prototype,"onRun",2);st([d({attribute:!1})],Le.prototype,"onCancel",2);st([B("input")],Le.prototype,"input",2);st([w()],Le.prototype,"queryText",2);st([w()],Le.prototype,"selectedIndex",2);Le=st([D("action-palette")],Le);var jv=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&jv(t,i,o),o};let se=class extends C{render(){const e=this.state;return e===void 0?null:l`
1194
- <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1195
- <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1196
- <header>
1197
- <strong>${this.dialogTitle(e)}</strong>
1198
- <button title="Close" @click=${()=>{this.cancel()}}>×</button>
1199
- </header>
1200
- ${this.renderBody(e)}
1201
- </section>
1202
- </div>
1203
- `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"Configure provider authentication";case"providers":return e.authType===void 0?"Select provider authentication":e.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${e.provider.name}`;case"oauth":return`Login to ${e.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(e){switch(e.step){case"method":return l`
1204
- <div class="options">
1205
- <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
1206
- <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
1207
- </div>
1208
- `;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No providers available.</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
1209
- <div class="form">
1210
- <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
1211
- <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
1212
- ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1213
- <div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"Saving…":"Save API key"}</button></div>
1214
- </div>
1215
- `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>l`
1216
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Hr(t.authType)}</small></button>
1217
- `)}</div>`}}renderProviderButton(e){return l`
1218
- <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1219
- <span>${e.name}${e.status.source!==void 0?l` <em>${Fv(e)}</em>`:null}</span>
1220
- <small>${e.id} · ${Hr(e.authType)}</small>
1221
- </button>
1222
- `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1223
- <div class="form">
1224
- ${t.auth!==void 0?l`
1225
- <p>Open this authorization link:</p>
1226
- <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1227
- ${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
1228
- `:l`<p>Starting login flow…</p>`}
1229
- ${t.progress.length>0?l`<ul class="progress">${t.progress.map(o=>l`<li>${o}</li>`)}</ul>`:null}
1230
- ${i!==void 0?l`
1231
- <label>${i.message}</label>
1232
- <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${o=>{o.target instanceof HTMLInputElement&&this.onOAuthInput?.(o.target.value)}}>
1233
- <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
1234
- `:null}
1235
- ${s!==void 0?l`
1236
- <p>${s.message}</p>
1237
- <div class="inline-options">${s.options.map(o=>l`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
1238
- `:null}
1239
- ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1240
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
1241
- ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1242
- </div>
1243
- `}focusInputIfNeeded(){const e=zv(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};se.styles=[ca,O`
1244
- .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1245
- .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1246
- .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
1247
- .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
1248
- label { color: var(--pi-muted); }
1249
- .actions { display: flex; justify-content: flex-end; gap: 8px; }
1250
- .actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
1251
- .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
1252
- .actions button:disabled { opacity: .6; cursor: wait; }
1253
- .warning { color: var(--pi-warning); }
1254
- .error-text { color: var(--pi-danger); }
1255
- .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1256
- .inline-options { display: grid; gap: 8px; }
1257
- em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1258
- `];be([d({attribute:!1})],se.prototype,"state",2);be([d({attribute:!1})],se.prototype,"onChooseMethod",2);be([d({attribute:!1})],se.prototype,"onSelectProvider",2);be([d({attribute:!1})],se.prototype,"onApiKeyInput",2);be([d({attribute:!1})],se.prototype,"onSaveApiKey",2);be([d({attribute:!1})],se.prototype,"onLogoutProvider",2);be([d({attribute:!1})],se.prototype,"onOAuthInput",2);be([d({attribute:!1})],se.prototype,"onOAuthRespond",2);be([d({attribute:!1})],se.prototype,"onOAuthCancel",2);be([d({attribute:!1})],se.prototype,"onCancel",2);be([B("input")],se.prototype,"input",2);se=be([D("auth-dialog")],se);function Hr(e){return e==="oauth"?"subscription":"API key"}function zv(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Fv(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ runtime";case"fallback":return"✓ custom key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let ge=class extends C{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await j.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1259
- <div class="backdrop" @click=${()=>this.onCancel?.()}>
1260
- <section @click=${e=>{e.stopPropagation()}}>
1261
- <header>
1262
- <strong>Add project</strong>
1263
- <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1264
- </header>
1265
- <div class="body">
1266
- <label>
1267
- Project folder
1268
- <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
1269
- </label>
1270
- <div class="suggestions">
1271
- ${this.loading?l`<div class="hint">Loading folders…</div>`:null}
1272
- ${this.suggestions.map((e,t)=>l`
1273
- <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
1274
- ${e.path}
1275
- </button>
1276
- `)}
1277
- ${!this.loading&&this.suggestions.length===0?l`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
1278
- </div>
1279
- <label class="check">
1280
- <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
1281
- Create the folder if it does not exist
1282
- </label>
1283
- </div>
1284
- <footer>
1285
- <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
1286
- <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
1287
- </footer>
1288
- </section>
1289
- </div>
1290
- `}};ge.styles=O`
1291
- :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1292
- .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1293
- section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1294
- header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1295
- footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1296
- .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
1297
- label { display: grid; gap: 6px; color: var(--pi-muted); }
1298
- input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1299
- .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
1300
- .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
1301
- .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1302
- .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
1303
- .hint { padding: 12px; color: var(--pi-muted); }
1304
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1305
- header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1306
- .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1307
- button:disabled { opacity: .5; cursor: not-allowed; }
1308
- `;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([w()],ge.prototype,"path",2);De([w()],ge.prototype,"createMissing",2);De([w()],ge.prototype,"suggestions",2);De([w()],ge.prototype,"selected",2);De([w()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([D("project-dialog")],ge);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Kv(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&cs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||cs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?cs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1309
- <div class="backdrop" @click=${()=>this.onCancel?.()}>
1310
- <section @click=${s=>{s.stopPropagation()}}>
1311
- <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
1312
- <header>
1313
- <strong>Add machine</strong>
1314
- <button type="button" @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1315
- </header>
1316
- <div class="body">
1317
- ${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
1318
- <label>
1319
- Remote PI WEB URL
1320
- <input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
1321
- </label>
1322
- <small class=${t===void 0?"hint":"field-error"}>${t??"Enter the reachable base URL first, including http:// or https://."}</small>
1323
- ${e?l`
1324
- <label>
1325
- Machine name
1326
- <input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"Dev Box"} autocomplete="off" />
1327
- </label>
1328
- <small class="hint">Suggested from the URL. Edit it to use a friendlier sidebar label.</small>
1329
- <label>
1330
- Bearer token <span class="optional">optional</span>
1331
- <input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="Leave blank if the remote machine does not require one" autocomplete="off" />
1332
- </label>
1333
- <small class="hint">Paste only the token value; PI WEB sends it as an Authorization: Bearer header.</small>
1334
- `:l`<p class="hint intro">After you enter a URL, PI WEB will suggest a machine name and let you add an optional bearer token.</p>`}
1335
- </div>
1336
- <footer>
1337
- <button type="button" @click=${()=>{this.onCancel?.()}}>Cancel</button>
1338
- <button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"Adding…":"Add machine"}</button>
1339
- </footer>
1340
- </form>
1341
- </section>
1342
- </div>
1343
- `}};me.styles=O`
1344
- :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1345
- .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1346
- section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1347
- form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
1348
- header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1349
- footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1350
- .body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
1351
- label { display: grid; gap: 6px; color: var(--pi-muted); }
1352
- input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1353
- input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
1354
- .hint { color: var(--pi-muted); }
1355
- .intro { margin: 4px 0 0; line-height: 1.4; }
1356
- .optional { color: var(--pi-muted); font-weight: 400; }
1357
- .field-error { color: var(--pi-danger); }
1358
- .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; }
1359
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1360
- header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1361
- .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1362
- button:disabled { opacity: .5; cursor: not-allowed; }
1363
- `;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([w()],me.prototype,"url",2);We([w()],me.prototype,"name",2);We([w()],me.prototype,"token",2);We([w()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([D("machine-dialog")],me);function Kv(e){const t=e.trim();if(t==="")return"";const i=qr(t)??qr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Vv(t)}function cs(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function qr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Vv(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Gv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function Qv(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1364
- `):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1365
- `)??""}}function Zv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const n=Number(o);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:Jv(e.allowedHostsText);const r=Xv(e.allowedPathsText);return r.length>0&&(i.pathAccess={allowedPaths:r}),i}function Jv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Xv(e){const t=e.split(`
1366
- `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Yv(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Yv(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}var eb=Object.defineProperty,tb=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?tb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&eb(t,i,o),o};let ve=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Gv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Qv(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1367
- <div class="section-heading">
1368
- <div>
1369
- <h2>General configuration</h2>
1370
- <p>Update the JSON config file PI WEB is using. Host and port changes are saved immediately, but require the web service to restart before the running server binds to the new address.</p>
1371
- </div>
1372
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1373
- </div>
1374
- ${this.renderMessages()}
1375
- ${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
1376
- <div class="config-path-card">
1377
- <span>Config file</span>
1378
- <code>${e?.path??"Unknown"}</code>
1379
- <small>${e?.exists===!0?"Existing file":"This file will be created on save"}</small>
1380
- </div>
1381
- <form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
1382
- <label class="field">
1383
- <span class="field-heading">
1384
- <span>Host</span>
1385
- ${this.renderOverrideBadge("host")}
1386
- </span>
1387
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Kr(t)})}}>
1388
- <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1389
- </label>
1390
-
1391
- <label class="field">
1392
- <span class="field-heading">
1393
- <span>Port</span>
1394
- ${this.renderOverrideBadge("port")}
1395
- </span>
1396
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Kr(t)})}}>
1397
- <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1398
- </label>
1399
-
1400
- <div class="field">
1401
- <span class="field-heading">
1402
- <span>Allowed hosts</span>
1403
- ${this.renderOverrideBadge("allowedHosts")}
1404
- </span>
1405
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:ob(t)==="all"?"all":"list"})}}>
1406
- <option value="list">Only listed hosts</option>
1407
- <option value="all">Allow every host</option>
1408
- </select>
1409
- <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Vr(t)})}}></textarea>
1410
- <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1411
- </div>
1412
-
1413
- <label class="field">
1414
- <span class="field-heading">
1415
- <span>External filesystem roots</span>
1416
- </span>
1417
- <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:Vr(t)})}}></textarea>
1418
- <small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1419
- </label>
1420
-
1421
- ${this.renderEffectiveConfig()}
1422
-
1423
- <footer class="form-actions">
1424
- <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"Saving…":"Save config"}</button>
1425
- </footer>
1426
- </form>
1427
- `}
1428
- `}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">environment override</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1429
- <section class="effective-card" aria-label="Effective configuration summary">
1430
- <h3>Effective after environment overrides</h3>
1431
- <dl>
1432
- <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1433
- <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1434
- <div><dt>Allowed hosts</dt><dd>${ib(e.allowedHosts)}</dd></div>
1435
- <div><dt>External roots</dt><dd>${sb(e.pathAccess?.allowedPaths)}</dd></div>
1436
- </dl>
1437
- </section>
1438
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Zv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=rb(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=O`
1439
- :host { display: block; }
1440
- .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1441
- .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1442
- h2, h3, p { margin: 0; }
1443
- h2 { font-size: 17px; line-height: 1.25; }
1444
- h3 { font-size: 13px; line-height: 1.3; }
1445
- p { color: var(--pi-muted); line-height: 1.45; }
1446
- button, input, select, textarea { font: inherit; }
1447
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1448
- button:disabled { opacity: .55; cursor: not-allowed; }
1449
- .secondary { flex: 0 0 auto; }
1450
- .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1451
- .message { margin-bottom: 12px; }
1452
- .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1453
- .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1454
- .loading-card { color: var(--pi-muted); }
1455
- .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1456
- .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1457
- code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1458
- .config-path-card small, .field small { color: var(--pi-muted); }
1459
- .config-form { display: grid; gap: 14px; }
1460
- .field { display: grid; gap: 7px; }
1461
- .field-heading { display: flex; align-items: center; gap: 8px; }
1462
- input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; }
1463
- input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1464
- textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1465
- textarea:disabled { opacity: .55; }
1466
- .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1467
- .effective-card { display: grid; gap: 10px; }
1468
- .effective-card dl { display: grid; gap: 8px; margin: 0; }
1469
- .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1470
- dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1471
- .muted { color: var(--pi-muted); }
1472
- .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1473
- .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1474
-
1475
- @media (max-width: 760px) {
1476
- .section-heading { display: grid; gap: 12px; }
1477
- .section-heading .secondary { justify-self: start; }
1478
- .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1479
- }
1480
- `;_e([d({attribute:!1})],ve.prototype,"configResponse",2);_e([d({type:Boolean})],ve.prototype,"loading",2);_e([d({type:Boolean})],ve.prototype,"saving",2);_e([d()],ve.prototype,"error",2);_e([d()],ve.prototype,"savedMessage",2);_e([d({attribute:!1})],ve.prototype,"onReload",2);_e([d({attribute:!1})],ve.prototype,"onSave",2);_e([w()],ve.prototype,"draft",2);_e([w()],ve.prototype,"localError",2);ve=_e([D("settings-general-panel")],ve);function ib(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function sb(e){return e===void 0||e.length===0?l`<span class="muted">External paths denied</span>`:e.join(", ")}function Kr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function ob(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Vr(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function rb(e){return e instanceof Error?e.message:String(e)}var nb=Object.defineProperty,ab=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?ab(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&nb(t,i,o),o};let Ee=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return l`
1481
- <div class="section-heading">
1482
- <div>
1483
- <h2>Session daemon</h2>
1484
- <p>These settings affect the long-lived session runtime. Changes are saved to the config file immediately but only take effect after the session daemon restarts.</p>
1485
- </div>
1486
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1487
- </div>
1488
- ${this.renderMessages()}
1489
- <div class="restart-note" role="note">Restart required: run <code>pi-web restart</code> (or restart the session daemon service) after changing these settings.</div>
1490
- ${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
1491
- <div class="config-path-card">
1492
- <span>Config file</span>
1493
- <code>${e?.path??"Unknown"}</code>
1494
- </div>
1495
- <div class="field">
1496
- <span class="field-heading">
1497
- <span>Allow agents to start sessions</span>
1498
- ${t?l`<span class="override-badge">environment override</span>`:null}
1499
- </span>
1500
- <label class="toggle">
1501
- <input
1502
- type="checkbox"
1503
- .checked=${i}
1504
- ?disabled=${this.loading||this.saving||t}
1505
- @change=${r=>{this.toggleSpawnSessions(r)}}
1506
- >
1507
- <span>Enable the <code>spawn_session</code> tool</span>
1508
- </label>
1509
- <small>When enabled, LLMs can start new sessions, constrained to a workspace (any worktree) of the same registered project so every spawned session stays visible here. On by default.</small>
1510
- </div>
1511
- <div class="field">
1512
- <span class="field-heading">
1513
- <span>Allow agents to start tracked subsessions</span>
1514
- <span class="beta-badge">beta</span>
1515
- ${s?l`<span class="override-badge">environment override</span>`:null}
1516
- </span>
1517
- <label class="toggle">
1518
- <input
1519
- type="checkbox"
1520
- .checked=${o}
1521
- ?disabled=${this.loading||this.saving||s||!i}
1522
- @change=${r=>{this.toggleSubsessions(r)}}
1523
- >
1524
- <span>Enable the <code>spawn_subsession</code> tools</span>
1525
- </label>
1526
- <small>Beta: agents can start child sessions they stay attached to (<code>spawn_subsession</code>, <code>list_subsessions</code>, <code>check_subsession</code>, <code>read_subsession</code>) and are notified when a child finishes. Requires "Allow agents to start sessions". Off by default.</small>
1527
- </div>
1528
- <section class="effective-card" aria-label="Effective configuration summary">
1529
- <h3>Effective after environment overrides</h3>
1530
- <dl>
1531
- <div><dt>Spawn sessions</dt><dd>${i?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
1532
- <div><dt>Subsessions</dt><dd>${o?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
1533
- </dl>
1534
- </section>
1535
- `}
1536
- `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=O`
1537
- :host { display: block; }
1538
- .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1539
- .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1540
- h2, h3, p { margin: 0; }
1541
- h2 { font-size: 17px; line-height: 1.25; }
1542
- h3 { font-size: 13px; line-height: 1.3; }
1543
- p { color: var(--pi-muted); line-height: 1.45; }
1544
- button, input { font: inherit; }
1545
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1546
- button:disabled { opacity: .55; cursor: not-allowed; }
1547
- .secondary { flex: 0 0 auto; }
1548
- .message, .loading-card, .config-path-card, .effective-card, .restart-note { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1549
- .message { margin-bottom: 12px; }
1550
- .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1551
- .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1552
- .loading-card { color: var(--pi-muted); }
1553
- .restart-note { margin-bottom: 14px; border-color: var(--pi-warning-border); color: var(--pi-warning); background: var(--pi-warning-surface); line-height: 1.45; }
1554
- .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1555
- .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1556
- code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1557
- .field { display: grid; gap: 7px; margin-bottom: 14px; }
1558
- .field small { color: var(--pi-muted); line-height: 1.45; }
1559
- .field-heading { display: flex; align-items: center; gap: 8px; }
1560
- .toggle { display: flex; align-items: center; gap: 9px; cursor: pointer; }
1561
- .toggle input { width: 16px; height: 16px; }
1562
- .toggle input:disabled { cursor: not-allowed; }
1563
- .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1564
- .beta-badge { border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); background: var(--pi-bg); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
1565
- .effective-card { display: grid; gap: 10px; }
1566
- .effective-card dl { display: grid; gap: 8px; margin: 0; }
1567
- .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1568
- dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1569
- .muted { color: var(--pi-muted); }
1570
-
1571
- @media (max-width: 760px) {
1572
- .section-heading { display: grid; gap: 12px; }
1573
- .section-heading .secondary { justify-self: start; }
1574
- .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1575
- }
1576
- `;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([D("settings-sessiond-panel")],Ee);var lb=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?cb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&lb(t,i,o),o};let Ie=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1577
- <div class="section-heading">
1578
- <div>
1579
- <h2>Plugins</h2>
1580
- <p>Enable or disable discovered PI WEB plugins. Changes apply after reloading the browser tab; already-loaded plugin code is not unloaded from the current page.</p>
1581
- </div>
1582
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1583
- </div>
1584
- ${this.renderMessages()}
1585
- <div class="plugin-note">Config key: <code>plugins</code>. Plugins are enabled unless their entry sets <code>enabled</code> to <code>false</code>.</div>
1586
- ${this.loading&&e.length===0?l`<div class="loading-card">Loading plugins…</div>`:e.length===0?l`<div class="loading-card">No external or bundled plugins discovered.</div>`:l`
1587
- <div class="plugin-list">
1588
- ${e.map(t=>this.renderPlugin(t))}
1589
- </div>
1590
- `}
1591
- `}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage} Reload the browser tab to apply plugin changes.</div>`:null}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"Config disabled":t?.enabled===!0?"Config enabled":"Default enabled";return l`
1592
- <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1593
- <div class="plugin-main">
1594
- <strong>${e.id}</strong>
1595
- <small>${e.source} · ${e.scope}${e.machineSpecific?" · machine-specific":""}</small>
1596
- <small>${i}</small>
1597
- </div>
1598
- <label class="toggle">
1599
- <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
1600
- <span>${e.enabled?"Enabled":"Disabled"}</span>
1601
- </label>
1602
- </article>
1603
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ie.styles=O`
1604
- :host { display: block; }
1605
- .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1606
- .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1607
- h2, p { margin: 0; }
1608
- h2 { font-size: 17px; line-height: 1.25; }
1609
- p { color: var(--pi-muted); line-height: 1.45; }
1610
- button, input { font: inherit; }
1611
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1612
- button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1613
- .secondary { flex: 0 0 auto; }
1614
- .message, .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1615
- .message { margin-bottom: 12px; }
1616
- .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1617
- .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1618
- .loading-card, .plugin-note { color: var(--pi-muted); }
1619
- .plugin-note { margin-bottom: 14px; }
1620
- code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1621
- .plugin-list { display: grid; gap: 10px; }
1622
- .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
1623
- .plugin-card.disabled { opacity: .75; }
1624
- .plugin-main { min-width: 0; display: grid; gap: 3px; }
1625
- .plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1626
- .plugin-main small { color: var(--pi-muted); }
1627
- .toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
1628
- .toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
1629
-
1630
- @media (max-width: 760px) {
1631
- .section-heading { display: grid; gap: 12px; }
1632
- .section-heading .secondary { justify-self: start; }
1633
- .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1634
- .toggle { justify-self: start; }
1635
- }
1636
- `;ze([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);ze([d({attribute:!1})],Ie.prototype,"configResponse",2);ze([d({type:Boolean})],Ie.prototype,"loading",2);ze([d({type:Boolean})],Ie.prototype,"saving",2);ze([d()],Ie.prototype,"error",2);ze([d()],Ie.prototype,"savedMessage",2);ze([d({attribute:!1})],Ie.prototype,"onReload",2);ze([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=ze([D("settings-plugins-panel")],Ie);var db=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&db(t,i,o),o};const Gr={capture:!0};let oe=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=zn(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Lt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=gb(this.actions),t=this.shortcutResolutions();return l`
1637
- <div class="section-heading">
1638
- <div>
1639
- <h2>Keyboard shortcuts</h2>
1640
- <p>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.</p>
1641
- </div>
1642
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1643
- </div>
1644
- ${this.renderMessages()}
1645
- ${this.configResponse===void 0&&this.loading?l`<div class="loading-card">Loading shortcuts…</div>`:l`
1646
- <div class="config-path-card">
1647
- <span>Config file</span>
1648
- <code>${this.configResponse?.path??"Unknown"}</code>
1649
- <small>Shortcut overrides are saved under <code>shortcuts</code>. A value of <code>null</code> disables the action shortcut.</small>
1650
- </div>
1651
- ${e.length===0?l`<div class="loading-card">No actions registered.</div>`:e.map(i=>l`
1652
- <section class="shortcut-group">
1653
- <h3>${i.name}</h3>
1654
- <div class="shortcut-list">
1655
- ${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
1656
- </div>
1657
- </section>
1658
- `)}
1659
- `}
1660
- `}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Mi(e.id,i),o=wb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Xi(r),a=n?.ok===!0?n.shortcut:bb(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=fb(t);return l`
1661
- <article class=${hb(t)}>
1662
- <div class="shortcut-main">
1663
- <strong>${e.title}</strong>
1664
- ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1665
- <small class="shortcut-id">${e.id}</small>
1666
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ni(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1667
- </div>
1668
- <div class="shortcut-editor">
1669
- <div class="shortcut-status">
1670
- ${a!==void 0&&a!==""?l`<kbd>${ni(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
1671
- <small class=${u}>${yb(u)}${p?" · Unsaved":""}</small>
1672
- ${f===void 0?null:l`<small class=${ub(t)}>${f}</small>`}
1673
- </div>
1674
- <label class="shortcut-input-label">
1675
- <span>Shortcut</span>
1676
- <input
1677
- class="shortcut-input"
1678
- data-action-id=${e.id}
1679
- .value=${r}
1680
- placeholder=${e.shortcut??"mod+k"}
1681
- autocomplete="off"
1682
- autocapitalize="off"
1683
- spellcheck="false"
1684
- ?disabled=${this.saving}
1685
- @input=${v=>{this.updateDraft(e.id,Sb(v))}}
1686
- >
1687
- </label>
1688
- ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
1689
- <div class="shortcut-actions">
1690
- <button class="primary" ?disabled=${this.loading||this.saving||!p||r.trim()===""} @click=${()=>{this.saveShortcut(e)}}>Save</button>
1691
- <button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"Cancel recording":"Record"}</button>
1692
- <button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>None</button>
1693
- <button ?disabled=${this.loading||this.saving||!c} @click=${()=>{this.resetShortcut(e.id)}}>Reset</button>
1694
- </div>
1695
- </div>
1696
- </article>
1697
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Mi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ni(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Xi(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?vb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(eo(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Xi(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},jn)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!1)}};oe.styles=O`
1698
- :host { display: block; }
1699
- .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1700
- .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1701
- h2, h3, p { margin: 0; }
1702
- h2 { font-size: 17px; line-height: 1.25; }
1703
- h3 { font-size: 13px; line-height: 1.3; }
1704
- p { color: var(--pi-muted); line-height: 1.45; }
1705
- button, input { font: inherit; }
1706
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1707
- button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1708
- .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1709
- .secondary { flex: 0 0 auto; }
1710
- .message, .loading-card, .config-path-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1711
- .message { margin-bottom: 12px; }
1712
- .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1713
- .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1714
- .loading-card, .config-path-card { color: var(--pi-muted); }
1715
- .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1716
- .config-path-card span { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1717
- code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1718
- .shortcut-group { margin: 0 0 16px; }
1719
- .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1720
- .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
1721
- .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 48%); gap: 14px; align-items: start; padding: 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
1722
- .shortcut-row.shadowed { background: color-mix(in srgb, var(--pi-warning) 5%, var(--pi-surface)); }
1723
- .shortcut-row.shadowing { background: color-mix(in srgb, var(--pi-accent) 5%, var(--pi-surface)); }
1724
- .shortcut-row:last-child { border-bottom: 0; }
1725
- .shortcut-main { min-width: 0; display: grid; gap: 4px; }
1726
- .shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1727
- .shortcut-main small { color: var(--pi-muted); }
1728
- .shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1729
- .shortcut-editor { min-width: 0; display: grid; gap: 8px; }
1730
- .shortcut-status { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
1731
- .shortcut-status small { color: var(--pi-muted); font-size: 11px; }
1732
- .shortcut-status small.custom { color: var(--pi-accent); }
1733
- .shortcut-status small.disabled { color: var(--pi-warning); }
1734
- .shortcut-status small.conflict { border: 1px solid currentColor; border-radius: 999px; padding: 2px 7px; }
1735
- .shortcut-status small.conflict.shadowing { color: var(--pi-accent); }
1736
- .shortcut-status small.conflict.shadowed { color: var(--pi-warning); }
1737
- .shortcut-input-label { min-width: 0; display: grid; gap: 5px; }
1738
- .shortcut-input-label span { color: var(--pi-muted); font-size: 11px; font-weight: 700; text-transform: uppercase; }
1739
- input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; outline: none; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1740
- input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1741
- .shortcut-actions { display: flex; justify-content: flex-end; gap: 7px; flex-wrap: wrap; }
1742
- kbd { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-bg); color: var(--pi-text-secondary); padding: 3px 7px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
1743
- .unassigned { color: var(--pi-muted); font-size: 12px; }
1744
- .recording-hint { color: var(--pi-accent); font-size: 12px; }
1745
-
1746
- @media (max-width: 760px) {
1747
- .section-heading { display: grid; gap: 12px; }
1748
- .section-heading .secondary { justify-self: start; }
1749
- .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1750
- .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1751
- }
1752
- `;we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"configResponse",2);we([d({type:Boolean})],oe.prototype,"loading",2);we([d({type:Boolean})],oe.prototype,"saving",2);we([d()],oe.prototype,"error",2);we([d()],oe.prototype,"savedMessage",2);we([d({attribute:!1})],oe.prototype,"onReload",2);we([d({attribute:!1})],oe.prototype,"onSave",2);we([w()],oe.prototype,"drafts",2);we([w()],oe.prototype,"localError",2);we([w()],oe.prototype,"recording",2);oe=we([D("settings-shortcuts-panel")],oe);function hb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function ub(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function fb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function gb(e){const t=new Map;for(const i of[...e].sort(mb)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function mb(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function Mi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function vb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function bb(e,t){const i=Mi(e.id,t);if(i!==null)return i??e.shortcut}function wb(e,t){const i=Mi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function yb(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function Sb(e){return e.target instanceof HTMLInputElement?e.target.value:""}var xb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xb(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1753
- <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1754
- <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1755
- <header class="settings-header">
1756
- <div>
1757
- <span class="eyebrow">Settings</span>
1758
- <h1>PI WEB</h1>
1759
- </div>
1760
- <button class="close-button" title="Close settings" aria-label="Close settings" @click=${()=>this.onClose?.()}>×</button>
1761
- </header>
1762
- <div class="settings-body">
1763
- <nav class="settings-nav" aria-label="Settings sections">
1764
- ${this.renderNavButton("general","General","Server config")}
1765
- ${this.renderNavButton("sessiond","Session daemon","Runtime settings")}
1766
- ${this.renderNavButton("plugins","Plugins","Enable and disable")}
1767
- ${this.renderNavButton("shortcuts","Keyboard","Shortcuts")}
1768
- </nav>
1769
- <main class="settings-content">
1770
- ${this.renderActiveSection()}
1771
- </main>
1772
- </div>
1773
- </section>
1774
- </div>
1775
- `}renderActiveSection(){return this.section==="sessiond"?l`
1776
- <settings-sessiond-panel
1777
- .configResponse=${this.configResponse}
1778
- .loading=${this.loading}
1779
- .saving=${this.saving}
1780
- .error=${this.error}
1781
- .savedMessage=${this.savedMessage}
1782
- .onReload=${()=>this.loadConfig()}
1783
- .onSave=${e=>this.saveConfig(e)}
1784
- ></settings-sessiond-panel>
1785
- `:this.section==="shortcuts"?l`
1786
- <settings-shortcuts-panel
1787
- .actions=${this.actions}
1788
- .configResponse=${this.configResponse}
1789
- .loading=${this.loading}
1790
- .saving=${this.saving}
1791
- .error=${this.error}
1792
- .savedMessage=${this.savedMessage}
1793
- .onReload=${()=>this.loadConfig()}
1794
- .onSave=${e=>this.saveConfig(e)}
1795
- ></settings-shortcuts-panel>
1796
- `:this.section==="plugins"?l`
1797
- <settings-plugins-panel
1798
- .configResponse=${this.configResponse}
1799
- .pluginsResponse=${this.pluginsResponse}
1800
- .loading=${this.loading}
1801
- .saving=${this.saving}
1802
- .error=${this.error}
1803
- .savedMessage=${this.savedMessage}
1804
- .onReload=${()=>this.loadConfig()}
1805
- .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
1806
- ></settings-plugins-panel>
1807
- `:l`
1808
- <settings-general-panel
1809
- .configResponse=${this.configResponse}
1810
- .loading=${this.loading}
1811
- .saving=${this.saving}
1812
- .error=${this.error}
1813
- .savedMessage=${this.savedMessage}
1814
- .onReload=${()=>this.loadConfig()}
1815
- .onSave=${e=>this.saveConfig(e)}
1816
- ></settings-general-panel>
1817
- `}renderNavButton(e,t,i){const s=this.section===e;return l`
1818
- <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
1819
- <strong>${t}</strong>
1820
- <small>${i}</small>
1821
- </button>
1822
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ui.config(),ws.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${ds(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ui.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${ds(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await ws.plugins()}catch(e){this.error=`Failed to refresh plugins: ${ds(e)}`}}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};re.styles=O`
1823
- :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1824
- .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
1825
- .settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1826
- .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
1827
- .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1828
- h1 { margin: 0; font-size: 20px; line-height: 1.2; }
1829
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1830
- .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1831
- .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
1832
- .settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
1833
- .settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
1834
- .settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
1835
- .settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
1836
- .settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1837
- .settings-nav small { color: var(--pi-muted); }
1838
- .settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
1839
-
1840
- @media (max-width: 760px) {
1841
- .backdrop { padding: 0; place-items: stretch; }
1842
- .settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
1843
- .settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
1844
- .settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
1845
- .settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
1846
- .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1847
- .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1848
- }
1849
- `;ye([d({attribute:!1})],re.prototype,"section",2);ye([d({attribute:!1})],re.prototype,"actions",2);ye([d({attribute:!1})],re.prototype,"onNavigate",2);ye([d({attribute:!1})],re.prototype,"onClose",2);ye([d({attribute:!1})],re.prototype,"onConfigSaved",2);ye([w()],re.prototype,"configResponse",2);ye([w()],re.prototype,"pluginsResponse",2);ye([w()],re.prototype,"loading",2);ye([w()],re.prototype,"saving",2);ye([w()],re.prototype,"error",2);ye([w()],re.prototype,"savedMessage",2);re=ye([D("settings-dialog")],re);function ds(e){return e instanceof Error?e.message:String(e)}var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$b(t,i,o),o};let ce=class extends C{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
1850
- ${this.hideToolTabs?null:l`
1851
- <header>
1852
- <div class=${this.workspaceHeaderFrameClass()}>
1853
- <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
1854
- <div class="tabs">
1855
- ${i.map(o=>{const r=s?.id===o.id,n=o.badge?.(t),a=this.panelTabAriaLabel(o,n);return l`
1856
- <button class=${this.panelTabClass(o,r)} title=${a} aria-label=${a} aria-pressed=${String(r)} @click=${()=>{this.onSelectTool(o.id)}}>
1857
- ${this.renderPanelTabContent(o,n)}
1858
- </button>
1859
- `})}
1860
- </div>
1861
- </div>
1862
- </div>
1863
- </header>
1864
- `}
1865
- ${s===void 0?this.renderEmptyState({title:"No workspace tools available",body:"No tools are available for this workspace."}):l`
1866
- <div class="panel-content">
1867
- ${s.render(t)}
1868
- </div>
1869
- `}
1870
- `}panelTabClass(e,t){return[...e.icon===void 0?[]:["icon-tab"],...t?["selected"]:[]].join(" ")}panelTabAriaLabel(e,t){if(typeof t!="string"&&typeof t!="number")return e.title;const i=String(t).trim();return i===""?e.title:`${e.title}, ${i}`}renderPanelTabContent(e,t){return l`
1871
- ${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
1872
- <span class="tab-label">${e.title}</span>
1873
- ${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
1874
- `}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
1875
- <section class="empty-state" role="status">
1876
- <h2>${e.title}</h2>
1877
- ${e.body===void 0?null:l`<p>${e.body}</p>`}
1878
- </section>
1879
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ce.styles=Ff;Ce([d({attribute:!1})],ce.prototype,"workspace",2);Ce([d({attribute:!1})],ce.prototype,"panelContext",2);Ce([d({attribute:!1})],ce.prototype,"emptyState",2);Ce([d()],ce.prototype,"tool",2);Ce([d({attribute:!1})],ce.prototype,"panels",2);Ce([d({type:Boolean})],ce.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],ce.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],ce.prototype,"workspaceHeaderStrip",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollLeft",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollRight",2);ce=Ce([D("workspace-panel")],ce);var Rb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rb(t,i,o),o};let ne=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Cb(this.machines),t=Mb(this.machine),i=Tb(this.project),s=Db(this.workspace),o=_b(this.session);return l`
1880
- <nav class=${this.contextBarClass()} aria-label="Current location">
1881
- <span class="context-bar-label">Location</span>
1882
- <ol class="context-items" @scroll=${this.onContextScroll}>
1883
- ${e?l`
1884
- <li class="context-item">
1885
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Ab(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
1886
- <span class="context-kind">Machine</span>
1887
- <span class="context-value">${t}</span>
1888
- </button>
1889
- </li>
1890
- `:null}
1891
- <li class="context-item">
1892
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Eb(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
1893
- <span class="context-kind">Project</span>
1894
- <span class="context-value">${i}</span>
1895
- </button>
1896
- </li>
1897
- <li class="context-item">
1898
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Wb(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1899
- <span class="context-kind">Workspace</span>
1900
- <span class="context-value">${s}</span>
1901
- </button>
1902
- </li>
1903
- <li class="context-item">
1904
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Ob(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1905
- <span class="context-kind">Session</span>
1906
- <span class="context-value">${o}</span>
1907
- </button>
1908
- </li>
1909
- </ol>
1910
- ${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
1911
- </nav>
1912
- `}renderActionsButton(){return this.onShowActions===void 0?null:l`
1913
- <button type="button" class="context-action-button" title="Show Actions" aria-label="Show Actions" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
1914
- <svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1915
- <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
1916
- </svg>
1917
- </button>
1918
- `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ne.styles=O`
1919
- /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
1920
- :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
1921
- .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
1922
- .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; }
1923
- .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1924
- .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1925
- .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
1926
- .context-bar-label { display: none; }
1927
- .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
1928
- .context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
1929
- .context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
1930
- .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
1931
- .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--pi-bg); pointer-events: none; }
1932
- .context-actions::before { content: ""; position: absolute; top: 0; bottom: 0; left: -24px; z-index: 0; width: 24px; background: linear-gradient(90deg, transparent, var(--pi-bg)); pointer-events: none; }
1933
- app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
1934
- .context-action-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; }
1935
- .context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1936
- .context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
1937
- .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
1938
- .context-chip:hover { background: var(--pi-surface-hover); }
1939
- .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
1940
- .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
1941
- .context-kind { display: none; }
1942
- .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1943
- button { cursor: pointer; }
1944
- `;Se([d({attribute:!1})],ne.prototype,"machines",2);Se([d({attribute:!1})],ne.prototype,"machine",2);Se([d({attribute:!1})],ne.prototype,"project",2);Se([d({attribute:!1})],ne.prototype,"workspace",2);Se([d({attribute:!1})],ne.prototype,"session",2);Se([d({attribute:!1})],ne.prototype,"refreshControl",2);Se([d({attribute:!1})],ne.prototype,"onOpenSection",2);Se([d({attribute:!1})],ne.prototype,"onShowActions",2);Se([B(".context-items")],ne.prototype,"contextItems",2);Se([w()],ne.prototype,"canScrollLeft",2);Se([w()],ne.prototype,"canScrollRight",2);ne=Se([D("app-context-bar")],ne);function Cb(e){return e.length>1}function Mb(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function Ab(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Tb(e){return e?.name??"No project"}function Eb(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function Db(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Wb(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function _b(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"No session"}function Ob(e){return e===void 0?"No session selected":e.path}var Lb=Object.defineProperty,jb=Object.getOwnPropertyDescriptor,ot=(e,t,i,s)=>{for(var o=s>1?void 0:s?jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Lb(t,i,o),o};let je=class extends C{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
1945
- <div class=${this.frameClass()}>
1946
- <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1947
- ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
1948
- <button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
1949
- ${this.renderTabMark(t,e)}
1950
- <span class="tab-label">${t.label}</span>
1951
- ${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
1952
- </button>
1953
- `})}
1954
- </div>
1955
- </div>
1956
- `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:ru(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=O`
1957
- :host { flex: 0 0 auto; min-width: 0; }
1958
- .mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
1959
- .mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
1960
- .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1961
- .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
1962
- .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
1963
- .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
1964
- .mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
1965
- .mobile-tabs .navigation-tab { display: none; }
1966
- .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
1967
- .tab-icon { flex: 0 0 auto; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1968
- .tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
1969
- .tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
1970
- .tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
1971
- .tab-label { min-width: 0; }
1972
- .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; margin-left: 0; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
1973
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1974
- @media (max-width: 760px) {
1975
- .mobile-tabs { gap: 4px; padding: 6px 8px; }
1976
- .mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
1977
- .mobile-tabs .navigation-tab { display: inline-flex; }
1978
- .tab-fallback { display: inline-block; }
1979
- .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
1980
- .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1981
- }
1982
- `;ot([d({attribute:!1})],je.prototype,"tabs",2);ot([d({attribute:!1})],je.prototype,"selectedView",2);ot([d({attribute:!1})],je.prototype,"onSelect",2);ot([B(".mobile-tabs")],je.prototype,"mobileTabs",2);ot([w()],je.prototype,"canScrollLeft",2);ot([w()],je.prototype,"canScrollRight",2);je=ot([D("app-mobile-main-tabs")],je);var Nb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?zb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Nb(t,i,o),o};let te=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=ps(e,this.statuses),i=e.name;return l`
1983
- <div class="machine-switcher">
1984
- <button
1985
- type="button"
1986
- class="machine-switcher-button"
1987
- title=${Zr(e)}
1988
- aria-label=${`Machine: ${i}. Switch machine.`}
1989
- aria-expanded=${String(this.open)}
1990
- @click=${s=>{this.toggleMenu(s.currentTarget)}}
1991
- @keydown=${s=>{this.handleSwitcherButtonKeydown(s)}}
1992
- >
1993
- ${this.renderActivity(e)}
1994
- <span class="machine-switcher-text">
1995
- <span class="machine-switcher-kicker">Machine</span>
1996
- <span class="machine-switcher-label">${i}</span>
1997
- </span>
1998
- <span class=${`machine-status ${t}`}>${Qr(t)}</span>
1999
- <span class="machine-chevron" aria-hidden="true">▾</span>
2000
- </button>
2001
- ${this.open?l`
2002
- <div class="machine-switcher-menu" style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
2003
- ${this.machines.map(s=>this.renderMachineOption(s))}
2004
- </div>
2005
- `:null}
2006
- </div>
2007
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=ps(e,this.statuses),s=da(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
2008
- <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2009
- <button
2010
- type="button"
2011
- class="machine-option-main"
2012
- title=${Zr(e)}
2013
- data-machine-id=${e.id}
2014
- @click=${()=>{this.select(e)}}
2015
- @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
2016
- >
2017
- <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2018
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Qr(i)}</small>
2019
- </button>
2020
- ${s?l`
2021
- <div class="machine-option-actions">
2022
- <button
2023
- type="button"
2024
- class="machine-option-actions-toggle"
2025
- title="Machine actions"
2026
- aria-label=${`Actions for ${e.name}`}
2027
- aria-expanded=${String(o)}
2028
- @click=${r=>{r.stopPropagation(),this.toggleActionsMenu(e.id,r.currentTarget)}}
2029
- >⋯</button>
2030
- ${o?l`
2031
- <div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${r=>{r.stopPropagation()}}>
2032
- <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
2033
- </div>
2034
- `:null}
2035
- </div>
2036
- `:null}
2037
- </div>
2038
- `}renderActivity(e){const t=ps(e,this.statuses);if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return oa(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Jr(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Jr(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Ht(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};te.styles=O`
2039
- :host { min-width: 0; display: block; }
2040
- .machine-switcher { min-width: 0; }
2041
- .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
2042
- .machine-switcher-button:hover, .machine-switcher-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
2043
- .machine-switcher-text { flex: 1 1 auto; min-width: 0; display: grid; gap: 1px; }
2044
- .machine-switcher-kicker { color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
2045
- .machine-switcher-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.2; }
2046
- .machine-status { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
2047
- .machine-status.online { color: var(--pi-success); }
2048
- .machine-status.offline, .machine-status.error { color: var(--pi-danger); }
2049
- .machine-chevron { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
2050
- .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
2051
- .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
2052
- .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
2053
- .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
2054
- .machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
2055
- .machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
2056
- .machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
2057
- .machine-option-main, .machine-option-actions-toggle, .machine-option-actions-panel button { border: 0; border-radius: 7px; background: transparent; color: var(--pi-text); cursor: pointer; }
2058
- .machine-option-main { min-width: 0; display: grid; gap: 2px; padding: 7px 8px; text-align: left; }
2059
- .machine-option-name { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
2060
- .machine-option-name span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2061
- .machine-option-main small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-muted); }
2062
- .machine-option-actions { position: relative; align-self: stretch; }
2063
- .machine-option-actions-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); }
2064
- .machine-option-actions-panel { position: fixed; z-index: 10001; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
2065
- .machine-option-actions-panel button { display: block; width: 100%; padding: 7px 9px; text-align: left; white-space: nowrap; }
2066
- .machine-option-actions-panel button.danger { color: var(--pi-danger); }
2067
- .machine-option-main:hover, .machine-option-main:focus-visible, .machine-option-actions-toggle:hover, .machine-option-actions-toggle:focus-visible, .machine-option.selected .machine-option-main { background: var(--pi-selection-bg); }
2068
- .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2069
- .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
2070
- @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2071
- `;pe([d({attribute:!1})],te.prototype,"machines",2);pe([d({attribute:!1})],te.prototype,"selected",2);pe([d({attribute:!1})],te.prototype,"statuses",2);pe([d({attribute:!1})],te.prototype,"activities",2);pe([d({attribute:!1})],te.prototype,"onSelect",2);pe([d({attribute:!1})],te.prototype,"onRemove",2);pe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);pe([w()],te.prototype,"open",2);pe([w()],te.prototype,"menuStyle",2);pe([w()],te.prototype,"openActionsMachineId",2);pe([w()],te.prototype,"actionMenuStyle",2);te=pe([D("machine-switcher")],te);function ps(e,t){return t[e.id]?.status??e.status??"unknown"}function Qr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Zr(e){return e.baseUrl??e.name}function Jr(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ei(t.bottom)};`,`left: ${ei(o)};`,`width: ${ei(s)};`,`max-height: ${ei(r)};`].join(" ")}function ei(e){return`${String(Math.round(e))}px`}var Fb=Object.defineProperty,Bb=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fb(t,i,o),o};let x=class extends C{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2072
- <header>
2073
- <strong>PI WEB</strong>
2074
- ${Ai(this.machines)?l`
2075
- <machine-switcher
2076
- .machines=${this.machines}
2077
- .selected=${this.selectedMachine}
2078
- .statuses=${this.machineStatuses}
2079
- .activities=${this.machineActivities}
2080
- .onSelect=${e=>this.onSelectMachine?.(e)}
2081
- .onRemove=${e=>this.onRemoveMachine?.(e)}
2082
- .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
2083
- .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2084
- ></machine-switcher>
2085
- `:null}
2086
- <div class="header-actions">
2087
- ${this.refreshControl}
2088
- <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
2089
- </div>
2090
- </header>
2091
- ${this.compact&&Ai(this.machines)?l`
2092
- <machine-list
2093
- .machines=${this.machines}
2094
- .selected=${this.selectedMachine}
2095
- .statuses=${this.machineStatuses}
2096
- .activities=${this.machineActivities}
2097
- .collapsible=${this.collapsible}
2098
- .collapsed=${this.machinesCollapsed}
2099
- .onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
2100
- .onSelect=${e=>this.onSelectMachine?.(e)}
2101
- .onRemove=${e=>this.onRemoveMachine?.(e)}
2102
- .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
2103
- .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2104
- ></machine-list>
2105
- `:null}
2106
- <project-list
2107
- .projects=${this.projects}
2108
- .selected=${this.selectedProject}
2109
- .activities=${this.workspaceActivities}
2110
- .workspacesByProjectId=${this.workspacesByProjectId}
2111
- .collapsible=${this.collapsible}
2112
- .collapsed=${this.projectsCollapsed}
2113
- .onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
2114
- .onSelect=${e=>this.onSelectProject?.(e)}
2115
- .onClose=${e=>this.onCloseProject?.(e)}
2116
- .onFocusPreviousSection=${()=>{this.focusPreviousFrom("projects")}}
2117
- .onFocusNextSection=${()=>{this.focusNextFrom("projects")}}
2118
- .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2119
- ></project-list>
2120
- <workspace-list
2121
- .workspaces=${this.workspaces}
2122
- .selected=${this.selectedWorkspace}
2123
- .activities=${this.workspaceActivities}
2124
- .deletingWorkspaceIds=${this.deletingWorkspaceIds}
2125
- .collapsible=${this.collapsible}
2126
- .collapsed=${this.workspacesCollapsed}
2127
- .workspaceLabelItems=${this.workspaceLabelItems}
2128
- .onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
2129
- .onSelect=${e=>this.onSelectWorkspace?.(e)}
2130
- .onDelete=${e=>this.onDeleteWorkspace?.(e)}
2131
- .onFocusPreviousSection=${()=>{this.focusPreviousFrom("workspaces")}}
2132
- .onFocusNextSection=${()=>{this.focusNextFrom("workspaces")}}
2133
- .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2134
- ></workspace-list>
2135
- <session-list
2136
- .sessions=${this.sessions}
2137
- .statuses=${this.sessionStatuses}
2138
- .activities=${this.sessionActivities}
2139
- .sending=${this.sendingPrompts}
2140
- .selected=${this.selectedSession}
2141
- .canStart=${this.canStartSession}
2142
- .canDeleteArchived=${this.canDeleteArchivedSessions}
2143
- .canReload=${this.canReloadSessions}
2144
- .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
2145
- .collapsible=${this.collapsible}
2146
- .collapsed=${this.sessionsCollapsed}
2147
- .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
2148
- .onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
2149
- .onStart=${()=>this.onStartSession?.()}
2150
- .onSelect=${e=>this.onSelectSession?.(e)}
2151
- .onArchive=${e=>this.onArchiveSession?.(e)}
2152
- .onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
2153
- .onArchiveMany=${e=>this.onArchiveSessions?.(e)}
2154
- .onRestore=${e=>this.onRestoreSession?.(e)}
2155
- .onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
2156
- .onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
2157
- .onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
2158
- .onDetachParent=${e=>this.onDetachParentSession?.(e)}
2159
- .onReload=${e=>this.onReloadSession?.(e)}
2160
- .onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
2161
- .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2162
- .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2163
- ></session-list>
2164
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Ub(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Hb(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=O`
2165
- :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2166
- :host([compact]) { flex: 1 1 auto; }
2167
- header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
2168
- header strong { flex: 0 0 auto; }
2169
- machine-switcher { flex: 1 1 auto; min-width: 0; }
2170
- :host([compact]) header { display: none; }
2171
- .header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
2172
- 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); }
2173
- session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
2174
- machine-list[collapsed],
2175
- project-list[collapsed],
2176
- workspace-list[collapsed],
2177
- session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2178
- :host([compact]) machine-list,
2179
- :host([compact]) project-list,
2180
- :host([compact]) workspace-list,
2181
- :host([compact]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
2182
- :host([compact]) machine-list[collapsed],
2183
- :host([compact]) project-list[collapsed],
2184
- :host([compact]) workspace-list[collapsed],
2185
- :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2186
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2187
- `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([D("app-navigation-panel")],x);function Ai(e){return e.length>1}function Ub(e,t){const i=Ea(t);return i[i.indexOf(e)-1]}function Hb(e,t){const i=Ea(t);return i[i.indexOf(e)+1]??"chat"}function Ea(e){return ki.filter(t=>t!=="machines"||Ai(e))}var qb=Object.defineProperty,Kb=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?Kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&qb(t,i,o),o};const Vb=new Set(["ArrowLeft","ArrowRight","Home","End"]),Gb=420,Qb=4;let K=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2188
- ${this.renderResizeHandle()}
2189
- <button
2190
- type="button"
2191
- class="edge-button"
2192
- title=${e}
2193
- aria-label=${e}
2194
- aria-controls=${this.controls}
2195
- aria-expanded=${String(!this.collapsed)}
2196
- @click=${()=>{this.onToggle?.()}}
2197
- >${this.renderIcon()}</button>
2198
- `}renderResizeHandle(){if(!this.resizable)return F;const e=this.resizeConstraints();return l`
2199
- <div
2200
- class="resize-handle"
2201
- role="separator"
2202
- tabindex="0"
2203
- aria-label=${this.resizeLabel}
2204
- title=${`${this.resizeLabel}. Double-click or double-tap to reset.`}
2205
- aria-controls=${this.controls}
2206
- aria-orientation="vertical"
2207
- aria-valuemin=${String(e.minWidth)}
2208
- aria-valuemax=${String(e.maxWidth)}
2209
- aria-valuenow=${this.resizeAriaValueNow()}
2210
- @pointerdown=${t=>{this.onResizePointerDown(t)}}
2211
- @pointermove=${t=>{this.onResizePointerMove(t)}}
2212
- @pointerup=${t=>{this.onResizePointerUp(t)}}
2213
- @pointercancel=${t=>{this.onResizePointerCancel(t)}}
2214
- @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2215
- @keydown=${t=>{this.onResizeKeyDown(t)}}
2216
- ></div>
2217
- `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Qb)&&(t.moved=!0,this.commitPanelWidth(hf(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Vb.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=uf(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Gb){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Ut(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=O`
2218
- :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
2219
- :host([side="navigation"]) { grid-column: 2; }
2220
- :host([side="workspace"]) { grid-column: 4; }
2221
- .resize-handle { position: absolute; inset: 0 -6px; z-index: 0; cursor: col-resize; touch-action: none; outline: none; }
2222
- .resize-handle::after { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; transform: translateX(-50%); background: transparent; transition: width .12s ease, background .12s ease, opacity .12s ease; }
2223
- .resize-handle:hover::after, .resize-handle:focus-visible::after, :host([resizing]) .resize-handle::after { width: 3px; background: var(--pi-accent); opacity: .72; }
2224
- .edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
2225
- .edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
2226
- :host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
2227
- :host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
2228
- .edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2229
- @media (max-width: 1180px) {
2230
- :host([side="navigation"]) { grid-row: 1 / 3; }
2231
- :host([side="workspace"]) { display: none; }
2232
- }
2233
- @media (max-width: 760px) {
2234
- :host([side="navigation"]) { display: none; }
2235
- }
2236
- `;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([D("app-panel-edge-control")],K);var Zb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,Da=(e,t,i,s)=>{for(var o=s>1?void 0:s?Jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zb(t,i,o),o};let Ti=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
2237
- <button
2238
- class="app-refresh-button"
2239
- title=${e}
2240
- aria-label=${e}
2241
- @click=${this.onReloadClick}
2242
- >${this.renderRefreshIcon()}</button>
2243
- `}renderRefreshIcon(){return l`
2244
- <svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2245
- <path d="M20 6v5h-5"></path>
2246
- <path d="M4 18v-5h5"></path>
2247
- <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2248
- <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2249
- </svg>
2250
- `}};Ti.styles=O`
2251
- :host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
2252
- :host, :host * { -webkit-user-select: none; user-select: none; }
2253
- .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
2254
- .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2255
- `;Da([d({attribute:!1})],Ti.prototype,"onReload",2);Ti=Da([D("app-refresh-control")],Ti);var Xb=Object.defineProperty,Yb=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Yb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Xb(t,i,o),o};const ew=900*1e3,tw=750,Os=[1e3,3e3,8e3,15e3,3e4],Xr={capture:!0},hs="auto:on",Yr="auto:off",ti="theme:",us=Nt("core:workspace.files"),fs=Nt("core:workspace.git"),ii=Nt("core:workspace.terminal"),iw=320,sw=2,ow="(min-width: 1181px)";let de=class extends C{constructor(){super(...arguments),this.state=td(),this.sessions=new Vp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Fp),this.activity=new id(()=>this.state,e=>{this.setState(e)}),this.auth=new rd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new ah(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new rh),this.projects=new fd(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new ud(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new cd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new hd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new yh,this.realtime=new ir,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new ph,this.terminalSelection=new bh,this.appShell=new Zu(this),this.panelCollapse=new lf(this),this.panelResize=new df(this),this.navigationSections=new rf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=rw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=_h()??Eh,this.activeThemeId=io,this.isRefreshingApp=!1,this.settingsSection=wr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},ew),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!lw(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),nw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=br();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=tw){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await yn.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Wa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ui.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(br(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?sn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?sn():{selectedFilePath:Qi(us,"file"),selectedDiffPath:Qi(fs,"diff"),selectedTerminalId:Qi(ii,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){ts(e,{replace:!0}),xe(us,"file",void 0,{replace:!0}),xe(fs,"diff",void 0,{replace:!0}),xe(ii,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=dw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Os.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gs(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),ts({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(rr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(rr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ts(nr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){xe(us,"file",e.selectedFilePath,{replace:!0}),xe(fs,"diff",e.selectedDiffPath,{replace:!0}),xe(ii,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??hh(e.id);if(await this.restoreRouteFor(nr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=on(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=If(e,{api:{runTerminalCommand:(r,n)=>pt.runTerminalCommand(r,n,t),listCommandRuns:r=>pt.listCommandRuns(r,t),getCommandRun:r=>pt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){xe(ii,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,is(e)}closeSettings(){this.settingsSection=void 0,is(void 0)}navigateSettings(e){this.settingsSection=e,is(e)}restoreSettingsRoute(){this.settingsSection=wr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new ir;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>aw(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):cw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await pt.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=tn(e),s=tn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2256
- <workspace-panel
2257
- id="workspace-panel"
2258
- .workspace=${e}
2259
- .panelContext=${t}
2260
- .emptyState=${i}
2261
- .tool=${this.state.workspaceTool}
2262
- .panels=${this.visibleWorkspacePanels()}
2263
- .onSelectTool=${s=>{this.openWorkspaceTool(s)}}
2264
- ></workspace-panel>
2265
- `}renderNavigationPanelEdgeControl(){const e=this.resizablePanelConstraints("navigation");return l`
2266
- <app-panel-edge-control
2267
- side="navigation"
2268
- controls="navigation-panel"
2269
- resizeLabel="Resize navigation panel"
2270
- expandLabel="Expand navigation panel"
2271
- collapseLabel="Collapse navigation panel"
2272
- .collapsed=${this.panelCollapse.navigationPanelCollapsed}
2273
- .resizable=${!this.appShell.isMobileNavigationLayout}
2274
- .panelWidth=${this.panelResize.panelWidth("navigation")}
2275
- .minWidth=${e.minWidth}
2276
- .maxWidth=${e.maxWidth}
2277
- .onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
2278
- .onResizeStart=${()=>this.startPanelResize("navigation")}
2279
- .onResize=${t=>{this.panelResize.resizePanel("navigation",t,{persist:!1})}}
2280
- .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2281
- .onReset=${()=>{this.resetResizablePanel("navigation")}}
2282
- ></app-panel-edge-control>
2283
- `}renderWorkspacePanelEdgeControl(){const e=this.resizablePanelConstraints("workspace");return l`
2284
- <app-panel-edge-control
2285
- side="workspace"
2286
- controls="workspace-panel"
2287
- resizeLabel="Resize workspace panel"
2288
- expandLabel="Expand workspace panel"
2289
- collapseLabel="Collapse workspace panel"
2290
- .collapsed=${this.panelCollapse.workspacePanelCollapsed}
2291
- .resizable=${!this.appShell.isMobileNavigationLayout}
2292
- .panelWidth=${this.panelResize.panelWidth("workspace")}
2293
- .minWidth=${e.minWidth}
2294
- .maxWidth=${e.maxWidth}
2295
- .onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
2296
- .onResizeStart=${()=>this.startPanelResize("workspace")}
2297
- .onResize=${t=>{this.panelResize.resizePanel("workspace",t,{persist:!1})}}
2298
- .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2299
- .onReset=${()=>{this.resetResizablePanel("workspace")}}
2300
- ></app-panel-edge-control>
2301
- `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-sw-iw);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(ow).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsReload)}supportsWorkspaceFileSuggestions(e=g(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&ht(t,Ze.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}renderNavigationPanel(){return l`
2302
- <app-navigation-panel
2303
- .machines=${this.state.machines}
2304
- .selectedMachine=${this.state.selectedMachine}
2305
- .machineStatuses=${this.state.machineStatuses}
2306
- .machineActivities=${this.state.machineActivities}
2307
- .machinesCollapsed=${this.navigationSections.isCollapsed("machines")}
2308
- .onToggleMachines=${()=>{this.navigationSections.toggle("machines")}}
2309
- .onSelectMachine=${e=>this.selectNavigationItem("machines","projects",()=>this.selectMachineWithMemory(e))}
2310
- .onRemoveMachine=${e=>{this.removeMachine(e)}}
2311
- .projects=${this.state.projects}
2312
- .selectedProject=${this.state.selectedProject}
2313
- .workspaceActivities=${this.state.workspaceActivities}
2314
- .workspacesByProjectId=${this.state.workspacesByProjectId}
2315
- .workspaces=${this.state.workspaces}
2316
- .selectedWorkspace=${this.state.selectedWorkspace}
2317
- .deletingWorkspaceIds=${Qh(this.state.workspaceDeletionRuns)}
2318
- .sessions=${this.state.sessions}
2319
- .sessionStatuses=${this.state.sessionStatuses}
2320
- .sessionActivities=${this.state.sessionActivities}
2321
- .sendingPrompts=${this.state.sendingPrompts}
2322
- .selectedSession=${this.state.selectedSession}
2323
- .canStartSession=${!!this.state.selectedWorkspace}
2324
- .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
2325
- .canReloadSessions=${this.canReloadSessions()}
2326
- .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
2327
- .collapsible=${!0}
2328
- .compact=${this.appShell.isMobileNavigationLayout}
2329
- .projectsCollapsed=${this.navigationSections.isCollapsed("projects")}
2330
- .workspacesCollapsed=${this.navigationSections.isCollapsed("workspaces")}
2331
- .sessionsCollapsed=${this.navigationSections.isCollapsed("sessions")}
2332
- .workspaceLabelItems=${e=>this.workspaceLabelItems(e)}
2333
- .refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
2334
- .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
2335
- .onToggleProjects=${()=>{this.navigationSections.toggle("projects")}}
2336
- .onToggleWorkspaces=${()=>{this.navigationSections.toggle("workspaces")}}
2337
- .onToggleSessions=${()=>{this.navigationSections.toggle("sessions")}}
2338
- .onSelectProject=${e=>this.selectNavigationItem("projects","workspaces",()=>this.workspaces.selectProject(e))}
2339
- .onCloseProject=${e=>this.projects.closeProject(e.id)}
2340
- .onSelectWorkspace=${e=>this.selectNavigationItem("workspaces","sessions",()=>this.workspaces.selectWorkspace(e))}
2341
- .onDeleteWorkspace=${e=>{this.deleteWorkspace(e)}}
2342
- .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
2343
- .onStartSession=${()=>this.selectNavigationItem("sessions","chat",()=>this.sessions.startSession())}
2344
- .onSelectSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.selectSession(e))}
2345
- .onArchiveSession=${e=>this.sessions.archiveSession(e)}
2346
- .onArchiveSessionWithDescendants=${e=>this.sessions.archiveSessionWithDescendants(e)}
2347
- .onArchiveSessions=${e=>this.sessions.archiveSessions(e)}
2348
- .onRestoreSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.restoreSession(e))}
2349
- .onDeleteCachedNewSession=${e=>this.sessions.deleteCachedNewSession(e)}
2350
- .onDeleteArchivedSession=${e=>this.sessions.deleteArchivedSessions([e])}
2351
- .onDeleteArchivedSessions=${e=>this.sessions.deleteArchivedSessions(e)}
2352
- .onDetachParentSession=${e=>this.sessions.detachParent(e)}
2353
- .onReloadSession=${e=>this.sessions.reloadSession(e)}
2354
- .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2355
- .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2356
- ></app-navigation-panel>
2357
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,o=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},o),o()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ai(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await gs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=en(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>ys.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=en(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return ju({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Pf(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>fr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>fr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>Lu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!lh(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Kn(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2358
-
2359
- This will run git worktree remove and delete:
2360
- ${e.path}
2361
-
2362
- The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await ys.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${pw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=Is(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(Vh(t.id));if(g(this.state)!==e)return;const s=Gh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))Si(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(Si);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=on(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Is(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:hw(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
2363
-
2364
- This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Yr:hs;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${ti}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${ti}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hs||e===Yr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===hs},this.applyPreferredTheme(!0);return}if(!e.startsWith(ti))return;const t=e.slice(ti.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Lh(t),e&&Oh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return jh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return qn(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("auto pair"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:t,options:e.map(i=>{const s=uw(i);return{value:i,label:`${i}${i===t?" ✓ current":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2365
- <app-context-bar
2366
- .machines=${this.state.machines}
2367
- .machine=${this.state.selectedMachine}
2368
- .project=${this.state.selectedProject}
2369
- .workspace=${this.state.selectedWorkspace}
2370
- .session=${this.state.selectedSession}
2371
- .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
2372
- .onOpenSection=${e=>{this.openNavigationSection(e)}}
2373
- .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
2374
- ></app-context-bar>
2375
- `:null}renderMobileMainTabs(){return l`
2376
- <app-mobile-main-tabs
2377
- .tabs=${this.mobileMainTabs()}
2378
- .selectedView=${this.state.mainView}
2379
- .onSelect=${e=>{this.selectMainView(e)}}
2380
- ></app-mobile-main-tabs>
2381
- `}mobileMainTabs(){return[{id:"navigation",label:"Sessions",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"Chat",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
2382
- <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2383
- <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2384
- ${this.renderNavigationPanelEdgeControl()}
2385
- <main class=${Xn(e.mainView)}>
2386
- ${this.renderContextBar()}
2387
- ${this.renderMobileMainTabs()}
2388
- ${e.error?l`<div class="error">${e.error}</div>`:null}
2389
- <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2390
- ${e.selectedSession?l`
2391
- <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
2392
- <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${(t,i,s,o)=>{this.sendPrompt(t,i,s,o)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2393
- <status-bar .status=${e.status}></status-bar>
2394
- ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
2395
- ${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
2396
- ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
2397
- ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
2398
- `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
2399
- </main>
2400
- ${this.renderWorkspacePanelEdgeControl()}
2401
- ${this.renderWorkspacePanel()}
2402
- ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
2403
- ${e.projectDialogOpen?l`<project-dialog .machineId=${g(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
2404
- ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
2405
- ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
2406
- ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2407
- </div>
2408
- `}};de.styles=zf;Me([w()],de.prototype,"state",2);Me([B("chat-view")],de.prototype,"chatView",2);Me([B("prompt-editor")],de.prototype,"promptEditor",2);Me([B("app-navigation-panel")],de.prototype,"navigationPanel",2);Me([B("#navigation-panel")],de.prototype,"navigationPanelFrame",2);Me([B("#workspace-panel")],de.prototype,"workspacePanelFrame",2);Me([w()],de.prototype,"activeThemeId",2);Me([w()],de.prototype,"isRefreshingApp",2);Me([w()],de.prototype,"settingsSection",2);Me([w()],de.prototype,"shortcutConfig",2);de=Me([D("pi-web-app")],de);function rw(){const e=new _u;return e.register({id:"core",plugin:bu}),e.register({id:"themes",plugin:xu}),e}function en(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function nw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function aw(e,t){return Wa(e,t)}function Wa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function lw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function tn(e){return Ye(e.status,e.activity)}function cw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function sn(){return{}}function on(e,t){return JSON.stringify([e,t])}function dw(e){const t=Math.min(e,Os.length-1);return Os[t]??3e4}function pw(e){return e instanceof Error?e.message:String(e)}function hw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function uw(e){switch(e){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)";default:return}}export{O as a,l as b,pt as c,Rw as d,B as e,$w as f,C as i,d as n,w as r,Pw as s,D as t};