@chainingintention/pi-web-cn 1.202606.22 → 1.202606.24
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.
- package/dist/client/assets/{CodeViewer-B1z_k75G.js → CodeViewer-DA68s2LY.js} +1 -1
- package/dist/client/assets/{TerminalPanel-CqG27wd5.js → TerminalPanel-DR8I9BBO.js} +1 -1
- package/dist/client/assets/{index-bm72ZAqQ.js → index-Bjpa_x8C.js} +3 -3
- package/dist/client/index.html +1 -1
- package/dist/server/sessions/managementAgentTools.js +118 -77
- package/dist/server/sessions/managementAgentTools.js.map +1 -1
- package/dist/server/sessions/managementPermissionSystem.js +92 -0
- package/dist/server/sessions/managementPermissionSystem.js.map +1 -0
- package/dist/server/sessions/piSessionService.js +75 -16
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/sessions/sessionRoutes.js +5 -5
- package/dist/server/sessions/sessionRoutes.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-DA68s2LY.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-DR8I9BBO.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{Q as Ao,w as rt,J as Ji,R as el,S as tl,G as il,U as sl,V as ol,A as rl,W as nl,X as al,Y as ll,Z as Mo,x as Eo,_ as cl}from"./vendor-editor-core-Bc1A7SO7.js";import{m as dl,i as pl,d as hl}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 oi=globalThis,Hs=oi.ShadowRoot&&(oi.ShadyCSS===void 0||oi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,qs=Symbol(),Do=new WeakMap;let mn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==qs)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(Hs&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Do.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Do.set(i,t))}return t}toString(){return this.cssText}};const ul=e=>new mn(typeof e=="string"?e:e+"",void 0,qs),D=(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 mn(i,e,qs)},fl=(e,t)=>{if(Hs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=oi.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Wo=Hs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return ul(i)})(e):e;const{is:gl,defineProperty:ml,getOwnPropertyDescriptor:vl,getOwnPropertyNames:bl,getOwnPropertySymbols:wl,getPrototypeOf:yl}=Object,Di=globalThis,Oo=Di.trustedTypes,Sl=Oo?Oo.emptyScript:"",xl=Di.reactiveElementPolyfillSupport,At=(e,t)=>e,pi={toAttribute(e,t){switch(t){case Boolean:e=e?Sl: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}},Ks=(e,t)=>!gl(e,t),_o={attribute:!0,type:String,converter:pi,reflect:!1,useDefault:!1,hasChanged:Ks};Symbol.metadata??=Symbol("metadata"),Di.litPropertyMetadata??=new WeakMap;let ct=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=_o){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&&ml(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=vl(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)??_o}static _$Ei(){if(this.hasOwnProperty(At("elementProperties")))return;const t=yl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(At("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(At("properties"))){const i=this.properties,s=[...bl(i),...wl(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(Wo(o))}else t!==void 0&&i.push(Wo(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 fl(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:pi).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:pi;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??Ks)(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){}};ct.elementStyles=[],ct.shadowRootOptions={mode:"open"},ct[At("elementProperties")]=new Map,ct[At("finalized")]=new Map,xl?.({ReactiveElement:ct}),(Di.reactiveElementVersions??=[]).push("2.1.2");const Vs=globalThis,Lo=e=>e,hi=Vs.trustedTypes,jo=hi?hi.createPolicy("lit-html",{createHTML:e=>e}):void 0,vn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,bn="?"+Be,kl=`<${bn}>`,Ze=document,Dt=()=>Ze.createComment(""),Wt=e=>e===null||typeof e!="object"&&typeof e!="function",Gs=Array.isArray,$l=e=>Gs(e)||typeof e?.[Symbol.iterator]=="function",Qi=`[
|
|
3
3
|
\f\r]`,wt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Fo=/-->/g,No=/>/g,qe=RegExp(`>|${Qi}(?:([^\\s"'>=/]+)(${Qi}*=${Qi}*(?:[^
|
|
4
4
|
\f\r"'\`<>=]|("|')|))|$)`,"g"),zo=/'/g,Bo=/"/g,wn=/^(?:script|style|textarea|title)$/i,yn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=yn(1),he=yn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Uo=new WeakMap,Je=Ze.createTreeWalker(Ze,129);function Sn(e,t){if(!Gs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return jo!==void 0?jo.createHTML(t):t}const Pl=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=wt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===wt?u[1]==="!--"?n=Fo:u[1]!==void 0?n=No:u[2]!==void 0?(wn.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??wt,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]==='"'?Bo:zo):n===Bo||n===zo?n=qe:n===Fo||n===No?n=wt:(n=qe,o=void 0);const w=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===wt?c+kl:h>=0?(s.push(p),c.slice(0,h)+vn+c.slice(h)+Be+w):c+Be+(h===-2?a:w)}return[Sn(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]=Pl(t,i);if(this.el=Ot.createElement(p,s),Je.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Je.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(vn)){const g=u[n++],w=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:r,name:P[2],strings:w,ctor:P[1]==="."?Il:P[1]==="?"?Cl:P[1]==="@"?Tl:Wi}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(wn.test(o.tagName)){const h=o.textContent.split(Be),g=h.length-1;if(g>0){o.textContent=hi?hi.emptyScript:"";for(let w=0;w<g;w++)o.append(h[w],Dt()),Je.nextNode(),c.push({type:2,index:++r});o.append(h[g],Dt())}}}else if(o.nodeType===8)if(o.data===bn)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=Ze.createElement("template");return s.innerHTML=t,s}}function pt(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Wt(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=pt(e,o._$AS(e,t.values),o,s)),t}class Rl{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ze).importNode(i,!0);Je.currentNode=o;let r=Je.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ft(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new Al(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Je.nextNode(),n++)}return Je.currentNode=Ze,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 ft{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=pt(this,t,i),Wt(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):$l(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&&Wt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ze.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(Sn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Rl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Uo.get(t.strings);return i===void 0&&Uo.set(t.strings,i=new Ot(t)),i}k(t){Gs(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 ft(this.O(Dt()),this.O(Dt()),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=Lo(t).nextSibling;Lo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Wi=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=pt(this,t,i,0),n=!Wt(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=pt(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!Wt(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??"")}},Il=class extends Wi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},Cl=class extends Wi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},Tl=class extends Wi{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=pt(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)}},Al=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){pt(this,t)}};const Ml={I:ft},El=Vs.litHtmlPolyfillSupport;El?.(Ot,ft),(Vs.litHtmlVersions??=[]).push("3.3.3");const Dl=(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 ft(t.insertBefore(Dt(),r),r,void 0,i??{})}return o._$AI(e),o};const Js=globalThis;let C=class extends ct{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=Dl(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,Js.litElementHydrateSupport?.({LitElement:C});const Wl=Js.litElementPolyfillSupport;Wl?.({LitElement:C});(Js.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Ol={attribute:!0,type:String,converter:pi,reflect:!1,hasChanged:Ks},_l=(e=Ol,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"?_l(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 k(e){return d({...e,state:!0,attribute:!1})}const Ll=(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 Ll(i,s,{get(){return r(this)}})}}function xn(e,t=Fl()){if(t===void 0)return e;const i=jl(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function jl(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Fl(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(xn(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Nl(n)??o.statusText)}const r=await o.json();return t(r)}function Nl(e){if(zl(e))return typeof e.error=="string"?e.error:void 0}function zl(e){return typeof e=="object"&&e!==null}const ht={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},Bl=Object.values(ht),Ul=new Set(Bl);function Hl(e){return typeof e=="string"&&Ul.has(e)}function _t(e,t){return e?.capabilities?.includes(t)===!0}function Mt(e){return typeof e=="object"&&e!==null}function b(e){if(!Mt(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 ee(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 ql(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Kl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Vl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=b(e);return{messages:ql(t.messages),start:ee(t,"start"),total:ee(t,"total")}}function Gl(e){const t=b(e);return N(kn)(t.machines)}function kn(e){const t=b(e),i=Zl(t,"kind"),s=$(t,"baseUrl"),o=$n(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 Jl(e){const t=b(e),i=$n(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:ui(t.web)},...t.sessiond===void 0?{}:{sessiond:ui(t.sessiond)},...s===void 0?{}:{error:s}}}function Ql(e){const t=b(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...y("packageName",$(t,"packageName")),...y("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:In(t.components)},...t.capabilities===void 0?{}:{capabilities:Qs(t.capabilities)},...i===void 0?{}:{error:i}}}function Zl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function $n(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 Ho(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Xl(e){const t=b(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 ks(e){const t=b(e);return{path:m(t,"path"),size:ee(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Zi(e){const t=b(e);return{path:m(t,"path")}}function qo(e){const t=b(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function $s(e){const t=b(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:ee(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function yt(e){const t=b(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:ee(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Yl)(t.queuedMessages),...y("messageCount",Pe(t,"messageCount")),tokens:ec(t.tokens),cost:ee(t,"cost"),...sc(t.model),...mc(t.contextUsage),...y("thinkingLevel",$(t,"thinkingLevel"))}}function Yl(e){const t=b(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...y("imageCount",Pe(t,"imageCount"))}}function ec(e){const t=b(e);return{input:ee(t,"input"),output:ee(t,"output"),cacheRead:ee(t,"cacheRead"),cacheWrite:ee(t,"cacheWrite"),total:ee(t,"total")}}function Pn(e){const t=b(e);return{...y("provider",$(t,"provider")),...y("id",$(t,"id")),...y("name",$(t,"name")),...y("contextWindow",Pe(t,"contextWindow")),...y("reasoning",t.reasoning),...y("input",tc(t.input))}}function tc(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(ic)}}function ic(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function sc(e){return e===void 0?{}:{model:Pn(e)}}function oc(e){const t=b(e);return{models:N(Pn)(t.models)}}function rc(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function nc(e){const t=b(e);return{levels:N(rc)(t.levels)}}function ac(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function lc(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 cc(e){const t=b(e),i=t.source===void 0?void 0:lc(t.source);return{configured:E(t,"configured"),...y("source",i),...y("label",$(t,"label"))}}function dc(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),authType:ac(t.authType),status:cc(t.status)}}function pc(e){const t=b(e);return{providers:N(dc)(t.providers)}}function Vt(e){const t=b(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:hc(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...y("error",$(t,"error")),...y("auth",uc(t.auth)),...y("prompt",fc(t.prompt)),...y("select",gc(t.select))}}function hc(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function uc(e){if(e===void 0)return;const t=b(e);return{url:m(t,"url"),...y("instructions",$(t,"instructions"))}}function fc(e){if(e===void 0)return;const t=b(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,...y("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function gc(e){if(e===void 0)return;const t=b(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(Tn)(t.options)}}function mc(e){if(e===void 0)return{};const t=b(e);return{contextUsage:{tokens:Yo(t,"tokens"),contextWindow:ee(t,"contextWindow"),percent:Yo(t,"percent")}}}function vc(e){const t=b(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,...y("description",$(t,"description"))}}function Rn(e){const t=b(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 bc(e){const t=b(e);return{path:m(t,"path"),entries:N(wc)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function wc(e){const t=b(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,...y("size",Pe(t,"size")),...y("modifiedAt",$(t,"modifiedAt"))}}function yc(e){const t=b(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...y("language",$(t,"language")),...y("mediaType",Sc(t.mediaType)),...y("mimeType",$(t,"mimeType")),encoding:i,size:ee(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function Sc(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function xc(e){const t=b(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...y("branch",$(t,"branch")),...y("upstream",$(t,"upstream")),...y("ahead",Pe(t,"ahead")),...y("behind",Pe(t,"behind")),files:N(kc)(t.files)}}function kc(e){const t=b(e);return{path:m(t,"path"),...y("oldPath",$(t,"oldPath")),index:Ko(t.index),workingTree:Ko(t.workingTree)}}function Ko(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 $c(e){const t=b(e);return{...y("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Xi(e){const t=b(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...y("exitCode",Pe(t,"exitCode")),...y("commandRunId",$(t,"commandRunId"))}}function Et(e){const t=b(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:Pc(t.status),...y("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...y("startedAt",$(t,"startedAt")),...y("completedAt",$(t,"completedAt")),metadata:Rc(t.metadata,"metadata")}}function Pc(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=b(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Ic(e){const t=b(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Cc(e){const t=b(e);return{workspaces:N(Ic)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Vo(e){const t=b(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Go(t.config),effectiveConfig:Go(t.effectiveConfig),envOverrides:Ec(t.envOverrides)}}function Go(e){const t=b(e);return{...y("host",$(t,"host")),...y("port",Pe(t,"port")),...y("allowedHosts",Tc(t.allowedHosts)),...y("shortcuts",Ac(t.shortcuts)),...y("plugins",Mc(t.plugins)),...y("spawnSessions",Xo(t,"spawnSessions")),...y("subsessions",Xo(t,"subsessions"))}}function Tc(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function Ac(e){if(e!==void 0){if(!Mt(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 Mc(e){if(e!==void 0){if(!Mt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Mt(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&&(!Mt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Ec(e){const t=b(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function Dc(e){const t=b(e);return{plugins:N(Wc)(t.plugins)}}function Wc(e){const t=b(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Oc(t.scope),machineSpecific:_c(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function Oc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function _c(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Lc(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Fc(t.components),release:zc(t.release),commands:Bc(t.commands),messages:N(Uc)(t.messages)}}function jc(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:In(t.components),capabilities:Qs(t.capabilities)}}function Fc(e){const t=b(e);return{web:ui(t.web),sessiond:ui(t.sessiond)}}function In(e){const t=b(e);return{web:Jo(t.web),sessiond:Jo(t.sessiond)}}function Jo(e){const t=b(e);return{component:Cn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Qs(t.capabilities),...y("error",$(t,"error"))}}function ui(e){const t=b(e);return{component:Cn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),...y("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...y("installation",Nc(t.installation)),...y("error",$(t,"error"))}}function Nc(e){if(e===void 0)return;const t=b(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,...y("path",$(t,"path")),...y("source",$(t,"source")),...s===void 0?{}:{scope:s},...y("npmRoot",$(t,"npmRoot"))}}function zc(e){const t=b(e);return{packageName:m(t,"packageName"),...y("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...y("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...y("error",$(t,"error"))}}function Bc(e){const t=b(e);return{...y("update",$(t,"update")),...y("restart",$(t,"restart")),...y("restartWeb",$(t,"restartWeb")),...y("restartSessiond",$(t,"restartSessiond")),...y("status",$(t,"status"))}}function Uc(e){const t=b(e);return{id:m(t,"id"),severity:Hc(t.severity),title:m(t,"title"),body:m(t,"body"),...y("command",$(t,"command"))}}function Cn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Qs(e){if(!Array.isArray(e)||!e.every(Hl))throw new Error("Invalid PI WEB capabilities");return e}function Hc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Qo(e){const t=b(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(Tn)(t.options)};if(i==="done")return{type:i,...y("message",$(t,"message")),...qc(t.session),...y("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Tn(e){const t=b(e);return{value:m(t,"value"),label:m(t,"label"),...y("description",$(t,"description"))}}function qc(e){return e===void 0?{}:{session:$s(e)}}function Gt(e){if(b(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Kc(e){const t=b(e);return N(Vc)(t.attachments)}function Vc(e){const t=b(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:ee(t,"size")}}function Ps(e){if(b(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Gc(e){if(b(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Jc(e){if(b(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Zo(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Kl(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 Qc(e){if(b(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Zc(e){if(b(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Xc(e){if(b(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Yc(e){if(b(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Xo(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 Yo(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 y(e,t){return t===void 0?{}:{[e]:t}}function ed(e){return typeof e=="string"?e:e.id}function td(e){return typeof e=="string"?void 0:e.cwd}function id(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 sd(e,t,i="local"){const s=new URLSearchParams,o=td(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(ed(e))}/messages${r===""?"":`?${r}`}`}function od(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()}`}function An(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return xn(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function rd(e){return typeof e=="string"?e:e.id}function Mn(e){return typeof e=="string"?void 0:e.cwd}function En(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(rd(e))}`}function K(e,t,i="local"){return`${En(e,i)}/${t}`}function Jt(e,t,i="local"){return`${K(e,t,i)}${Dn(e)}`}function nd(e,t="local"){return`${En(e,t)}${Dn(e)}`}function Dn(e){const t=Mn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function V(e,t={}){const i=Mn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const Wn={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,Lc),piWebRuntime:()=>v("/api/pi-web/runtime",jc)},ad={machines:()=>v("/api/machines",Gl),addMachine:e=>v("/api/machines",kn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,Jl),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Ql)},fi={config:()=>v("/api/config",Vo),saveConfig:e=>v("/api/config",Vo,{method:"PUT",body:JSON.stringify({config:e})})},Rs={plugins:()=>v("/api/plugins",Dc)},On={workspaceActivity:(e="local")=>v(`${R(e)}/activity`,Cc)},ld={projects:(e="local")=>v(`${R(e)}/projects`,N(Ho)),addProject:(e,t,i,s="local")=>v(`${R(s)}/projects`,Ho,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${R(t)}/projects/${encodeURIComponent(e)}`,Ps,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,N(Rn))},Is={workspaces:(e,t="local")=>v(`${R(t)}/projects/${e}/workspaces`,N(Xl)),deleteWorkspace:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Et,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,bc),workspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,yc),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?fd(e,t,i,s):v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:await hd(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,qo,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zi,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,qo,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>An(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>gd(e,t,i,s)},cd={sessions:(e,t="local")=>v(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,N($s)),startSession:(e,t="local")=>v(`${R(t)}/sessions`,$s,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(sd(e,t,i),Vl),status:(e,t="local")=>v(Jt(e,"status",t),yt),models:(e,t="local")=>v(Jt(e,"models",t),oc),setModel:(e,t,i,s="local")=>v(K(e,"model",s),yt,{method:"POST",body:V(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(K(e,"model/cycle",i),yt,{method:"POST",body:V(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(Jt(e,"thinking-levels",t),nc),setThinkingLevel:(e,t,i="local")=>v(K(e,"thinking-level",i),yt,{method:"POST",body:V(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(K(e,"thinking-level/cycle",t),yt,{method:"POST",body:V(e)}),commands:(e,t="local")=>v(Jt(e,"commands",t),N(vc)),prompt:(e,t,i,s="local",o)=>v(K(e,"prompt",s),Gt,{method:"POST",body:V(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>v(K(e,"attachments",i),Kc,{method:"POST",body:V(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(K(e,"shell",i),Gt,{method:"POST",body:V(e,{text:t})}),runCommand:(e,t,i="local")=>v(K(e,"commands/run",i),Qo,{method:"POST",body:V(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(K(e,"commands/respond",s),Qo,{method:"POST",body:V(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(K(e,"abort",t),Gc,{method:"POST",body:V(e)}),stop:(e,t="local")=>v(K(e,"stop",t),Jc,{method:"POST",body:V(e)}),archive:(e,t="local")=>v(K(e,"archive",t),Zo,{method:"POST",body:V(e)}),archiveWithDescendants:(e,t="local")=>v(K(e,"archive-tree",t),Zo,{method:"POST",body:V(e)}),restore:(e,t="local")=>v(K(e,"restore",t),Qc,{method:"POST",body:V(e)}),deleteArchived:(e,t="local")=>v(nd(e,t),Zc,{method:"DELETE"}),detachParent:(e,t="local")=>v(K(e,"detach-parent",t),Xc,{method:"POST",body:V(e)}),reloadSession:(e,t="local")=>v(K(e,"reload",t),Yc,{method:"POST",body:V(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 v(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,pc)},saveApiKey:(e,t,i="local")=>v(`${R(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${R(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${R(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>v(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},dt={terminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Xi)),startTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Xi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ps,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Ps,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Xi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Et,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${R(t)}/terminal-command-runs${pd(e)}`,N(Et)),getCommandRun:(e,t="local")=>dd(e,t),cancelCommandRun:(e,t="local")=>v(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Et,{method:"POST"})};async function dd(e,t){const i=await fetch(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Zs(s)??i.statusText)}return Et(await i.json())}}function pd(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 Zs(e){if(!md(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function hd(e){return ud(await e.arrayBuffer())}function ud(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function fd(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Zs(n)??r.statusText)}return ks(await r.json())}async function gd(e,t,i,s){const o=await fetch(An(e,t,i,{machineId:s}));if(!o.ok){const p=await o.json().catch(()=>({}));throw new Error(Zs(p)??o.statusText)}const r=await o.blob(),n=URL.createObjectURL(r),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function md(e){return typeof e=="object"&&e!==null}const vd={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${R(i.machineId)}/files?${s.toString()}`,N(Rn))}},bd={gitStatus:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,xc),gitDiff:(e,t,i,s="local")=>v(id(s,e,t,i),$c)},z={...Wn,...ad,...fi,...Rs,...On,...ld,...Is,...cd,...dt,...vd,...bd};function wd(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(`${Ys()}${Xs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function ry(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ys()}${Xs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function yd(e="local"){return new WebSocket(`${Ys()}${Xs(e)}/events`)}function Xs(e){return`/api/machines/${encodeURIComponent(e)}`}function Ys(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function ri(){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 Sd(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function _n(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Ln="local";function Yi(e,t){return`${e}:${t}`}function jn(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Ln}class xd{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??On}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,kd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),o=f(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=$d(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},...f(s)===t?{workspaceActivities:i}:{}})}}function kd(e){const t={};for(const i of e.workspaces)_n(i)&&(t[i.cwd]=i);return t}function $d(e,t){const i={...e};return _n(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Pd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??z,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Rd(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:f(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,f(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:f(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,f(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,f(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,f(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:f(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,f(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,f(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,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Rd(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 Ft(e){return e.replaceAll(":",".")}function Id(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 es(e,t){const i=Id(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ae(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));Cd(o,s)}function Cd(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 Qt=Ft("core:workspace.files");class Td{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??z}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(er(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,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:Ad(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,f(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"}),ae(Qt,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}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 this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(er(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=f(this.getState()),r=Md(this.getState()),n=[];for(const c of t){const p=Dd(r,Ed(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=f(this.getState());ts(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const o=f(this.getState());ts(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||ts(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function er(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Ad(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Md(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(Fn(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function ts(e){const t=e.selectedFilePath;return t===void 0?"file":Fn(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function Fn(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Ed(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Dd(e,t){return e===""?t:`${e}/${t}`}const tr=Ft("core:workspace.git");class Wd{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 z.gitStatus(t.id,i.id,f(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}),ae(tr,"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"}),ae(tr,"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([z.gitDiff(i.id,s.id,{path:t},f(this.getState())),z.gitDiff(i.id,s.id,{path:t,staged:!0},f(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 Od{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 z.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:ir(this.getState().machineActivities,o),machineRuntimes:ir(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,...ri()}),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 z.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 z.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:is(this.getState().machineStatuses,t.id),machineRuntimes:is(this.getState().machineRuntimes,t.id),machineActivities:is(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 z.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 z.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 z.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=>z.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=>z.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 is(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ir(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class _d{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await z.projects(t);if(f(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){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await z.addProject(t.trim(),void 0,i,f(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 z.closeProject(t,f(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 Cs="pi-web:cached-new-sessions:v1",Ld="browserCachedNew",gt="local";function Nt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function sr(e,t=gt,i=Nt()){if(e.messageCount!==0||e.archived===!0)return;const s=eo(i).filter(o=>o.id!==e.id||o.machineId!==t);to([Ts(e,t),...s],i)}function Ts(e,t=gt){return{...e,browserCachedNew:!0,machineId:t}}function or(e,t=gt,i=Nt()){const s=eo(i).filter(o=>o.id!==e||o.machineId!==t);to(s,i)}function jd(e,t,i=gt,s=Nt()){const o=new Set(t.map(c=>c.id)),r=eo(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&to(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:zd(e)&&e.browserCachedNew===!0}function Fd(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:gt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function eo(e=Nt()){try{const t=e?.getItem(Cs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Nd(s)):[]}catch{return[]}}function to(e,t=Nt()){try{e.length===0?t?.removeItem(Cs):t?.setItem(Cs,JSON.stringify(e))}catch{}}function Nd(e){if(!Bd(e))return[];const t=nt(e,"id"),i=nt(e,"path"),s=nt(e,"cwd"),o=nt(e,"created"),r=nt(e,"modified"),n=nt(e,"firstMessage"),a=Ud(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=ss(e,"name"),p=ss(e,"parentSessionPath"),u=ss(e,"machineId")??gt;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 zd(e){return Ld in e}function Bd(e){return typeof e=="object"&&e!==null}function nt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ss(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Ud(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Hd(e){return np(e.flatMap(io)).filter(t=>t.parts.length>0)}function Me(e,t){return{role:e,parts:[{type:"text",text:t}]}}function St(e,t){const i=Xd(t);return i===void 0?e:{...e,meta:i}}function qd(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,Me(t,i)]}function Kd(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 io(e){if(Gd(e))return[e];if(O(e,"role")==="bashExecution")return[St(tp(e),e)];const t=ip(O(e,"role")),i=sp(fe(e,"content"),e),s=t==="user"?Jd(i):void 0;if(s!==void 0)return s.map(p=>St(p,e));const o=Zd(e);if(t==="tool")return[St({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?[St({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Vd(e);return c===void 0?a:[...a,St(c,e)]}function Vd(e){if(O(e,"role")!=="assistant"||O(e,"stopReason")!=="error")return;const t=O(e,"errorMessage")?.trim();return Me("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Gd(e){const t=O(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Jd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Qd(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 Qd(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 Zd(e){const t=O(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Xd(e){const t=Yd(fe(e,"timestamp")),i=ep(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Yd(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 ep(e){if(O(e,"role")!=="assistant")return;const t=O(e,"provider"),i=O(e,"model"),s=O(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 tp(e){const t=O(e,"command")??"",i=ni(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",mi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${mi(o)}`),ni(e,"cancelled")===!0&&i.push("","cancelled"),ni(e,"truncated")===!0&&i.push("","output truncated");const r=O(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
@@ -21,7 +21,7 @@ ${o.join(`
|
|
|
21
21
|
`)+1,s=e.slice(i),o=dr(s,"@ "),r=dr(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 dr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Zp(e[i-1]))return i;return-1}function Zp(e){return e===" "||e===" "}function ro(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Yp(e).startsWith("/")?{kind:"command"}:Kn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Xp(e){return ro(e).kind==="shell"}function Yp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
22
22
|
`))+1;return e.slice(t)}class eh{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),Jn(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=wd(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 Gn(t);th(i)&&this.onEvent?.(i)}}class pr{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),Jn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=yd(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 Gn(t);sh(i)&&this.onEvent?.(i)}}function th(e){const t=no(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 ih(e){const t=no(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function sh(e){const t=no(e);return ih(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function no(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Gn(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 Jn(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 oh(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 ao(e){return typeof e=="string"&&e!==""?e:void 0}function oh(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!rh(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 rh(e){return!nh(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 nh(e){return typeof e=="object"&&e!==null}class ah{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 lh="pi-web:session-selection:v1";class ch{constructor(t=Bt()){this.sessionIdsByCwd=new _i(lh,ao,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function dh(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return hh(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 ph(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function hh(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function uh(e,t,i){return Ms(e,[t],i)}function Ms(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function fh(e,t,i){return Es(e,t,[i])}function Es(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 xt=100;class gh{constructor(t,i,s,o=new ah,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new eh,this.api=r.api??z,this.transcripts=r.transcripts??new Gp}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();ph(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=f(this.getState()),s=await this.api.startSession(t.path,i);sr(s,i);const o=Ts(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 dh(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:xt},f(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)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:xt},f(this.getState())),this.api.status(t,f(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(Z(t)&&$h(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:xt},f(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&&Xp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(w=>Vn(w.path,!1)).join(" "),g=t===""?h:`${t}
|
|
23
23
|
|
|
24
|
-
${h}`;await this.api.prompt(a,g,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:Qn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Me("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Me("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,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Me("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,f(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(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=uh(i.sessions,t.id,new Date().toISOString()),o=fh(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||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Ms(o.sessions,s,new Date().toISOString()),n=Es(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=hr(t).filter(n=>n.archived!==!0&&!Z(n));if(i.length===0)return;const s=f(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=ur(o);if(r.length>0){const n=this.getState(),a=Ms(n.sessions,r,new Date().toISOString()),c=Es(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=hr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!_t(o,ht.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=ur(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(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),or(t.id,f(this.getState())),oo(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,f(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||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!_t(s,ht.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,f(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,f(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,f(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,f(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,f(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,f(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,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(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:xt},f(this.getState())),this.api.status(i,f(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=vh(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return jn(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(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=f(this.getState()),o=await this.api.startSession(t.cwd,s);sr(o,s),hp(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),or(t.id,s);const r=Ts(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(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Fd(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,Me(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&bi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Sh(i,t.sessionId,t.messageCount),...s?{sessionActivities:mh(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(xh(t))return}if(kh(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:xt},f(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 mh(e,t){return Qn(e,t)}function Qn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function hr(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 ur(e){return e.filter(bh).map(t=>t.value)}function vh(e){return e.filter(wh).map(t=>yh(t.reason))}function bh(e){return e.status==="fulfilled"}function wh(e){return e.status==="rejected"}function yh(e){return e instanceof Error?e.message:String(e)}function Sh(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 xh(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 kh(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function $h(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ph{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 Rh="pi-web:workspace-selection:v1";class Ih{constructor(t=Bt()){this.workspaceIdsByProject=new _i(Rh,ao,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Ch(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 Th{constructor(t,i,s,o,r=new Ph,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??z}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...ri()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Yi(f(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=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...ri()});try{const o=await this.api.workspaces(t.id,s);if(f(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=Ch(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Yi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Yi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...ri()});try{const o=jd(t.path,await this.api.sessions(t.path,s),s);if(f(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){f(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,f(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=Mh(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 Ah(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Mh(e){return e.find(t=>t.isMain)??e[0]}const Eh="pi-web:machine-navigation:v1";class Dh{constructor(t=Bt()){this.snapshotsByMachine=new _i(Eh,Oh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?mr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,mr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Wh(e){return{machineId:e,surface:{}}}function fr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Ln,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 gr(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 mr(e){return{...e,surface:{...e.surface}}}function Oh(e){if(!Xn(e))return;const t=_e(e,"machineId");if(t===void 0)return;const i=Zn(_e(e,"tool")),s=Lh(_e(e,"view"));return{machineId:t,projectId:_e(e,"projectId"),workspaceId:_e(e,"workspaceId"),sessionId:_e(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:_h(e.surface)}}function _h(e){return Xn(e)?{selectedFilePath:_e(e,"selectedFilePath"),selectedDiffPath:_e(e,"selectedDiffPath"),selectedTerminalId:_e(e,"selectedTerminalId")}:{}}function Lh(e){return e==="navigation"||e==="chat"?e:Zn(e)}function Zn(e){return jh(e)?e:void 0}function jh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _e(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Xn(e){return typeof e=="object"&&e!==null}const Fh="pi-web:terminal-selection:v1";class Nh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(Fh,ao,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 ny(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 ay(e){return e.find(t=>!t.exited)??e[0]}const Yn=1200,zh=["mod","alt","shift"];class Bh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=ta(t);if(o===void 0)return!1;const r=lo(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=>Xh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>co(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},Yn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function lo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Uh(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(Ds)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Kh),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Vh(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,g=u===void 0||h?void 0:vr(u),w=h?[...a.get(p)??[]].sort(Ds).map(vr):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function os(e){return ia(e,{requireFirstChordActivator:!0})}function ea(e){const t=ia(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ai(e){return ea(e).map(t=>t.split("+").map(oa).join("+")).join(" ")}function ta(e){if(e.isComposing)return;const t=Qh(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 Uh(e,t,i){const s=Hh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=ea(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:qh(r),order:i}}function Hh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function qh(e){return e.join("\0")}function vr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Ds(e,t){return br(e.source)-br(t.source)||wr(e.action.id,t.action.id)||wr(e.action.title,t.action.title)||e.order-t.order}function Kh(e,t){return e.tokens.length-t.tokens.length||Ds(e,t)}function Vh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&co(e.tokens,i.tokens))}function br(e){switch(e){case"custom":return 0;case"default":return 1}}function wr(e,t){return e<t?-1:e>t?1:0}function ia(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Gh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Gh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const r of t){const n=Jh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${oa(n)} 修饰键。`};i.add(n);continue}const a=sa(r);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${r}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...zh.filter(r=>i.has(r)),s].join("+")}}function Jh(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 sa(e){const t=Zh(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 Qh(e){if(e===" ")return"space";const t=e.toLowerCase();return sa(t)}function Zh(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 oa(e){return e==="mod"?yr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?yr()?"⌥":"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 Xh(e,t){return e.length===t.length&&co(e,t)}function co(e,t){return t.every((i,s)=>e[s]===i)}function yr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const po="themes:classic",Yh="themes:pi-web-dark",eu={themeId:Yh,auto:!0},ra="pi-web-app-theme",tu=["--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"],iu=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function su(){try{const e=window.localStorage.getItem(ra);return e===null?void 0:lu(e)}catch{return}}function ou(e){try{window.localStorage.setItem(ra,JSON.stringify(e))}catch{}}function ru(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of tu){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function nu(e){const t=au(e.themes,e.fallbackThemeId??po),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=na(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 au(e,t=po){return e.find(i=>i.id===t)??e[0]}function na(e,t){return e.find(i=>i.light===t||i.dark===t)}function lu(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return cu(i)?i:void 0}catch{return}}function cu(e){if(!du(e))return!1;const t=e.themeId,i=e.auto;return pu(t)&&typeof i=="boolean"}function du(e){return typeof e=="object"&&e!==null}function pu(e){return typeof e=="string"&&iu.test(e)}const hu="management";function uu(e){return fu(gu())===hu}function fu(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function gu(){return typeof window>"u"?void 0:window.location.search}const mu="workspace.delete",vu="pi.operation",bu="target.workspaceId";function wu(e){return{...e===void 0?{}:{projectId:e},metadata:{[vu]:mu}}}function yu(e){const t={};for(const i of e){const s=Ws(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 Su(e){return Object.entries(e).filter(([,t])=>xi(t)).map(([t])=>t)}function aa(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&xi(i)}function Ws(e){return e.metadata[bu]}function xi(e){return e.status==="queued"||e.status==="running"}function Sr(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:xr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:kt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:xr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:kt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:xu,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:kt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:ku,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Pu,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:$u,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function kt(e){return e.state.selectedWorkspace!==void 0}function xr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function xu(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!aa(e.state,t)}function ku(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function $u(e){return Z(e.state.selectedSession)}function Pu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||Z(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!_t(i,ht.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const Ru="modulepreload",Iu=function(e){return"/"+e},kr={},la=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 kr)return;kr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":Ru,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((w,P)=>{g.addEventListener("load",w),g.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)})},Cu=10*1024*1024,Tu="10 MB";function Au(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:li(e)}function li(e){switch(e){case"navigation":return he`
|
|
24
|
+
${h}`;await this.api.prompt(a,g,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:Qn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Me("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Me("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,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Me("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,f(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(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=uh(i.sessions,t.id,new Date().toISOString()),o=fh(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||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Ms(o.sessions,s,new Date().toISOString()),n=Es(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=hr(t).filter(n=>n.archived!==!0&&!Z(n));if(i.length===0)return;const s=f(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=ur(o);if(r.length>0){const n=this.getState(),a=Ms(n.sessions,r,new Date().toISOString()),c=Es(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=hr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!_t(o,ht.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=ur(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(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),or(t.id,f(this.getState())),oo(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,f(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||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!_t(s,ht.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,f(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,f(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,f(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,f(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,f(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,f(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,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(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:xt},f(this.getState())),this.api.status(i,f(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=vh(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return jn(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(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=f(this.getState()),o=await this.api.startSession(t.cwd,s);sr(o,s),hp(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),or(t.id,s);const r=Ts(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(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Fd(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,Me(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&bi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Sh(i,t.sessionId,t.messageCount),...s?{sessionActivities:mh(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(xh(t))return}if(kh(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:xt},f(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 mh(e,t){return Qn(e,t)}function Qn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function hr(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 ur(e){return e.filter(bh).map(t=>t.value)}function vh(e){return e.filter(wh).map(t=>yh(t.reason))}function bh(e){return e.status==="fulfilled"}function wh(e){return e.status==="rejected"}function yh(e){return e instanceof Error?e.message:String(e)}function Sh(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 xh(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 kh(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function $h(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class Ph{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 Rh="pi-web:workspace-selection:v1";class Ih{constructor(t=Bt()){this.workspaceIdsByProject=new _i(Rh,ao,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Ch(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 Th{constructor(t,i,s,o,r=new Ph,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??z}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...ri()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Yi(f(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=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...ri()});try{const o=await this.api.workspaces(t.id,s);if(f(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=Ch(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Yi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Yi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...ri()});try{const o=jd(t.path,await this.api.sessions(t.path,s),s);if(f(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){f(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,f(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=Mh(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 Ah(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Mh(e){return e.find(t=>t.isMain)??e[0]}const Eh="pi-web:machine-navigation:v1";class Dh{constructor(t=Bt()){this.snapshotsByMachine=new _i(Eh,Oh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?mr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,mr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Wh(e){return{machineId:e,surface:{}}}function fr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Ln,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 gr(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 mr(e){return{...e,surface:{...e.surface}}}function Oh(e){if(!Xn(e))return;const t=_e(e,"machineId");if(t===void 0)return;const i=Zn(_e(e,"tool")),s=Lh(_e(e,"view"));return{machineId:t,projectId:_e(e,"projectId"),workspaceId:_e(e,"workspaceId"),sessionId:_e(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:_h(e.surface)}}function _h(e){return Xn(e)?{selectedFilePath:_e(e,"selectedFilePath"),selectedDiffPath:_e(e,"selectedDiffPath"),selectedTerminalId:_e(e,"selectedTerminalId")}:{}}function Lh(e){return e==="navigation"||e==="chat"?e:Zn(e)}function Zn(e){return jh(e)?e:void 0}function jh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _e(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Xn(e){return typeof e=="object"&&e!==null}const Fh="pi-web:terminal-selection:v1";class Nh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(Fh,ao,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 ny(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 ay(e){return e.find(t=>!t.exited)??e[0]}const Yn=1200,zh=["mod","alt","shift"];class Bh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=ta(t);if(o===void 0)return!1;const r=lo(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=>Xh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>co(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},Yn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function lo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Uh(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(Ds)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Kh),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Vh(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,g=u===void 0||h?void 0:vr(u),w=h?[...a.get(p)??[]].sort(Ds).map(vr):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function os(e){return ia(e,{requireFirstChordActivator:!0})}function ea(e){const t=ia(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ai(e){return ea(e).map(t=>t.split("+").map(oa).join("+")).join(" ")}function ta(e){if(e.isComposing)return;const t=Qh(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 Uh(e,t,i){const s=Hh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=ea(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:qh(r),order:i}}function Hh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function qh(e){return e.join("\0")}function vr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Ds(e,t){return br(e.source)-br(t.source)||wr(e.action.id,t.action.id)||wr(e.action.title,t.action.title)||e.order-t.order}function Kh(e,t){return e.tokens.length-t.tokens.length||Ds(e,t)}function Vh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&co(e.tokens,i.tokens))}function br(e){switch(e){case"custom":return 0;case"default":return 1}}function wr(e,t){return e<t?-1:e>t?1:0}function ia(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Gh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Gh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const r of t){const n=Jh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${oa(n)} 修饰键。`};i.add(n);continue}const a=sa(r);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${r}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...zh.filter(r=>i.has(r)),s].join("+")}}function Jh(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 sa(e){const t=Zh(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 Qh(e){if(e===" ")return"space";const t=e.toLowerCase();return sa(t)}function Zh(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 oa(e){return e==="mod"?yr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?yr()?"⌥":"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 Xh(e,t){return e.length===t.length&&co(e,t)}function co(e,t){return t.every((i,s)=>e[s]===i)}function yr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const po="themes:classic",Yh="themes:pi-web-dark",eu={themeId:Yh,auto:!0},ra="pi-web-app-theme",tu=["--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"],iu=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function su(){try{const e=window.localStorage.getItem(ra);return e===null?void 0:lu(e)}catch{return}}function ou(e){try{window.localStorage.setItem(ra,JSON.stringify(e))}catch{}}function ru(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of tu){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function nu(e){const t=au(e.themes,e.fallbackThemeId??po),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=na(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 au(e,t=po){return e.find(i=>i.id===t)??e[0]}function na(e,t){return e.find(i=>i.light===t||i.dark===t)}function lu(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return cu(i)?i:void 0}catch{return}}function cu(e){if(!du(e))return!1;const t=e.themeId,i=e.auto;return pu(t)&&typeof i=="boolean"}function du(e){return typeof e=="object"&&e!==null}function pu(e){return typeof e=="string"&&iu.test(e)}const hu="management";function uu(e){return fu(gu())===hu}function fu(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function gu(){return typeof window>"u"?void 0:window.location.search}const mu="workspace.delete",vu="pi.operation",bu="target.workspaceId";function wu(e){return{...e===void 0?{}:{projectId:e},metadata:{[vu]:mu}}}function yu(e){const t={};for(const i of e){const s=Ws(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 Su(e){return Object.entries(e).filter(([,t])=>xi(t)).map(([t])=>t)}function aa(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&xi(i)}function Ws(e){return e.metadata[bu]}function xi(e){return e.status==="queued"||e.status==="running"}function Sr(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:xr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:kt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:xr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:kt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:xu,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:kt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:ku,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Pu,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:$u,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function kt(e){return e.state.selectedWorkspace!==void 0}function xr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function xu(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!aa(e.state,t)}function ku(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function $u(e){return Z(e.state.selectedSession)}function Pu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||Z(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!_t(i,ht.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const Ru="modulepreload",Iu=function(e){return"/"+e},kr={},la=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 kr)return;kr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":Ru,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((w,P)=>{g.addEventListener("load",w),g.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)})},Cu=10*1024*1024,Tu="10 MB";function Au(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:li(e)}function li(e){switch(e){case"navigation":return he`
|
|
25
25
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
26
26
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
27
27
|
<path d="M10 7h8"></path>
|
|
@@ -132,7 +132,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
|
|
|
132
132
|
<div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
|
|
133
133
|
<code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
|
|
134
134
|
</section>
|
|
135
|
-
`}function pa(){la(()=>import("./CodeViewer-B1z_k75G.js"),__vite__mapDeps([0,1,2,3]))}function Ku(){la(()=>import("./TerminalPanel-CqG27wd5.js"),__vite__mapDeps([4,5,6,1,2]))}function Vu(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Gu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Os(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`${rs(t)} KB`;const i=t/1024;return i<1024?`${rs(i)} MB`:`${rs(i/1024)} GB`}function rs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Ju={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!uu();return{contributions:{actions:e?Sr():Sr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?$r():$r().filter(t=>t.id!=="workspace.terminal")}}}},Qu={"--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"},Zu={"--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"},Xu={"--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"},Yu={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Zu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Xu},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Qu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ef=/^[a-z][a-z0-9.-]*$/u;function tf(e){return ef.test(e)}const sf="machine.";function of(e,t){if(e==="")throw new Error("Machine id is required");if(!tf(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${sf}${rf(e)}.${t}`}function rf(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Pr(e="/pi-web-plugins/manifest.json",t={}){const i=await nf(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=cf(n,r);s.push({id:t.machineId===void 0?o.id:of(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 nf(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 af(await t.json())}}function af(e){if(!ki(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ki(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:lf(t.machineSpecific)}})}}function lf(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function cf(e,t){if(!ki(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!df(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function df(e){return ki(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ki(e){return typeof e=="object"&&e!==null}const pf=/^[a-z][a-z0-9.-]*$/u,hf=/^[a-z][a-z0-9.-]*$/u,ha=new WeakMap,ua=new WeakMap;class uf{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&&vf(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=ff(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?.(ns(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(ns(c,t)):void 0},render:c=>i.render(ns(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(!pf.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!hf.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}: ${bf(i)}`);return i}}function ff(e,t){return ha.get(e)?.(t)??e}function ns(e,t){return ua.get(e)?.(t)??e}function gf(e,t){return ha.set(e,t),e}function mf(e,t){return ua.set(e,t),e}function vf(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bf(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 wf(e){return e.state.selectedMachine?.id??"local"}const yf=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Sf(){return typeof window>"u"||!("matchMedia"in window)?[]:yf.map(e=>window.matchMedia(e))}function Rr(e,t=xf()){return e.some(i=>i.matches)||kf(t)}function xf(){return typeof navigator>"u"?void 0:navigator}function kf(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $f=250;class Pf{constructor(t=Rf()){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()},$f)}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 Rf(){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 If="(max-width: 760px)",Cf="(max-width: 1180px)";class Tf{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Rr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Af(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Mf(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Sf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Rr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);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.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Ef(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Af(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(If)}function Mf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Cf)}function Ef(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const $i=["machines","projects","workspaces","sessions"];function Df(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function ho(e,t){if(e!=="none")return e??Df(t)}function Wf(e,t){return t.isMobileLayout?ho(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Of(e,t,i){return ho(e,i.state)===t?"none":t}function _f(e,t,i){return i?t:e}function Lf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Nf(i)}function jf(e){return $i[$i.indexOf(e)+1]}class Ff{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return ho(this.expanded,this.getState())}isCollapsed(t){return Wf(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Of(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Lf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(_f(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=jf(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){zf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Nf(e){const t=new Set(e);return $i.filter(i=>t.has(i))}function zf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Bf{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",fa(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function fa(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const _s="pi-web:panel-sizes:v1",Uf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Hf{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??uo(),this.panelSizes=Gf(this.storage)}hostConnected(){}constraints(t){return Ht(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=Zf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Xf(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(){Jf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Cr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Cr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ht(e){return Uf[e]}function qf(e,t,i){return e==="navigation"?i-t:t-i}function Kf(e,t,i,s,o=Ht(e)){return ue(e,t+qf(e,i,s),o)}function Vf(e,t,i,s={}){const o=s.constraints??Ht(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Yf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ht(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Gf(e=uo()){try{const t=e?.getItem(_s);if(t==null||t==="")return{};const i=JSON.parse(t);return Qf(i)}catch{return{}}}function Jf(e,t=uo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(_s);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(_s,JSON.stringify(i))}catch{}}function Qf(e){if(!eg(e)||e.version!==1)return{};const t={},i=Ir(e.navigationPanelWidth),s=Ir(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function Ir(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Zf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Xf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Yf(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 Cr(e){return`${String(Math.round(e))}px`}function uo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function eg(e){return typeof e=="object"&&e!==null}function Tr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:tg(e.get("tool")),view:ig(e.get("view"))}}function as(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 tg(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ig(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ga(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ar(){return sg(new URLSearchParams(window.location.search).get("settings"))}function ls(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 sg(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 og(e,t){return t===void 0?e:e.map(i=>ng(i,t))}function rg(e,t){const i=new Set(lo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return og(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ma(s):s)}function ng(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ma(e):{...e,shortcut:i}}function ma(e){const t={...e};return delete t.shortcut,t}function ag(e,t){const i=t.api??dt,s=t.pollIntervalMs??1e3,o=t.setTimeout??cg(),r=t.clearTimeout??dg();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:lg(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function lg(e,t,i,s,o){return Mr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&o(a),r(g))},u=g=>{c||(c=!0,a!==void 0&&o(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mr(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mr(e){return e.status==="succeeded"||e.status==="failed"}function cg(){return(e,t)=>globalThis.setTimeout(e,t)}function dg(){return e=>{globalThis.clearTimeout(e)}}function pg(e,t){return t[e.path]}function hg(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function ug(e,t,i){return ba(fg(e,t,i))}function va(e){return ba(Object.values(e??{}))}function ba(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function fg(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()]}function wa(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Li(e,t="活跃"){const i=wa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Zt=0,gg=120;function ya(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Sa():mg(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,g=i.top-c-Zt;return[...h<gg&&g>h?[`bottom: ${at(r-i.top+Zt)};`,`max-height: ${at(Math.max(0,g))};`]:[`top: ${at(i.bottom+Zt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,o-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function mg(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 at(e){return`${String(Math.round(e))}px`}class ji{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=ya(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const vg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function xa(e){return e.composedPath().some(t=>bg(t,vg))}function bg(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 Fi(e,t){xa(e)||t()}function Ni(e,t){return xa(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Er(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Er(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{Dr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{Dr(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 zi(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 Er(e,t){const i=$a(e),s=Pa(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||ka(i,o+t)}function Dr(e,t){const i=$a(e);i.length!==0&&ka(i,t<0?i.length-1:t)}function ka(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function $a(e){const t=Pa(e)?.getRootNode();return t===void 0||!wg(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function wg(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Pa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Bi=D`
|
|
135
|
+
`}function pa(){la(()=>import("./CodeViewer-DA68s2LY.js"),__vite__mapDeps([0,1,2,3]))}function Ku(){la(()=>import("./TerminalPanel-DR8I9BBO.js"),__vite__mapDeps([4,5,6,1,2]))}function Vu(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Gu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Os(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`${rs(t)} KB`;const i=t/1024;return i<1024?`${rs(i)} MB`:`${rs(i/1024)} GB`}function rs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Ju={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!uu();return{contributions:{actions:e?Sr():Sr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?$r():$r().filter(t=>t.id!=="workspace.terminal")}}}},Qu={"--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"},Zu={"--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"},Xu={"--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"},Yu={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Zu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Xu},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Qu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ef=/^[a-z][a-z0-9.-]*$/u;function tf(e){return ef.test(e)}const sf="machine.";function of(e,t){if(e==="")throw new Error("Machine id is required");if(!tf(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${sf}${rf(e)}.${t}`}function rf(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Pr(e="/pi-web-plugins/manifest.json",t={}){const i=await nf(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=cf(n,r);s.push({id:t.machineId===void 0?o.id:of(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 nf(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 af(await t.json())}}function af(e){if(!ki(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ki(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:lf(t.machineSpecific)}})}}function lf(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function cf(e,t){if(!ki(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!df(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function df(e){return ki(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ki(e){return typeof e=="object"&&e!==null}const pf=/^[a-z][a-z0-9.-]*$/u,hf=/^[a-z][a-z0-9.-]*$/u,ha=new WeakMap,ua=new WeakMap;class uf{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&&vf(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=ff(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?.(ns(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(ns(c,t)):void 0},render:c=>i.render(ns(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(!pf.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!hf.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}: ${bf(i)}`);return i}}function ff(e,t){return ha.get(e)?.(t)??e}function ns(e,t){return ua.get(e)?.(t)??e}function gf(e,t){return ha.set(e,t),e}function mf(e,t){return ua.set(e,t),e}function vf(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bf(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 wf(e){return e.state.selectedMachine?.id??"local"}const yf=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Sf(){return typeof window>"u"||!("matchMedia"in window)?[]:yf.map(e=>window.matchMedia(e))}function Rr(e,t=xf()){return e.some(i=>i.matches)||kf(t)}function xf(){return typeof navigator>"u"?void 0:navigator}function kf(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $f=250;class Pf{constructor(t=Rf()){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()},$f)}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 Rf(){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 If="(max-width: 760px)",Cf="(max-width: 1180px)";class Tf{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Rr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Af(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Mf(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Sf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Rr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);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.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Ef(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Af(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(If)}function Mf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Cf)}function Ef(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const $i=["machines","projects","workspaces","sessions"];function Df(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function ho(e,t){if(e!=="none")return e??Df(t)}function Wf(e,t){return t.isMobileLayout?ho(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Of(e,t,i){return ho(e,i.state)===t?"none":t}function _f(e,t,i){return i?t:e}function Lf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Nf(i)}function jf(e){return $i[$i.indexOf(e)+1]}class Ff{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return ho(this.expanded,this.getState())}isCollapsed(t){return Wf(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Of(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Lf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(_f(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=jf(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){zf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Nf(e){const t=new Set(e);return $i.filter(i=>t.has(i))}function zf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Bf{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",fa(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function fa(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const _s="pi-web:panel-sizes:v1",Uf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Hf{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??uo(),this.panelSizes=Gf(this.storage)}hostConnected(){}constraints(t){return Ht(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=Zf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Xf(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(){Jf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Cr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Cr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ht(e){return Uf[e]}function qf(e,t,i){return e==="navigation"?i-t:t-i}function Kf(e,t,i,s,o=Ht(e)){return ue(e,t+qf(e,i,s),o)}function Vf(e,t,i,s={}){const o=s.constraints??Ht(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Yf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ht(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Gf(e=uo()){try{const t=e?.getItem(_s);if(t==null||t==="")return{};const i=JSON.parse(t);return Qf(i)}catch{return{}}}function Jf(e,t=uo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(_s);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(_s,JSON.stringify(i))}catch{}}function Qf(e){if(!eg(e)||e.version!==1)return{};const t={},i=Ir(e.navigationPanelWidth),s=Ir(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function Ir(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Zf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Xf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Yf(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 Cr(e){return`${String(Math.round(e))}px`}function uo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function eg(e){return typeof e=="object"&&e!==null}function Tr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:tg(e.get("tool")),view:ig(e.get("view"))}}function as(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 tg(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ig(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ga(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ar(){return sg(new URLSearchParams(window.location.search).get("settings"))}function ls(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 sg(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 og(e,t){return t===void 0?e:e.map(i=>ng(i,t))}function rg(e,t){const i=new Set(lo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return og(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ma(s):s)}function ng(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ma(e):{...e,shortcut:i}}function ma(e){const t={...e};return delete t.shortcut,t}function ag(e,t){const i=t.api??dt,s=t.pollIntervalMs??1e3,o=t.setTimeout??cg(),r=t.clearTimeout??dg();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:lg(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function lg(e,t,i,s,o){return Mr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&o(a),r(g))},u=g=>{c||(c=!0,a!==void 0&&o(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mr(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mr(e){return e.status==="succeeded"||e.status==="failed"}function cg(){return(e,t)=>globalThis.setTimeout(e,t)}function dg(){return e=>{globalThis.clearTimeout(e)}}function pg(e,t){return t[e.path]}function hg(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function ug(e,t,i){return ba(fg(e,t,i))}function va(e){return ba(Object.values(e??{}))}function ba(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function fg(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()]}function wa(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Li(e,t="活跃"){const i=wa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Zt=0,gg=120;function ya(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Sa():mg(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,g=i.top-c-Zt;return[...h<gg&&g>h?[`bottom: ${at(r-i.top+Zt)};`,`max-height: ${at(Math.max(0,g))};`]:[`top: ${at(i.bottom+Zt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,o-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function mg(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 at(e){return`${String(Math.round(e))}px`}class ji{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=ya(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const vg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function xa(e){return e.composedPath().some(t=>bg(t,vg))}function bg(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 Fi(e,t){xa(e)||t()}function Ni(e,t){return xa(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Er(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Er(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{Dr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{Dr(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 zi(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 Er(e,t){const i=$a(e),s=Pa(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||ka(i,o+t)}function Dr(e,t){const i=$a(e);i.length!==0&&ka(i,t<0?i.length-1:t)}function ka(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function $a(e){const t=Pa(e)?.getRootNode();return t===void 0||!wg(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function wg(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Pa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Bi=D`
|
|
136
136
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
137
137
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
138
138
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|