@chainingintention/pi-web-cn 1.202608.4 → 1.202608.5

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-CWHRo84w.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-CoYwbZrx.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BUT2Idcq.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-b8CZY7en.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>i.map(i=>d[i]);
2
2
  import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var re=globalThis,ie=re.ShadowRoot&&(re.ShadyCSS===void 0||re.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,ae=Symbol(),oe=new WeakMap,se=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==ae)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(ie&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=oe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&oe.set(t,e))}return e}toString(){return this.cssText}},ce=e=>new se(typeof e==`string`?e:e+``,void 0,ae),h=(e,...t)=>new se(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,ae),le=(e,t)=>{if(ie)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=re.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ue=ie?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return ce(t)})(e):e,{is:de,defineProperty:fe,getOwnPropertyDescriptor:pe,getOwnPropertyNames:me,getOwnPropertySymbols:he,getPrototypeOf:ge}=Object,_e=globalThis,ve=_e.trustedTypes,ye=ve?ve.emptyScript:``,be=_e.reactiveElementPolyfillSupport,xe=(e,t)=>e,Se={toAttribute(e,t){switch(t){case Boolean:e=e?ye:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Ce=(e,t)=>!de(e,t),we={attribute:!0,type:String,converter:Se,reflect:!1,useDefault:!1,hasChanged:Ce};Symbol.metadata??=Symbol(`metadata`),_e.litPropertyMetadata??=new WeakMap;var Te=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=we){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&fe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=pe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(xe(`elementProperties`)))return;let e=ge(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(xe(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(xe(`properties`))){let e=this.properties,t=[...me(e),...he(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(ue(e))}else e!==void 0&&t.push(ue(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return le(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Se:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Se:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??Ce)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};Te.elementStyles=[],Te.shadowRootOptions={mode:`open`},Te[xe(`elementProperties`)]=new Map,Te[xe(`finalized`)]=new Map,be?.({ReactiveElement:Te}),(_e.reactiveElementVersions??=[]).push(`2.1.2`);var Ee=globalThis,De=e=>e,Oe=Ee.trustedTypes,ke=Oe?Oe.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Ae=`$lit$`,je=`lit$${Math.random().toFixed(9).slice(2)}$`,Me=`?`+je,Ne=`<${Me}>`,Pe=document,Fe=()=>Pe.createComment(``),Ie=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Le=Array.isArray,Re=e=>Le(e)||typeof e?.[Symbol.iterator]==`function`,ze=`[
3
3
  \f\r]`,Be=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ve=/-->/g,He=/>/g,Ue=RegExp(`>|${ze}(?:([^\\s"'>=/]+)(${ze}*=${ze}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),We=/'/g,Ge=/"/g,Ke=/^(?:script|style|textarea|title)$/i,qe=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=qe(1),Je=qe(2),Ye=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Xe=new WeakMap,Ze=Pe.createTreeWalker(Pe,129);function Qe(e,t){if(!Le(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return ke===void 0?t:ke.createHTML(t)}var $e=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Be;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Be?c[1]===`!--`?o=Ve:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ue):(Ke.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ue):o=He:o===Ue?c[0]===`>`?(o=i??Be,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ue:c[3]===`"`?Ge:We):o===Ge||o===We?o=Ue:o===Ve||o===He?o=Be:(o=Ue,i=void 0);let d=o===Ue&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Be?n+Ne:l>=0?(r.push(s),n.slice(0,l)+Ae+n.slice(l)+je+d):n+je+(l===-2?t:d)}return[Qe(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},et=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=$e(t,n);if(this.el=e.createElement(l,r),Ze.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Ze.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Ae)){let t=u[o++],n=i.getAttribute(e).split(je),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?at:r[1]===`?`?ot:r[1]===`@`?st:it}),i.removeAttribute(e)}else e.startsWith(je)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ke.test(i.tagName)){let e=i.textContent.split(je),t=e.length-1;if(t>0){i.textContent=Oe?Oe.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Fe()),Ze.nextNode(),c.push({type:2,index:++a});i.append(e[t],Fe())}}}else if(i.nodeType===8)if(i.data===Me)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(je,e+1))!==-1;)c.push({type:7,index:a}),e+=je.length-1}a++}}static createElement(e,t){let n=Pe.createElement(`template`);return n.innerHTML=e,n}};function tt(e,t,n=e,r){if(t===Ye)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Ie(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=tt(e,i._$AS(e,t.values),i,r)),t}var nt=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Pe).importNode(t,!0);Ze.currentNode=r;let i=Ze.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new rt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ct(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Ze.nextNode(),a++)}return Ze.currentNode=Pe,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},rt=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=tt(this,e,t),Ie(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Ye&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Re(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==_&&Ie(this._$AH)?this._$AA.nextSibling.data=e:this.T(Pe.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=et.createElement(Qe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new nt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Xe.get(e.strings);return t===void 0&&Xe.set(e.strings,t=new et(e)),t}k(t){Le(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Fe()),this.O(Fe()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=De(e).nextSibling;De(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},it=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=_,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=_}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=tt(this,e,t,0),a=!Ie(e)||e!==this._$AH&&e!==Ye,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=tt(this,r[n+o],t,o),s===Ye&&(s=this._$AH[o]),a||=!Ie(s)||s!==this._$AH[o],s===_?e=_:e!==_&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},at=class extends it{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},ot=class extends it{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},st=class extends it{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=tt(this,e,t,0)??_)===Ye)return;let n=this._$AH,r=e===_&&n!==_||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==_&&(n===_||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ct=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){tt(this,e)}},lt={M:Ae,P:je,A:Me,C:1,L:$e,R:nt,D:Re,V:tt,I:rt,H:it,N:ot,U:st,B:at,F:ct},ut=Ee.litHtmlPolyfillSupport;ut?.(et,rt),(Ee.litHtmlVersions??=[]).push(`3.3.3`);var dt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new rt(t.insertBefore(Fe(),e),e,void 0,n??{})}return i._$AI(e),i},ft=globalThis,v=class extends Te{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=dt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ye}};v._$litElement$=!0,v.finalized=!0,ft.litElementHydrateSupport?.({LitElement:v});var pt=ft.litElementPolyfillSupport;pt?.({LitElement:v}),(ft.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},mt={attribute:!0,type:String,converter:Se,reflect:!1,hasChanged:Ce},ht=(e=mt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function b(e){return(t,n)=>typeof n==`object`?ht(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function x(e){return b({...e,state:!0,attribute:!1})}var gt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function S(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return gt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return gt(n,r,{get(){return a(this)}})}}var _t=`management`;function vt(e=Et()){return Tt(e)===_t}function yt(e=Dt()){return vt(e?.search)?`management`:`normal`}function bt(e,t=Dt(),n=`management`){return Ct(e,t,n,!0)}function xt(e,t=Dt(),n=`management`){return Ct(e,t,n,!1)}function St(e){if(e!==`management`||globalThis.history===void 0)return;let t=Dt();t===void 0||wt(t)?.token===void 0||(t.searchParams.delete(`token`),globalThis.history.replaceState(globalThis.history.state,``,`${t.pathname}${t.search}${t.hash}`))}function Ct(e,t,n,r){if(n===`normal`||t===void 0)return e;let i=wt(t);if(i===void 0)return e;let a=new URL(e,t.origin);return a.searchParams.set(`embed`,i.embed),i.token!==void 0&&a.searchParams.set(`token`,i.token),`${a.pathname}${a.search}${r?a.hash:``}`}function wt(e){if(e===void 0)return;let t=Tt(e.search),n=e.searchParams.get(`token`)?.trim();if(t===_t)return{embed:t,...n===void 0||n===``?{}:{token:n}}}function Tt(e){if(e===void 0||e===``)return;let t=new URLSearchParams(e).get(`embed`)?.trim();return t===``?void 0:t}function Et(){return typeof window>`u`?void 0:window.location.search}function Dt(){if(globalThis.location===void 0)return;let e=globalThis.location;if(typeof e.href==`string`&&e.href!==``)return new URL(e.href);let t=typeof e.protocol==`string`&&e.protocol!==``?e.protocol:`http:`,n=typeof e.host==`string`&&e.host!==``?e.host:`localhost`,r=typeof e.search==`string`?e.search:``;return new URL(`${t}//${n}/${r}`)}function Ot(e,t=At()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(jt(e),n).toString()}function kt(e,t=At()){let n=new URL(Ot(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function At(){return{viteBaseUrl:`./`,documentBaseUrl:typeof document>`u`?`http://localhost/`:document.baseURI}}function jt(e){return e.startsWith(`/`)?`.${e}`:e}var Mt=yt();function Nt(e){Mt=e}function Pt(e){return Ot(bt(e,void 0,Mt))}async function C(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(Pt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(It(e)??i.statusText)}return St(Mt),t(await i.json())}async function Ft(e,t){let n=await fetch(Pt(e));if(n.status===204){St(Mt);return}if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(It(e)??n.statusText)}return St(Mt),t(await n.json())}}function It(e){if(Lt(e))return typeof e.error==`string`?e.error:void 0}function Lt(e){return typeof e==`object`&&!!e}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,sessionsAskUser:`sessions.askUser`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`},Rt=1e3,zt=32*1024,Bt=8*1024,Vt=1e3,Ht=4e3;function Ut(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Wt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Ut(e)}var Gt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Kt=/^sha256:[0-9a-f]{64}$/u,qt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Jt=new Set([`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Yt(e){if(!en(e)||Object.keys(e).some(e=>!Gt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Kt.test(n))&&!(typeof r!=`string`||!Xt(r))&&!(typeof i!=`string`||!Zt(i))&&$t(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEB_AGENT_SESSION_DIR`||a.some(e=>!Jt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Xt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Zt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):qt.test(e)}function Zt(e){if(e===``||e!==e.trim()||Qt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Qt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function $t(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function en(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var tn=Object.values(w),nn=new Set(tn);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig;function rn(e){return typeof e==`string`&&nn.has(e)}function T(e,t){return e?.capabilities?.includes(t)===!0}function an(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(rn)}function on(e){return typeof e==`object`&&!!e}function E(e){if(!on(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function sn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function cn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function ln(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:sn(t.messages),start:k(t,`start`),total:k(t,`total`)}}function un(e){let t=E(e);return j(dn)(t.machines)}function dn(e){let t=E(e),n=mn(t,`kind`),r=O(t,`baseUrl`),i=hn(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function fn(e){let t=E(e),n=hn(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Wi(t.web)},...t.sessiond===void 0?{}:{sessiond:Wi(t.sessiond)},...r===void 0?{}:{error:r}}}function pn(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...M(`packageName`,O(t,`packageName`)),...M(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:Hi(t.components)},...t.capabilities===void 0?{}:{capabilities:Xi(t.capabilities)},...n===void 0?{}:{error:n}}}function mn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function hn(e,t){let n=O(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function gn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function _n(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...M(`effectiveConfig`,vn(t.effectiveConfig))}}function vn(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...M(`uploads`,Si(e.uploads))}}}function yn(e){let t=E(e),n=O(t,`name`),r=Li(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`parentSessionCwd`),o=O(t,`parentSessionId`),s=Ri(t.childSessionsElsewhere,`childSessionsElsewhere`),c=O(t,`archivedAt`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...a===void 0?{}:{parentSessionCwd:a},...o===void 0?{}:{parentSessionId:o},...s===void 0?{}:{childSessionsElsewhere:s},...t.archived===!0?{archived:!0}:{},...c===void 0?{}:{archivedAt:c}}}function bn(e){let t=E(e);return{configured:A(t,`configured`),authenticated:A(t,`authenticated`)}}function xn(e){return{path:D(E(e),`path`)}}function Sn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0,path:D(t,`path`)}}function Cn(e){return{sessionIds:cn(E(e).sessionIds,`sessionIds`)}}function wn(e){return{pinned:A(E(e),`pinned`)}}function Tn(e){let t=E(e);return{results:j(En)(t.results),matchCount:k(t,`matchCount`),truncated:A(t,`truncated`)}}function En(e){let t=E(e);return{session:yn(t.session),matches:j(Dn)(t.matches)}}function Dn(e){let t=E(e),n=D(t,`role`);if(n!==`user`&&n!==`assistant`)throw Error(`Invalid session content search role`);return{messageIndex:k(t,`messageIndex`),role:n,excerpts:j(On)(t.excerpts),occurrenceCount:k(t,`occurrenceCount`)}}function On(e){let t=E(e);return{text:D(t,`text`),matchRanges:j(e=>{let t=E(e);return{start:k(t,`start`),length:k(t,`length`)}})(t.matchRanges)}}function kn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function An(e){if(e!==void 0)return{id:D(E(e),`id`)}}function jn(e){let t=E(e),n=An(t.dismiss);return{severity:kn(t.severity),message:D(t,`message`),...M(`source`,O(t,`source`)),...M(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Mn(e){return e===void 0?{}:{warnings:j(jn)(e)}}function Nn(e){let t=E(e);return{value:tr(t,`value`,128),label:tr(t,`label`,Vt),...M(`detail`,nr(t,`detail`,Vt))}}function Pn(e){let t=E(e),n=pr(t.options,Nn,12,`options`);Un(n.map(e=>e.value),`ask option value`),Li(t.allowOther,`allowOther`);let r=Li(t.multiple,`multiple`);return{id:tr(t,`id`,128),question:tr(t,`question`,Vt),...M(`detail`,nr(t,`detail`,Vt)),options:n,allowOther:!0,...r===void 0?{}:{multiple:r}}}function Fn(e){let t=E(e),n=pr(t.questions,Pn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Un(n.map(e=>e.id),`ask question id`),{askId:tr(t,`askId`,128),askedAt:hr(t,`askedAt`),questions:n}}function In(e){return e===void 0?{}:{pendingAsk:Fn(e)}}function Ln(e){let t=E(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:Fn(t.ask)}}function Rn(e){let t=E(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:tr(t,`askId`,128),reason:zn(t.reason)}}function zn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Bn(e){let t=E(e),n=Pn(t.question),r=pr(t.values,mr,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=nr(t,`otherText`,Ht),o=A(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function Vn(e){let t=E(e),n=pr(t.questions,Bn,20,`questions`),r=gr(t,`answeredCount`),i=cn(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:tr(t,`askId`,128),reason:zn(t.reason),askedAt:hr(t,`askedAt`),closedAt:hr(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:hr(t,`summary`)}}function Hn(e){let t=E(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:Vn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Wn(t.sessionStatus)}}function Un(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Wn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...M(`persisted`,Li(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(kr)(t.queuedMessages),...M(`messageCount`,xa(t,`messageCount`)),tokens:Ar(t.tokens),cost:k(t,`cost`),...Mr(t.model),...Xr(t.contextUsage),...M(`thinkingLevel`,O(t,`thinkingLevel`)),...Mn(t.warnings),...In(t.pendingAsk)}}function Gn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function Kn(e){let t=E(e),n=gr(t,`catalogRevision`),r=pr(t.sessions,Qn,Rt,`sessions`);if($n(r),er(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:tr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function qn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=tr(t,`sessionId`,512),r=tr(t,`cwd`,zt),i=rr(t,`catalogRevision`),a=t.unread===null?null:Qn(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:tr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Jn(e){let t=E(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=O(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:Yn(t.activity)}}function Yn(e){let t=E(e);return{sessionId:hr(t,`sessionId`),phase:Zn(t,`phase`),label:hr(t,`label`),...M(`detail`,O(t,`detail`)),at:hr(t,`at`),...M(`startup`,Xn(t))}}function Xn(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function Zn(e,t){let n=D(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function Qn(e){let t=E(e),n=tr(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:tr(t,`sessionId`,512),cwd:tr(t,`cwd`,zt),completionOrder:rr(t,`completionOrder`),completedAt:n}}function $n(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function er(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function tr(e,t,n){let r=hr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function nr(e,t,n){let r=O(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function rr(e,t){let n=gr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function ir(e){let t=E(e),n=or(t.summary),r=pr(t.notifications,sr,100,`notifications`);if(_r(r),vr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==br(r))throw Error(`Notification snapshot severity mismatch`);let i=cr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:hr(t,`daemonInstanceId`),catalogRevision:gr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function ar(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=or(t.summary),r=cr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=lr(t.delta);if(i.kind===`cleared`&&!yr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:hr(t,`daemonInstanceId`),catalogRevision:gr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function or(e){let t=E(e),n=gr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=gr(t,`discardedCount`),i=dr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:hr(t,`sessionId`),cwd:hr(t,`cwd`),inboxRevision:gr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function sr(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=gr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:hr(t,`id`),message:n,truncated:A(t,`truncated`),severity:ur(t.severity),receivedAt:r,order:i}}function cr(e){let t=E(e);return{order:gr(t,`order`),overflowWatermark:gr(t,`overflowWatermark`)}}function lr(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:sr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=pr(t.notificationIds,mr,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:fr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function ur(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function dr(e){return e===void 0?void 0:ur(e)}function fr(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function pr(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function mr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function hr(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function gr(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function _r(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function vr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function yr(e){return e.retainedCount===0&&e.discardedCount===0}function br(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function xr(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:cn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Er(t.thresholds),projects:j(Dr)(t.projects),totals:Or(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Sr(e){let t=E(e);return{...xr(t),archivedSessionIds:cn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:cn(t.deletedSessionIds,`deletedSessionIds`)}}function Cr(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:cn(t.archivedSessionIds,`archivedSessionIds`),failures:j(Tr)(t.failures),generatedAt:D(t,`generatedAt`)}}function wr(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:cn(t.deletedSessionIds,`deletedSessionIds`),failures:j(Tr)(t.failures),generatedAt:D(t,`generatedAt`)}}function Tr(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Er(e){let t=E(e);return{...M(`archiveIdleDays`,xa(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,xa(t,`deleteArchivedDays`))}}function Dr(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Or(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function kr(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function Ar(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function jr(e){let t=E(e);return{...M(`provider`,O(t,`provider`)),...M(`id`,O(t,`id`)),...M(`name`,O(t,`name`)),...M(`contextWindow`,xa(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Mr(e){return e===void 0?{}:{model:jr(e)}}function Nr(e){let t=E(e);return{models:j(jr)(t.models)}}function Pr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Fr(e){let t=E(e);return{levels:j(Pr)(t.levels)}}function Ir(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Lr(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Rr(e){let t=E(e),n=t.source===void 0?void 0:Lr(t.source);return{configured:A(t,`configured`),...M(`source`,n),...M(`label`,O(t,`label`))}}function zr(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:Ir(t.authType),status:Rr(t.status),...n===void 0?{}:{loginFlow:n}}}function Br(e){let t=E(e);return{providers:j(zr)(t.providers)}}function Vr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Hr(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,O(t,`error`)),...M(`auth`,Ur(t.auth)),...M(`prompt`,Gr(t.prompt)),...M(`select`,qr(t.select)),...M(`info`,Jr(t.info))}}function Hr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Ur(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...M(`instructions`,O(t,`instructions`)),...M(`deviceCode`,Wr(t.deviceCode))}}function Wr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...M(`intervalSeconds`,xa(t,`intervalSeconds`)),...M(`expiresInSeconds`,xa(t,`expiresInSeconds`))}}function Gr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Kr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...M(`placeholder`,O(t,`placeholder`)),...M(`allowEmpty`,ba(t,`allowEmpty`))}}function Kr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function qr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(sa)(t.options)}}function Jr(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...M(`links`,t.links===void 0?void 0:j(Yr)(t.links))}})(e)}function Yr(e){let t=E(e);return{url:D(t,`url`),...M(`label`,O(t,`label`))}}function Xr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:Sa(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:Sa(t,`percent`)}}}function Zr(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...M(`description`,O(t,`description`))}}function Qr(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function $r(e){let t=E(e);return{path:D(t,`path`),entries:j(ei)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function ei(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...M(`size`,xa(t,`size`)),...M(`modifiedAt`,O(t,`modifiedAt`))}}function ti(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...M(`language`,O(t,`language`)),...M(`mediaType`,ai(t.mediaType)),...M(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function ni(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function ri(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function ii(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function ai(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function oi(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...M(`branch`,O(t,`branch`)),...M(`upstream`,O(t,`upstream`)),...M(`ahead`,xa(t,`ahead`)),...M(`behind`,xa(t,`behind`)),files:j(si)(t.files),submodules:t.submodules===void 0?[]:cn(t.submodules,`submodules`)}}function si(e){let t=E(e);return{path:D(t,`path`),...M(`oldPath`,O(t,`oldPath`)),index:ci(t.index),workingTree:ci(t.workingTree),...M(`submoduleFromCommit`,O(t,`submoduleFromCommit`)),...M(`submoduleToCommit`,O(t,`submoduleToCommit`))}}function ci(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function li(e){let t=E(e);return{...M(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function ui(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...M(`exitCode`,xa(t,`exitCode`)),...M(`commandRunId`,O(t,`commandRunId`))}}function di(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:fi(t.status),...M(`exitCode`,xa(t,`exitCode`)),createdAt:D(t,`createdAt`),...M(`startedAt`,O(t,`startedAt`)),...M(`completedAt`,O(t,`completedAt`)),metadata:pi(t.metadata,`metadata`)}}function fi(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function pi(e,t){let n=E(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function mi(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function hi(e){let t=E(e);return{workspaces:j(mi)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function gi(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:_i(t.config),effectiveConfig:_i(t.effectiveConfig),envOverrides:Di(t.envOverrides)}}function _i(e){let t=E(e);return{...M(`host`,O(t,`host`)),...M(`port`,xa(t,`port`)),...M(`allowedHosts`,yi(t.allowedHosts)),...M(`shortcuts`,Ti(t.shortcuts)),...M(`plugins`,Ei(t.plugins)),...M(`pathAccess`,bi(t.pathAccess)),...M(`uploads`,Si(t.uploads)),...M(`maxUploadBytes`,xa(t,`maxUploadBytes`)),...M(`agent`,vi(t.agent)),...M(`spawnSessions`,ba(t,`spawnSessions`)),...M(`subsessions`,ba(t,`subsessions`)),...M(`askUser`,ba(t,`askUser`))}}function vi(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,O(e,`command`)),...M(`dir`,O(e,`dir`))}}}function yi(e){if(e!==void 0){if(e===!0)return!0;if(Ci(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function bi(e){if(e===void 0)return;if(!on(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,xi(t,`pathAccess.allowedPaths`))}}function xi(e,t){if(e!==void 0){if(wi(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Si(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,O(e,`defaultFolder`))}}}function Ci(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function wi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ti(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function Ei(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!on(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!on(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Di(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),askUser:ba(t,`askUser`)??!1,agentCommand:ba(t,`agentCommand`)??!1,agentDir:ba(t,`agentDir`)??!1,...Oi(t),agentSessionDir:ba(t,`agentSessionDir`)??!1}}function Oi(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function ki(e){let t=E(e);return{packages:j(ji)(t.packages)}}function Ai(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:Mi(t.scope),i=Li(t.removed,`removed`);return{action:Ni(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:j(ji)(t.packages)}}function ji(e){let t=E(e);return{source:D(t,`source`),scope:Mi(t.scope),filtered:A(t,`filtered`),...M(`installedPath`,O(t,`installedPath`))}}function Mi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Ni(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Pi(e){let t=E(e);return{plugins:j(Fi)(t.plugins)}}function Fi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ii(t.scope),machineSpecific:Li(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ii(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function Li(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Ri(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`Expected optional count field: ${t}`);return e===0?void 0:e}}function zi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Vi(t.components),release:Ki(t.release),commands:qi(t.commands),messages:j(Ji)(t.messages)}}function Bi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Hi(t.components),capabilities:Xi(t.capabilities)}}function Vi(e){let t=E(e);return{web:Wi(t.web),sessiond:Wi(t.sessiond)}}function Hi(e){let t=E(e);return{web:Ui(t.web),sessiond:Ui(t.sessiond)}}function Ui(e){let t=E(e),n=Yi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Yt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...M(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:Xi(t.capabilities),...M(`activeAgentProfile`,i),...M(`error`,O(t,`error`))}}function Wi(e){let t=E(e);return{component:Yi(t.component),label:D(t,`label`),...M(`runtimeVersion`,O(t,`runtimeVersion`)),...M(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...M(`installation`,Gi(t.installation)),...M(`error`,O(t,`error`))}}function Gi(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...M(`path`,O(t,`path`)),...M(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Ki(e){let t=E(e);return{packageName:D(t,`packageName`),...M(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...M(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,O(t,`error`))}}function qi(e){let t=E(e);return{...M(`update`,O(t,`update`)),...M(`restart`,O(t,`restart`)),...M(`restartWeb`,O(t,`restartWeb`)),...M(`restartSessiond`,O(t,`restartSessiond`)),...M(`status`,O(t,`status`))}}function Ji(e){let t=E(e);return{id:D(t,`id`),severity:Zi(t.severity),title:D(t,`title`),body:D(t,`body`),...M(`command`,O(t,`command`))}}function Yi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function Xi(e){let t=an(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Zi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Qi(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(sa)(t.options)};if(n===`tree`)return{type:n,tree:$i(t.tree)};if(n===`done`)return{type:n,...M(`message`,O(t,`message`)),...ca(t.session),...M(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function $i(e){let t=E(e),n=j(ea)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ia(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:oa(t.activePathIds,`activePathIds`)}}function ea(e){let t=E(e);return{id:aa(t,`id`),parentId:ia(t,`parentId`),kind:ta(t.kind),summary:D(t,`summary`),...M(`timestamp`,O(t,`timestamp`)),...M(`label`,O(t,`label`))}}function ta(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function na(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){ra(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return ra(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,O(t,`editorText`))}}function ra(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ia(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function aa(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function oa(e,t){let n=cn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function sa(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...M(`description`,O(t,`description`))}}function ca(e){return e===void 0?{}:{session:yn(e)}}function la(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function ua(e){let t=E(e);return j(da)(t.attachments)}function da(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function fa(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function pa(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function ma(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ha(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:cn(t.sessionIds,`sessionIds`),r=xa(t,`archivedCount`),i=xa(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function ga(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function _a(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function va(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ya(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function ba(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function xa(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Sa(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function M(e,t){return t===void 0?{}:{[e]:t}}function Ca(e){return typeof e==`string`?e:e.id}function wa(e){return typeof e==`string`?void 0:e.cwd}function Ta(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function Ea(e,t,n=`local`){let r=new URLSearchParams,i=wa(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(Ca(e))}/messages${a===``?``:`?${a}`}`}function Da(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`))}function Oa(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`))}function ka(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${i.toString()}`))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Aa(e){return typeof e==`string`?e:e.id}function ja(e){return typeof e==`string`?void 0:e.cwd}function Ma(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(Aa(e))}`}function P(e,t,n=`local`){return`${Ma(e,n)}/${t}`}function Na(e,t,n=`local`){return`${P(e,t,n)}${Fa(e)}`}function Pa(e,t=`local`){return`${Ma(e,t)}${Fa(e)}`}function Fa(e){let t=ja(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function F(e,t={}){let n=ja(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ia(e){return JSON.stringify({sessions:e.map(La)})}function La(e){let t=Aa(e),n=ja(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ra(e,t){let n=new URLSearchParams;t.projectId!==void 0&&n.set(`projectId`,t.projectId);let r=n.toString();return`${N(t.machineId)}/auth/${e}${r===``?``:`?${r}`}`}function za(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var Ba={piWebStatus:(e=`local`)=>C(za(e),zi),checkForUpdates:(e=`local`)=>C(`${za(e)}?refresh=1`,zi,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,Bi)},Va={machines:()=>C(`api/machines`,un),addMachine:e=>C(`api/machines`,dn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,fn),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,pn,t?{cache:`no-store`}:{})};function Ha(e){return e===void 0?`api/config`:`${N(e)}/config`}function Ua(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var Wa={config:e=>C(Ha(e),gi),saveConfig:(e,t)=>C(Ha(t),gi,{method:`PUT`,body:JSON.stringify({config:e})})},Ga={status:()=>C(`api/normal-auth/status`,bn),setup:e=>C(`api/normal-auth/setup`,la,{method:`POST`,body:JSON.stringify({password:e})}),login:e=>C(`api/normal-auth/login`,la,{method:`POST`,body:JSON.stringify({password:e})}),changePassword:(e,t)=>C(`api/normal-auth/change-password`,la,{method:`POST`,body:JSON.stringify({currentPassword:e,newPassword:t})})},Ka={plugins:e=>C(Ua(e),Pi)};function qa(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Ja={packages:e=>C(qa(``,e),ki),install:(e,t)=>{let n={source:e};return C(qa(`install`,t),Ai,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(qa(`remove`,n),Ai,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(qa(`update`,t),Ai,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Ya={workspaceActivity:(e=`local`)=>C(`${N(e)}/activity`,hi)},Xa={projects:(e=`local`)=>C(`${N(e)}/projects`,j(gn)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,gn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,fa,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Qr))};function Za(e,t,n,r,i,a=`local`){let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ni,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})}var Qa={workspaces:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(_n)),deleteWorkspace:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,di,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,$r),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ti),optionalWorkspaceFile:(e,t,n,r=`local`)=>Ft(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}&optional=true`,ti),createWorkspaceFile:(e,t,n,r=`local`)=>Za(e,t,n,new Uint8Array,void 0,r),writeWorkspaceFile:Za,deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,ri,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,ii,{method:`POST`})},createWorkspaceDirectory:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,xn,{method:`POST`,body:JSON.stringify({path:n})}),moveWorkspaceDirectory:(e,t,n,r,i=`local`)=>C(`${N(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,xn,{method:`PATCH`,body:JSON.stringify({fromPath:n,toPath:r})}),deleteWorkspaceDirectory:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(n)}`,Sn,{method:`DELETE`}),downloadWorkspaceFile:(e,t,n,r=`local`)=>io(e,t,n,r)},$a={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(yn)),search:(e,t,n=`local`)=>C(`${N(n)}/sessions/search?${new URLSearchParams({cwd:e,q:t}).toString()}`,j(yn)),searchContent:(e,t,n=`local`)=>C(`${N(n)}/sessions/search-content?${new URLSearchParams({cwd:e,q:t}).toString()}`,Tn),pinned:(e,t=`local`)=>C(`${N(t)}/sessions/pins?cwd=${encodeURIComponent(e)}`,Cn),pin:(e,t=`local`)=>C(`${Ma(e,t)}/pin`,wn,{method:`PUT`,body:F(e)}),unpin:(e,t=`local`)=>C(`${Ma(e,t)}/pin${Fa(e)}`,wn,{method:`DELETE`}),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,Kn,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return C(P(e,`unread/acknowledge`,r),Kn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(Na(e,`notifications`,t),ir),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),ir,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),ir,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,yn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,xr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Sr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Cr,{method:`POST`,body:Ia(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,wr,{method:`POST`,body:Ia(e)}),messages:(e,t,n=`local`)=>C(Ea(e,t,n),ln),status:(e,t=`local`)=>C(Na(e,`status`,t),Wn),streamSnapshot:(e,t=`local`)=>C(Na(e,`stream-snapshot`,t),Gn),models:(e,t=`local`)=>C(Na(e,`models`,t),Nr),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),Wn,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),Wn,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(Na(e,`thinking-levels`,t),Fr),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),Wn,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),Wn,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(Na(e,`commands`,t),j(Zr)),prompt:(e,t,n,r=`local`,i)=>C(P(e,`prompt`,r),la,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),ua,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),la,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),Qi,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),Qi,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),na,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),abort:(e,t=`local`)=>C(P(e,`abort`,t),pa,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),ma,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),ha,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),ha,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),ga,{method:`POST`,body:F(e)}),deleteArchived:(e,t=`local`)=>C(Pa(e,t),_a,{method:`DELETE`}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),va,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),ya,{method:`POST`,body:F(e)}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),Wn,{method:`POST`,body:F(e)}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),Wn,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Hn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Hn,{method:`POST`,body:F(e,{askId:t})}),authProviders:e=>{let t=new URLSearchParams;e.mode!==void 0&&t.set(`mode`,e.mode),e.authType!==void 0&&t.set(`authType`,e.authType),e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return C(`${N(e.machineId)}/auth/providers${n===``?``:`?${n}`}`,Br)},saveApiKey:(e,t,n)=>C(Ra(`api-key`,n),la,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t)=>C(Ra(`api-key/interactive`,t),Vr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t)=>C(Ra(`logout`,t),la,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t)=>C(Ra(`oauth`,t),Vr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t)=>C(Ra(`oauth/${encodeURIComponent(e)}`,t),Vr),respondOAuthFlow:(e,t,n,r)=>C(Ra(`oauth/${encodeURIComponent(e)}/respond`,r),Vr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t)=>C(Ra(`oauth/${encodeURIComponent(e)}/cancel`,t),Vr,{method:`POST`})},eo={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ui)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ui,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,fa,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,fa,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ui,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,di,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs${no(e)}`,j(di)),getCommandRun:(e,t=`local`)=>to(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,di,{method:`POST`})};async function to(e,t){return Ft(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`,di)}function no(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function ro(e){if(!ao(e))return;let t=e.error;return typeof t==`string`?t:void 0}async function io(e,t,n,r){let i=await fetch(ka(e,t,n,{machineId:r}));if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(ro(e)??i.statusText)}let a=await i.blob(),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o;let c=n.split(`/`).pop();s.download=c===void 0||c===``?`download`:c,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(o)}function ao(e){return typeof e==`object`&&!!e}var oo={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?C(`${N(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Qr)):(r.set(`cwd`,e),C(`${N(n.machineId)}/files?${r.toString()}`,j(Qr)))}},so={gitStatus:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,oi),gitDiff:(e,t,n,r=`local`)=>C(Ta(r,e,t,n),li)},I={...Ba,...Va,...Wa,...Ga,...Ka,...Ja,...Ya,...Xa,...Qa,...$a,...eo,...oo,...so};function co(e,t=`local`,n=yt()){let r=typeof e==`string`?void 0:e.cwd,i=r===void 0||r===``?``:`?${new URLSearchParams({cwd:r}).toString()}`,a=typeof e==`string`?e:e.id,o=xt(`${fo(t)}/sessions/${encodeURIComponent(a)}/events${i}`,void 0,n);return new WebSocket(kt(o))}function lo(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(kt(`${fo(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function uo(e=`local`,t=yt()){let n=xt(`${fo(e)}/events`,void 0,t);return new WebSocket(kt(n))}function fo(e){return`api/machines/${encodeURIComponent(e)}`}var po=`.pi-web/uploads`,mo=class extends Error{constructor(e=`工作区上传已取消`){super(e),this.name=`WorkspaceUploadCancelledError`}},ho=class extends Error{constructor(e,t){super(Eo(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function go(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function _o(e,t){return e?.uploads?.defaultFolder??t}function vo(e,t){let n=ko(e,`上传目标`,{allowEmpty:!0}),r=ko(t,`上传文件名`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function yo(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,Da(e,t,n.path,So(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Co(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(ni(jo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Mo(i)))},i.onerror=()=>{l(Error(`工作区上传失败`))},i.onabort=()=>{l(new mo(o?void 0:`工作区上传已中止`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function bo(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:vo(i,e.name),loaded:0,total:e.size,percent:To(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(wo(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new mo;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=yo(e,t,{path:p.path,file:f},{...xo(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(Oo(e,c))throw e;let t=Do(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new ho(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function xo(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function So(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Co(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:To(e.loaded,n),lengthComputable:e.lengthComputable}}function wo(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:To(i,r),done:n}}function To(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Eo(e){return e.length===1?e[0]?.error??`工作区上传失败`:`${String(e.length)} 个文件上传失败`}function Do(e){return e instanceof Error?e.message:String(e)}function Oo(e,t){return t.requested||e instanceof mo}function ko(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t}不能为空`)}if(Ao(r))throw Error(`${t}必须是工作区相对路径`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t}不能为空`)}if(i.some(e=>e===`..`))throw Error(`${t}不能包含路径穿越`);return i.join(`/`)}function Ao(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function jo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Mo(e){let t=No(e);return Po(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function No(e){try{return jo(e)}catch{return}}function Po(e){return typeof e==`object`&&!!e}function Fo(){return{sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:``}}function Io(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingAsk:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function Lo(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ro(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}var zo=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Bo(e){return zo.some(t=>t===e)}function Vo(e){return e===void 0||e===``?`off`:e}function Ho(e){let t=Vo(e);return Bo(t)?{off:`关闭`,minimal:`最低`,low:`低`,medium:`中`,high:`高`,xhigh:`极高`,max:`最高`}[t]??t:t}function Uo(e){switch(e){case`off`:return`不使用推理`;case`minimal`:return`极简推理(约 1k tokens)`;case`low`:return`轻量推理(约 2k tokens)`;case`medium`:return`中等推理(约 8k tokens)`;case`high`:return`深度推理(约 16k tokens)`;case`xhigh`:return`最大推理(约 32k tokens)`;case`max`:return`最高推理(约 64k tokens)`;default:return}}function Wo(e,t){let n=t.length>=2?t:zo,r=n.length-1,i=Vo(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function Go(e,t){return`${e}:${t}`}function Ko(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var qo=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Jo=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new qo,this.api=n.api??Ya,this.onActivityApplied=n.onActivityApplied}refresh(e=L(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Yo(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=L(this.getState())){let n=this.getState(),r=L(n)===t,i=Xo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...L(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Yo(e){let t={};for(let n of e.workspaces)Ro(n)&&(t[n.cwd]=n);return t}function Xo(e,t){let n={...e};return Ro(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Zo=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=ts(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){let t=this.captureTarget();if(t!==void 0){if(e!==void 0&&e!==``){await this.openLoginProvider(e,t);return}this.setState({authDialog:{step:`method`,target:t}})}}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step===`method`)try{let{providers:n}=await this.api.authProviders({mode:`login`,authType:e,...$o(t.target)});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:n,target:t.target}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`必须填写 API key`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{let n=e.target;await this.api.saveApiKey(e.provider.id,t,n),this.closeDialog(),this.refreshStatus(n)}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.captureTarget();if(t!==void 0)try{let{providers:n}=await this.api.authProviders({mode:`logout`,...$o(t)});if(e!==void 0&&e!==``){let r=n.find(t=>t.id===e);r!==void 0&&!this.rejectRemoteOAuth(`logout`,r,t)?await this.logoutProviderForTarget(r.id,t):r===void 0&&this.setState({error:`没有 ${e} 的已保存凭据`});return}this.setState({authDialog:{step:`logout`,providers:n,target:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog;if(t?.step!==`logout`)return;let n=t.providers.find(t=>t.id===e);n===void 0||this.rejectRemoteOAuth(`logout`,n,t.target)||await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){try{await this.api.logoutProvider(e,t),this.closeDialog(),this.refreshStatus(t)}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(t.flow.flowId,n.requestId,o,t.target);this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||es(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){try{let{providers:n}=await this.api.authProviders({mode:`login`,...$o(t)}),r=n.filter(t=>t.id===e);if(r.length===0){this.setState({error:`找不到认证提供商:${e}`});return}if(r.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:r,target:t}});return}let i=r[0];if(i===void 0)return;i.authType===`oauth`||i.loginFlow===`interactive`?await this.startOAuth(i,t):this.setState({authDialog:{step:`apiKey`,provider:i,value:``,target:t}})}catch(e){this.setState({error:String(e)})}}async startOAuth(e,t){if(this.rejectRemoteOAuth(`login`,e,t))return;let n=++this.oauthOperationGeneration;this.stopPolling();try{let r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,t):await this.api.startInteractiveApiKeyLogin(e.id,t);if(n!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,t)}catch{}return}this.updateOAuthFlow(r,t),r.status===`running`&&this.startPolling(r.flowId,t)}catch(e){n===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t,n){let r=this.getState().selectedMachine;if(t.authType!==`oauth`||n.machineKind!==`remote`)return!1;let i=r?.baseUrl??`对应的远程 PI WEB 实例`,a=e===`login`?`登录`:`退出`;return this.setState({error:`远程机器的 OAuth ${a}必须直接在 ${i} 上配置。`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?es(n.flow):void 0,a=es(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,inputValue:s,responding:c,target:t}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!Qo(i.target,t)){this.stopPolling();return}let a=es(i.flow);try{this.updateOAuthFlow(await this.api.oauthFlow(e,i.target),i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!Qo(o.target,t)||es(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{this.applyStatus(await this.api.status(t,e.machineId))}catch{}}selectedSessionForMachine(e){let t=this.getState();if(L(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}captureTarget(){let e=this.getState(),t=e.selectedMachine,n={machineId:L(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return n;let r=e.selectedProject;if(r===void 0){this.setState({error:`请先选择项目,再配置提供商认证。`});return}return{...n,projectId:r.id,projectName:r.name}}targetStillSelected(e){return L(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function Qo(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function $o(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function es(e){return e.prompt?.requestId??e.select?.requestId}function ts(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function ns(e){return e.replaceAll(`:`,`.`)}function rs(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function is(e,t){let n=rs(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function as(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));os(i,r)}function os(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function ss(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:vo(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ps(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:ps(0,n),status:`uploading`,startedAt:e.startedAt}}function cs(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function ls(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=fs(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function us(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`因前面的文件上传失败而未上传。`});return{...e,files:r,...fs(r),status:`error`,error:t,completedAt:n}}function ds(e,t){let n=`上传已取消`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...fs(r),status:`cancelled`,error:n,completedAt:t}}function fs(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ps(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var ms=ns(`core:workspace.files`),hs=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??bo,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=L(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i=await Promise.all(Object.keys(this.getState().expandedDirs).map(async r=>{try{return[r,(await this.api.workspaceTree(e.id,t.id,r,n)).entries]}catch(e){if(gs(e))return;throw e}})),a=Object.fromEntries(i.filter(e=>e!==void 0));this.setState({fileTree:r.entries,expandedDirs:a,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:ys(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,L(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),as(ms,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}selectDirectory(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,L(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(gs(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}async createFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0||e===``))try{await this.api.createWorkspaceFile(t.id,n.id,e,L(this.getState())),await this.refreshFiles(),await this.selectFile(e),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async createDirectory(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0||e===``))try{await this.api.createWorkspaceDirectory(t.id,n.id,e,L(this.getState())),await this.refreshFiles(),this.selectDirectory(e),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async moveSelectedPath(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(t===void 0||n===void 0||r===void 0||r===``||e===``))try{let i=L(this.getState());bs(this.getState())===`directory`?(await this.api.moveWorkspaceDirectory(t.id,n.id,r,e,i),await this.refreshFiles(),this.selectDirectory(e)):(await this.api.moveWorkspaceFile(t.id,n.id,r,e,void 0,i),await this.refreshFiles(),await this.selectFile(e)),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async deleteSelectedPath(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace,n=this.getState().selectedFilePath;if(!(e===void 0||t===void 0||n===void 0||n===``))try{let r=L(this.getState());bs(this.getState())===`directory`?await this.api.deleteWorkspaceDirectory(e.id,t.id,n,r):await this.api.deleteWorkspaceFile(e.id,t.id,n,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async downloadSelectedFile(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace,n=this.getState().selectedFilePath;if(!(e===void 0||t===void 0||n===void 0||n===``||bs(this.getState())===`directory`))try{await this.api.downloadWorkspaceFile(e.id,t.id,n,L(this.getState())),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`上传文件前请选择工作区。`});return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=ss({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(ds(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:ys(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(cs(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ls(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof ho)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(_s(t)){let e=ds(n,this.now());return this.setUploadBatch(e),e}let r=vs(t),i=us(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function gs(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function _s(e){return e instanceof mo}function vs(e){return e instanceof Error?e.message:String(e)}function ys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function bs(e){let t=e.selectedFilePath;return t===void 0?`file`:xs(e.fileTree,e.expandedDirs,t)?.type===`directory`?`directory`:`file`}function xs(e,t,n){let r=e.find(e=>e.path===n);if(r!==void 0)return r;for(let e of Object.values(t)){let t=e.find(e=>e.path===n);if(t!==void 0)return t}}var Ss=ns(`core:workspace.git`),Cs=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=await I.gitStatus(e.id,t.id,L(this.getState()));this.setState({gitStatus:n,gitStale:!1,error:``});let r=this.getState().selectedDiffPath;r!==void 0&&(n.files.some(e=>e.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),as(Ss,`diff`,void 0,{replace:!0})))}catch(e){this.setState({error:String(e)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),as(Ss,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0))try{let[r,i]=await Promise.all([I.gitDiff(t.id,n.id,{path:e},L(this.getState())),I.gitDiff(t.id,n.id,{path:e,staged:!0},L(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:i,error:``})}catch(e){this.setState({error:String(e)})}}updatePolling(){this.dispose();let e=this.getState();(e.workspaceTool===`core:workspace.git`||e.mainView===`core:workspace.git`)&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}},ws=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await I.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Es(this.getState().machineActivities,r),machineRuntimes:Es(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Fo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await I.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`无法移除本地机器。`});return}try{let n=this.getState().selectedMachine?.id===e.id;await I.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:Ts(this.getState().machineStatuses,e.id),machineRuntimes:Ts(this.getState().machineRuntimes,e.id),machineActivities:Ts(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await I.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await I.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} 暂不可用,正在重新连接…`}}),n}async safeRemoteHealth(e){try{return await I.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>I.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>I.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function Ts(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Es(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Ds=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=L(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(L(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=L(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(L(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){L(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=L(this.getState());try{if(await this.api.closeProject(e,t),L(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}};function Os(e,t){return t[e.path]}function ks(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function As(e,t,n){return Ns(Ps(e,t,n))}function js(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Ms(e){return Ns(Object.values(e??{}))}function Ns(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ps(e,t,n){return Object.values(n).filter(n=>js(e,t,n.cwd))}var Fs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Qa,this.onError=n.onError}handleActivityApplied(e){return L(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return L(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(L(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Is(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Is(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(L(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&L(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Ro).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Is(e,t,n){return e.some(e=>js(e,t[e.id]??[],n))}var Ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Ba,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=L(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=L(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),Rs(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return L(this.getState())===e&&t===this.requestSequence}};function Rs(e){if(e.release.error!==void 0)throw Error(`PI WEB 更新检查失败:${e.release.error}`);if(e.release.skipped===!0)throw Error(`由于离线或版本检查设置禁用了远程版本检查,已跳过 PI WEB 更新检查`)}var zs=`pi-web:cached-new-sessions:v1`,Bs=`browserCachedNew`,Vs=`local`;function Hs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Us(e,t=Vs,n=Hs()){if(e.messageCount!==0||e.archived===!0)return;let r=Ys(n).filter(n=>n.id!==e.id||n.machineId!==t);Xs([Ws(e,t),...r],n)}function Ws(e,t=Vs){return{...e,browserCachedNew:!0,machineId:t}}function Gs(e,t=Vs,n=Hs()){Xs(Ys(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Ks(e,t,n=Vs,r=Hs()){let i=new Set(t.map(e=>e.id)),a=Ys(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Xs(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function qs(e){return e!==void 0&&Qs(e)&&e.browserCachedNew===!0}function Js(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:Vs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ys(e=Hs()){try{let t=e?.getItem(zs);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Zs(e)):[]}catch{return[]}}function Xs(e,t=Hs()){try{e.length===0?t?.removeItem(zs):t?.setItem(zs,JSON.stringify(e))}catch{}}function Zs(e){if(!$s(e))return[];let t=ec(e,`id`),n=ec(e,`path`),r=ec(e,`cwd`),i=ec(e,`created`),a=ec(e,`modified`),o=ec(e,`firstMessage`),s=nc(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=tc(e,`name`),l=tc(e,`parentSessionPath`),u=tc(e,`machineId`)??Vs;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},machineId:u,browserCachedNew:!0}]}function Qs(e){return Bs in e}function $s(e){return typeof e==`object`&&!!e}function ec(e,t){let n=e[t];return typeof n==`string`?n:void 0}function tc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function nc(e,t){let n=e[t];return typeof n==`number`?n:void 0}function rc(e,t){return Tc(t===void 0?e.flatMap(cc):e.flatMap((e,n)=>cc(e).map(e=>({...e,transcriptIndex:t+n})))).filter(e=>e.parts.length>0)}function ic(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function ac(e,t){let n=mc(t);return n===void 0?e:{...e,meta:n}}function oc(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,ic(t,n)]}function sc(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function cc(e){if(uc(e))return[e];if(R(e,`role`)===`bashExecution`)return[ac(_c(e),e)];let t=R(e,`role`),n=vc(t),r=yc(Nc(e,`content`),e),i=t===`toolResult`?xc(R(e,`toolName`)??``,Nc(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?dc(a):void 0;if(o!==void 0)return o.map(t=>ac(t,e));let s=pc(e);if(n===`tool`)return[ac({role:n,parts:a,...s===void 0?{}:{source:s}},e)];let c=a.filter(e=>e.type!==`empty`),l=n===`assistant`&&c.length>0&&c.every(e=>e.type===`skillRead`)?`skill`:n,u=c.length>0?[ac({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=lc(e);return d===void 0?u:[...u,ac(d,e)]}function lc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return ic(`system`,`模型响应失败:${t===void 0||t===``?`模型返回了错误。`:t}`)}function uc(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Nc(e,`parts`))}function dc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=fc(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 fc(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function pc(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function mc(e){let t=hc(Nc(e,`timestamp`)),n=gc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function hc(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function gc(e){if(R(e,`role`)!==`assistant`)return;let t=R(e,`provider`),n=R(e,`model`),r=R(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function _c(e){let t=R(e,`command`)??``,n=Pc(e,`excludeFromContext`)===!0?[`已从上下文中排除`,``,`$ ${t}`]:[`$ ${t}`],r=Nc(e,`output`);r!=null&&n.push(``,Ic(r));let i=Nc(e,`exitCode`);i!=null&&n.push(``,`退出码 ${Ic(i)}`),Pc(e,`cancelled`)===!0&&n.push(``,`已取消`),Pc(e,`truncated`)===!0&&n.push(``,`输出已截断`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`完整输出:${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
4
4
  `)}]}}function vc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function yc(e,t){let n=bc(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=R(e,`type`),n=R(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=R(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=R(e,`name`)??`tool`,n=Nc(e,`arguments`),r=R(e,`id`),i=t===`read`?wc(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ac(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=R(e,`data`),n=R(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return kc(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?Cc(e.text,t):e):kc(e):[n]}function bc(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return Sc(Nc(e,`details`))}function xc(e,t){if(e===`ask_user`)return Sc(Nc(t,`superseded`))}function Sc(e){try{return{type:`askUserRecord`,outcome:Vn(e)}}catch{return}}function Cc(e,t){let n=R(t,`toolCallId`),r=Nc(t,`content`),i=Nc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:R(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Pc(t,`isError`)===!0}}function wc(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Tc(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.transcriptIndex===void 0?{}:{transcriptIndex:r.transcriptIndex},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&Dc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Ec(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function Dc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Oc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Oc(e){let t=Nc(e,`preview`);if(!Mc(t))return;let n=R(t,`diff`),r=R(t,`error`),i=Fc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function kc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ac(e)}]:[{type:`text`,text:Ic(e)}]}function Ac(e){if(!Mc(e))return Ic(e);let t=R(e,`command`);if(t!==void 0)return t;let n=R(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${jc(t)}`).join(` · `)}function jc(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Mc(e){return typeof e==`object`&&!!e}function Nc(e,t){return Mc(e)?e[t]:void 0}function R(e,t){let n=Nc(e,t);return typeof n==`string`?n:void 0}function Pc(e,t){let n=Nc(e,t);return typeof n==`boolean`?n:void 0}function Fc(e,t){let n=Nc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ic(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Lc=`pi-web:prompt-draft:`;function Rc(e){return`${Lc}${e}`}function zc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bc(e,t=zc()){try{return t?.getItem(Rc(e))??``}catch{return``}}function Vc(e,t,n=zc()){try{t?n?.setItem(Rc(e),t):n?.removeItem(Rc(e))}catch{}}function Hc(e,t=zc()){try{t?.removeItem(Rc(e))}catch{}}function Uc(e,t,n=zc()){let r=Bc(e,n);r!==``&&(Vc(t,r,n),Hc(e,n))}var Wc=`pi-web:ask-draft:`;function Gc(e,t){return`${Wc}${e}:${t}`}function Kc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function qc(e,t,n=Kc()){try{let r=n?.getItem(Gc(e,t));return r==null?{}:Xc(r)}catch{return{}}}function Jc(e,t,n,r=Kc()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Gc(e,t)):r?.setItem(Gc(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function Yc(e,t,n=Kc()){try{n?.removeItem(Gc(e,t))}catch{}}function Xc(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=Zc(r);t!==void 0&&(n[e]=t)}return n}function Zc(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={...e},n=t.values,r=t.otherText;if(!(!Array.isArray(n)||!n.every(e=>typeof e==`string`))&&!(r!==void 0&&typeof r!=`string`))return{values:[...n],...r===void 0?{}:{otherText:r}}}function Qc(e,t){return e.filter(e=>tl(e,t[e.id])!==void 0).length}function $c(e,t){return e.filter(e=>tl(e,t[e.id])===void 0)}function el(e,t){let n=[];for(let r of e){let e=tl(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function tl(e,t){if(t===void 0)return;let n=new Set(e.options.map(e=>e.value)),r=[...new Set(t.values)].filter(e=>n.has(e)),i=nl(t.otherText);if(e.multiple!==!0&&r.length+(i===void 0?0:1)>1){let t=r[0];return t===void 0?i===void 0?void 0:{id:e.id,values:[],otherText:i}:{id:e.id,values:[t]}}if(!(r.length===0&&i===void 0))return{id:e.id,values:r,...i===void 0?{}:{otherText:i}}}function nl(e){if(e===void 0)return;let t=e.trim().slice(0,Ht);return t===``?void 0:t}function rl(e,t){return ic(`bash`,`${t===!0?`已从上下文中排除
@@ -757,7 +757,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
757
757
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
758
758
  .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
759
759
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
760
- `]}};B([b({attribute:!1})],Fm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],Fm.prototype,`uploadInput`,void 0),B([x()],Fm.prototype,`pendingUpload`,void 0),B([x()],Fm.prototype,`destinationFolder`,void 0),B([x()],Fm.prototype,`overwrite`,void 0),B([x()],Fm.prototype,`createDirs`,void 0),B([x()],Fm.prototype,`formError`,void 0),B([x()],Fm.prototype,`dragActive`,void 0),Fm=B([y(`workspace-files-panel`)],Fm);function Im(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function Lm(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{vo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Rm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function zm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`请选择文件。`;if(t===void 0)return`正在加载 ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`二进制文件:${t.path} · ${Qm(t.size)}`}function Bm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Vm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Hm(e){return e==null?[]:Array.from(e)}function Um(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Wm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function Gm(e){let t=e.files.length;switch(e.status){case`completed`:return`已上传 ${String(t)} 个文件`;case`error`:return`${String(t)} 个文件上传失败`;case`cancelled`:return`已取消上传 ${String(t)} 个文件`;case`uploading`:return`正在上传 ${String(t)} 个文件`}}function Km(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return Xm(e.percent)}}function qm(e){return e.status===`uploading`?e.percent:1}function Jm(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return Xm(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function Ym(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Qm(e.loaded)} / ${Qm(e.total)}`:`已写入 ${e.response.path}`:e.error}function Xm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Zm(){Pm(()=>import(`./CodeViewer-CWHRo84w.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Qm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${$m(t)} KB`;let n=t/1024;return n<1024?`${$m(n)} MB`:`${$m(n/1024)} GB`}function $m(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function eh(e){let t=e.submoduleFromCommit,n=e.submoduleToCommit;return t!==void 0&&n!==void 0?`${t} → ${n}`:`commit`}function th(e){let t=e.split(`/`);return t[t.length-1]??e}function nh(e,t=[]){let n=ih(``),r=new Set(t);for(let e of t)oh(n,e).isSubmodule=!0;for(let t of e){if(r.has(t.path)){let e=oh(n,t.path);e.isSubmodule=!0,e.pointer={kind:`file`,name:eh(t),path:t.path,file:t,isSubmodulePointer:!0};continue}let e=t.path.split(`/`).filter(e=>e.length>0),i=e[e.length-1];if(i===void 0)continue;let a=n;for(let t=0;t<e.length-1;t+=1){let n=e[t];n!==void 0&&(a=ah(a,n))}a.files.push({kind:`file`,name:i,path:t.path,file:t})}return sh(n)}function rh(e){let t=[];for(let n of e)n.kind===`directory`&&(t.push(n.path),t.push(...rh(n.children)));return t}function ih(e){return{path:e,directories:new Map,files:[],isSubmodule:!1}}function ah(e,t){let n=e.path.length===0?t:`${e.path}/${t}`,r=e.directories.get(n);if(r!==void 0)return r;let i=ih(n);return e.directories.set(n,i),i}function oh(e,t){let n=e;for(let e of t.split(`/`).filter(e=>e.length>0))n=ah(n,e);return n}function sh(e){let t=[...e.directories.values()].map(e=>({kind:`directory`,name:th(e.path),path:e.path,...e.isSubmodule?{isSubmodule:!0}:{},children:sh(e)})).sort((e,t)=>e.name.localeCompare(t.name)),n=[...e.files].sort((e,t)=>e.name.localeCompare(t.name));return[...e.pointer===void 0?[]:[e.pointer],...t,...n]}function ch(e,t=[]){let n=new Set(t),r=new Map,i=new Map;for(let e of t)i.set(e,[]);let a=[];for(let o of e){if(n.has(o.path)){r.set(o.path,{name:eh(o),file:o});continue}let e=lh(o.path,t);if(e!==void 0){i.get(e)?.push({path:o.path,relativePath:o.path.slice(e.length+1),file:o});continue}a.push(o)}return{submodules:t.map(e=>{let t=r.get(e),n=i.get(e)??[];return{path:e,name:th(e),...t===void 0?{}:{pointer:t},files:[...n].sort((e,t)=>e.relativePath.localeCompare(t.relativePath))}}).sort((e,t)=>e.name.localeCompare(t.name)),files:a}}function lh(e,t){let n;for(let r of t)r!==``&&e.startsWith(`${r}/`)&&(n===void 0||r.length>n.length)&&(n=r);return n}var uh=`pi-web.gitFileView`;function dh(e){return e===`tree`?`tree`:`list`}function fh(e=mh()){if(e===void 0)return`list`;try{return dh(e.getItem(uh))}catch{return`list`}}function ph(e,t=mh()){if(t!==void 0)try{t.setItem(uh,e)}catch{}}function mh(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var hh={submodules:[],files:[]},gh={nodes:[],listModel:hh,expandablePaths:[]},_h=class extends v{constructor(...e){super(...e),this.view=fh(),this.expandedDirectories=new Set}static{this.styles=[Em,h`
760
+ `]}};B([b({attribute:!1})],Fm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],Fm.prototype,`uploadInput`,void 0),B([x()],Fm.prototype,`pendingUpload`,void 0),B([x()],Fm.prototype,`destinationFolder`,void 0),B([x()],Fm.prototype,`overwrite`,void 0),B([x()],Fm.prototype,`createDirs`,void 0),B([x()],Fm.prototype,`formError`,void 0),B([x()],Fm.prototype,`dragActive`,void 0),Fm=B([y(`workspace-files-panel`)],Fm);function Im(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function Lm(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{vo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Rm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function zm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`请选择文件。`;if(t===void 0)return`正在加载 ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`二进制文件:${t.path} · ${Qm(t.size)}`}function Bm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Vm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Hm(e){return e==null?[]:Array.from(e)}function Um(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Wm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function Gm(e){let t=e.files.length;switch(e.status){case`completed`:return`已上传 ${String(t)} 个文件`;case`error`:return`${String(t)} 个文件上传失败`;case`cancelled`:return`已取消上传 ${String(t)} 个文件`;case`uploading`:return`正在上传 ${String(t)} 个文件`}}function Km(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return Xm(e.percent)}}function qm(e){return e.status===`uploading`?e.percent:1}function Jm(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return Xm(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function Ym(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Qm(e.loaded)} / ${Qm(e.total)}`:`已写入 ${e.response.path}`:e.error}function Xm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Zm(){Pm(()=>import(`./CodeViewer-BUT2Idcq.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Qm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${$m(t)} KB`;let n=t/1024;return n<1024?`${$m(n)} MB`:`${$m(n/1024)} GB`}function $m(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function eh(e){let t=e.submoduleFromCommit,n=e.submoduleToCommit;return t!==void 0&&n!==void 0?`${t} → ${n}`:`commit`}function th(e){let t=e.split(`/`);return t[t.length-1]??e}function nh(e,t=[]){let n=ih(``),r=new Set(t);for(let e of t)oh(n,e).isSubmodule=!0;for(let t of e){if(r.has(t.path)){let e=oh(n,t.path);e.isSubmodule=!0,e.pointer={kind:`file`,name:eh(t),path:t.path,file:t,isSubmodulePointer:!0};continue}let e=t.path.split(`/`).filter(e=>e.length>0),i=e[e.length-1];if(i===void 0)continue;let a=n;for(let t=0;t<e.length-1;t+=1){let n=e[t];n!==void 0&&(a=ah(a,n))}a.files.push({kind:`file`,name:i,path:t.path,file:t})}return sh(n)}function rh(e){let t=[];for(let n of e)n.kind===`directory`&&(t.push(n.path),t.push(...rh(n.children)));return t}function ih(e){return{path:e,directories:new Map,files:[],isSubmodule:!1}}function ah(e,t){let n=e.path.length===0?t:`${e.path}/${t}`,r=e.directories.get(n);if(r!==void 0)return r;let i=ih(n);return e.directories.set(n,i),i}function oh(e,t){let n=e;for(let e of t.split(`/`).filter(e=>e.length>0))n=ah(n,e);return n}function sh(e){let t=[...e.directories.values()].map(e=>({kind:`directory`,name:th(e.path),path:e.path,...e.isSubmodule?{isSubmodule:!0}:{},children:sh(e)})).sort((e,t)=>e.name.localeCompare(t.name)),n=[...e.files].sort((e,t)=>e.name.localeCompare(t.name));return[...e.pointer===void 0?[]:[e.pointer],...t,...n]}function ch(e,t=[]){let n=new Set(t),r=new Map,i=new Map;for(let e of t)i.set(e,[]);let a=[];for(let o of e){if(n.has(o.path)){r.set(o.path,{name:eh(o),file:o});continue}let e=lh(o.path,t);if(e!==void 0){i.get(e)?.push({path:o.path,relativePath:o.path.slice(e.length+1),file:o});continue}a.push(o)}return{submodules:t.map(e=>{let t=r.get(e),n=i.get(e)??[];return{path:e,name:th(e),...t===void 0?{}:{pointer:t},files:[...n].sort((e,t)=>e.relativePath.localeCompare(t.relativePath))}}).sort((e,t)=>e.name.localeCompare(t.name)),files:a}}function lh(e,t){let n;for(let r of t)r!==``&&e.startsWith(`${r}/`)&&(n===void 0||r.length>n.length)&&(n=r);return n}var uh=`pi-web.gitFileView`;function dh(e){return e===`tree`?`tree`:`list`}function fh(e=mh()){if(e===void 0)return`list`;try{return dh(e.getItem(uh))}catch{return`list`}}function ph(e,t=mh()){if(t!==void 0)try{t.setItem(uh,e)}catch{}}function mh(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var hh={submodules:[],files:[]},gh={nodes:[],listModel:hh,expandablePaths:[]},_h=class extends v{constructor(...e){super(...e),this.view=fh(),this.expandedDirectories=new Set}static{this.styles=[Em,h`
761
761
  :host { flex: 1 1 auto; }
762
762
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
763
763
  .toolbar .toolbar-actions button { margin-left: 0; }
@@ -825,7 +825,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
825
825
  <div class="viewer-header"><strong>${e.path??`差异`}</strong><small>${e.staged?`已暂存`:`未暂存`}${e.truncated?` · 已截断`:``}</small></div>
826
826
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
827
827
  </section>
828
- `}function xh(){Pm(()=>import(`./UnifiedDiffViewer-DbtJHQ4S.js`),[],import.meta.url)}function Sh(e){let t=e.branch??`游离 HEAD`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function Ch(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function wh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Th(){return[{id:`workspace.files`,title:`文件`,icon:Cm(`files`),order:10,render:Eh},{id:`workspace.git`,title:`Git`,icon:Cm(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:Oh},{id:`workspace.terminal`,title:`终端`,icon:Cm(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Dh}]}function Eh(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Dh(e){return kh(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Oh(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function kh(){Pm(()=>import(`./TerminalPanel-CoYwbZrx.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Ah={apiVersion:1,name:`PI WEB 核心`,activate:()=>{let e=!vt();return{contributions:{actions:e?dm():dm().filter(e=>e.id!==`view.terminal`),workspacePanels:e?Th():Th().filter(e=>e.id!==`workspace.terminal`)}}}},jh={"--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`},Mh={"--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`},Nh={"--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`},Ph={apiVersion:1,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:Mh},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:Nh},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:jh}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},Fh=/^[a-z][a-z0-9.-]*$/u,Ih=/^[a-z][a-z0-9.-]*$/u,Lh=new WeakMap,Rh=new WeakMap,zh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&Wh(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Kh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Bh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(Vh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(Vh(t,e)):void 0},render:n=>t.render(Vh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!Fh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Ih.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Gh(t)}`);return t}};function Bh(e,t){return Lh.get(e)?.(t)??e}function Vh(e,t){return Rh.get(e)?.(t)??e}function Hh(e,t){return Lh.set(e,t),e}function Uh(e,t){return Rh.set(e,t),e}function Wh(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Gh(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Kh(e){return e.state.selectedMachine?.id??`local`}var qh=/^[a-z][a-z0-9.-]*$/u;function Jh(e){return qh.test(e)}var Yh=`machine.`;function Xh(e,t){if(e===``)throw Error(`Machine id is required`);if(!Jh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${Zh(e)}.${t}`}function Zh(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Qh(e=`pi-web-plugins/manifest.json`,t={}){let n=Ot(e),r=await tg(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=$h(e.module,n),a=ig(await(t.moduleLoader??eg)(r),r);i.push({id:t.machineId===void 0?e.id:Xh(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function $h(e,t,n){return e.startsWith(`/`)?n===void 0?Ot(e):Ot(e,n):new URL(e,t).toString()}async function eg(e){return Pm(()=>import(e),[],import.meta.url)}async function tg(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return ng(await t.json())}}function ng(e){if(!og(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!og(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:rg(e.machineSpecific)}})}}function rg(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ig(e,t){if(!og(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!ag(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ag(e){return og(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function og(e){return typeof e==`object`&&!!e}var sg=class{constructor(e,t){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(`PI WEB 插件`,()=>Qh()),this.gatewayLoad}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(`来自 ${e.name} 的 PI WEB 插件`,()=>Qh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},cg=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function lg(){return typeof window>`u`||!(`matchMedia`in window)?[]:cg.map(e=>window.matchMedia(e))}function ug(e,t=dg()){return e.some(e=>e.matches)||fg(t)}function dg(){return typeof navigator>`u`?void 0:navigator}function fg(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var pg=class{constructor(e=mg()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function mg(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var hg=`(max-width: 760px)`,gg=`(max-width: 1180px)`,_g=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=e=>{this.isStackedWorkspaceLayout!==e.matches&&(this.isStackedWorkspaceLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ug(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??vg(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??yg(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??lg(),this.viewportPositionRepairer=t.viewportPositionRepairer??new pg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=ug(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(e,t){return bg(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function vg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(hg)}function yg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(gg)}function bg(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var xg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new qo,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Sg(),this.documentTarget=t.documentTarget??Cg(),this.isDocumentVisible=t.isDocumentVisible??wg,this.scheduleFrame=t.scheduleFrame??Tg}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function Sg(){return typeof window>`u`?void 0:window}function Cg(){return typeof document>`u`?void 0:document}function wg(){return typeof document>`u`||document.visibilityState===`visible`}function Tg(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Eg=[`machines`,`projects`,`workspaces`,`sessions`];function Dg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Og(e,t){if(e!==`none`)return e??Dg(t)}function kg(e,t){return t.isMobileLayout?Og(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ag(e,t,n){return n.isMobileLayout?Og(e,n.state)===t?`none`:t:e}function jg(e,t,n){return n?t:e}function Mg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Fg(n)}function Ng(e){return Eg[Eg.indexOf(e)+1]}var Pg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Og(this.expanded,this.getState())}isCollapsed(e){return kg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Ag(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Mg(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(jg(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Ng(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ig(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Fg(e){let t=new Set(e);return Eg.filter(e=>t.has(e))}function Ig(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Lg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,Rg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Rg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var zg=`pi-web:panel-sizes:v1`,Bg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Vg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??t_(),this.panelSizes=qg(this.storage)}hostConnected(){}constraints(e){return Hg(e)}panelWidth(e,t){return Kg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Kg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Zg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Qg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Jg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${e_(Kg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${e_(Kg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Hg(e){return Bg[e]}function Ug(e,t,n){return e===`navigation`?n-t:t-n}function Wg(e,t,n,r,i=Hg(e)){return Kg(e,t+Ug(e,n,r),i)}function Gg(e,t,n,r={}){let i=r.constraints??Hg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=$g(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Kg(e,t+a,i)}function Kg(e,t,n=Hg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function qg(e=t_()){try{let t=e?.getItem(zg);return t==null||t===``?{}:Yg(JSON.parse(t))}catch{return{}}}function Jg(e,t=t_()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(zg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Kg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Kg(`workspace`,e.workspacePanelWidth)),t.setItem(zg,JSON.stringify(n))}catch{}}function Yg(e){if(!n_(e)||e.version!==1)return{};let t={},n=Xg(e.navigationPanelWidth),r=Xg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Kg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Kg(`workspace`,r)),t}function Xg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Zg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Qg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function $g(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function e_(e){return`${String(Math.round(e))}px`}function t_(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function n_(e){return typeof e==`object`&&!!e}function r_(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:a_(e.get(`tool`)),view:o_(e.get(`view`))}}function i_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function a_(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function o_(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function s_(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function c_(){return u_(new URLSearchParams(window.location.search).get(`settings`))}function l_(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function u_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function d_(e,t){return t===void 0?e:e.map(e=>p_(e,t))}function f_(e,t){let n=new Set(Ef(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return d_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?m_(e):e)}function p_(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?m_(e):{...e,shortcut:n}}function m_(e){let t={...e};return delete t.shortcut,t}function h_(e,t){let n=t.api??eo,r=t.pollIntervalMs??1e3,i=t.setTimeout??v_(),a=t.clearTimeout??y_();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:g_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function g_(e,t,n,r,i){return __(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&__(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function __(e){return e.status===`succeeded`||e.status===`failed`}function v_(){return(e,t)=>globalThis.setTimeout(e,t)}function y_(){return e=>{globalThis.clearTimeout(e)}}function b_(e,t=`活动中`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function x_(e,t=`活动中`,n){let r=b_(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var S_=0,C_=120;function w_(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?E_():T_(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-S_,f=n.top-c-S_;return[...d<C_&&f>d?[`bottom: ${D_(a-n.top+S_)};`,`max-height: ${D_(Math.max(0,f))};`]:[`top: ${D_(n.bottom+S_)};`,`max-height: ${D_(Math.max(0,d))};`],`right: ${D_(Math.max(0,i-u))};`,`max-width: ${D_(Math.max(0,u-o))};`].join(` `)}function T_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():E_()}function E_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function D_(e){return`${String(Math.round(e))}px`}var O_=class{constructor(e){this.host=e,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this.host)||this.close()},e.addController(this)}hostConnected(){document.addEventListener(`click`,this.onDocumentClick)}hostDisconnected(){document.removeEventListener(`click`,this.onDocumentClick)}isOpen(e){return this.openId===e}toggle(e,t){if(this.openId===e){this.close();return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openId=e,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===``||(this.openId=void 0,this.menuStyle=``,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},k_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function A_(e){return e.composedPath().some(e=>j_(e,k_))}function j_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function M_(e,t){A_(e)||t()}function N_(e,t){return A_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?F_(e,()=>{I_(e.currentTarget,-1)}):e.key===`ArrowDown`?F_(e,()=>{I_(e.currentTarget,1)}):e.key===`Home`?F_(e,()=>{L_(e.currentTarget,0)}):e.key===`End`?F_(e,()=>{L_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?F_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?F_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&F_(e,t.cancel)}function P_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function F_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function I_(e,t){let n=z_(e),r=V_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||R_(n,i+t)}function L_(e,t){let n=z_(e);n.length!==0&&R_(n,t<0?n.length-1:t)}function R_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function z_(e){let t=V_(e)?.getRootNode();return t===void 0||!B_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function B_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function V_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var H_=h`
828
+ `}function xh(){Pm(()=>import(`./UnifiedDiffViewer-CXY7AXrD.js`),[],import.meta.url)}function Sh(e){let t=e.branch??`游离 HEAD`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function Ch(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function wh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Th(){return[{id:`workspace.files`,title:`文件`,icon:Cm(`files`),order:10,render:Eh},{id:`workspace.git`,title:`Git`,icon:Cm(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:Oh},{id:`workspace.terminal`,title:`终端`,icon:Cm(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Dh}]}function Eh(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Dh(e){return kh(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Oh(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function kh(){Pm(()=>import(`./TerminalPanel-b8CZY7en.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Ah={apiVersion:1,name:`PI WEB 核心`,activate:()=>{let e=!vt();return{contributions:{actions:e?dm():dm().filter(e=>e.id!==`view.terminal`),workspacePanels:e?Th():Th().filter(e=>e.id!==`workspace.terminal`)}}}},jh={"--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`},Mh={"--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`},Nh={"--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`},Ph={apiVersion:1,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:Mh},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:Nh},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:jh}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},Fh=/^[a-z][a-z0-9.-]*$/u,Ih=/^[a-z][a-z0-9.-]*$/u,Lh=new WeakMap,Rh=new WeakMap,zh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&Wh(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Kh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Bh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(Vh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(Vh(t,e)):void 0},render:n=>t.render(Vh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!Fh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Ih.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Gh(t)}`);return t}};function Bh(e,t){return Lh.get(e)?.(t)??e}function Vh(e,t){return Rh.get(e)?.(t)??e}function Hh(e,t){return Lh.set(e,t),e}function Uh(e,t){return Rh.set(e,t),e}function Wh(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Gh(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Kh(e){return e.state.selectedMachine?.id??`local`}var qh=/^[a-z][a-z0-9.-]*$/u;function Jh(e){return qh.test(e)}var Yh=`machine.`;function Xh(e,t){if(e===``)throw Error(`Machine id is required`);if(!Jh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${Zh(e)}.${t}`}function Zh(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Qh(e=`pi-web-plugins/manifest.json`,t={}){let n=Ot(e),r=await tg(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=$h(e.module,n),a=ig(await(t.moduleLoader??eg)(r),r);i.push({id:t.machineId===void 0?e.id:Xh(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function $h(e,t,n){return e.startsWith(`/`)?n===void 0?Ot(e):Ot(e,n):new URL(e,t).toString()}async function eg(e){return Pm(()=>import(e),[],import.meta.url)}async function tg(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return ng(await t.json())}}function ng(e){if(!og(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!og(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:rg(e.machineSpecific)}})}}function rg(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ig(e,t){if(!og(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!ag(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ag(e){return og(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function og(e){return typeof e==`object`&&!!e}var sg=class{constructor(e,t){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(`PI WEB 插件`,()=>Qh()),this.gatewayLoad}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(`来自 ${e.name} 的 PI WEB 插件`,()=>Qh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},cg=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function lg(){return typeof window>`u`||!(`matchMedia`in window)?[]:cg.map(e=>window.matchMedia(e))}function ug(e,t=dg()){return e.some(e=>e.matches)||fg(t)}function dg(){return typeof navigator>`u`?void 0:navigator}function fg(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var pg=class{constructor(e=mg()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function mg(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var hg=`(max-width: 760px)`,gg=`(max-width: 1180px)`,_g=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=e=>{this.isStackedWorkspaceLayout!==e.matches&&(this.isStackedWorkspaceLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ug(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??vg(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??yg(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??lg(),this.viewportPositionRepairer=t.viewportPositionRepairer??new pg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=ug(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(e,t){return bg(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function vg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(hg)}function yg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(gg)}function bg(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var xg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new qo,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Sg(),this.documentTarget=t.documentTarget??Cg(),this.isDocumentVisible=t.isDocumentVisible??wg,this.scheduleFrame=t.scheduleFrame??Tg}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function Sg(){return typeof window>`u`?void 0:window}function Cg(){return typeof document>`u`?void 0:document}function wg(){return typeof document>`u`||document.visibilityState===`visible`}function Tg(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Eg=[`machines`,`projects`,`workspaces`,`sessions`];function Dg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Og(e,t){if(e!==`none`)return e??Dg(t)}function kg(e,t){return t.isMobileLayout?Og(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ag(e,t,n){return n.isMobileLayout?Og(e,n.state)===t?`none`:t:e}function jg(e,t,n){return n?t:e}function Mg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Fg(n)}function Ng(e){return Eg[Eg.indexOf(e)+1]}var Pg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Og(this.expanded,this.getState())}isCollapsed(e){return kg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Ag(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Mg(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(jg(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Ng(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ig(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Fg(e){let t=new Set(e);return Eg.filter(e=>t.has(e))}function Ig(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Lg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,Rg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Rg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var zg=`pi-web:panel-sizes:v1`,Bg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Vg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??t_(),this.panelSizes=qg(this.storage)}hostConnected(){}constraints(e){return Hg(e)}panelWidth(e,t){return Kg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Kg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Zg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Qg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Jg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${e_(Kg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${e_(Kg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Hg(e){return Bg[e]}function Ug(e,t,n){return e===`navigation`?n-t:t-n}function Wg(e,t,n,r,i=Hg(e)){return Kg(e,t+Ug(e,n,r),i)}function Gg(e,t,n,r={}){let i=r.constraints??Hg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=$g(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Kg(e,t+a,i)}function Kg(e,t,n=Hg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function qg(e=t_()){try{let t=e?.getItem(zg);return t==null||t===``?{}:Yg(JSON.parse(t))}catch{return{}}}function Jg(e,t=t_()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(zg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Kg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Kg(`workspace`,e.workspacePanelWidth)),t.setItem(zg,JSON.stringify(n))}catch{}}function Yg(e){if(!n_(e)||e.version!==1)return{};let t={},n=Xg(e.navigationPanelWidth),r=Xg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Kg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Kg(`workspace`,r)),t}function Xg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Zg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Qg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function $g(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function e_(e){return`${String(Math.round(e))}px`}function t_(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function n_(e){return typeof e==`object`&&!!e}function r_(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:a_(e.get(`tool`)),view:o_(e.get(`view`))}}function i_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function a_(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function o_(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function s_(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function c_(){return u_(new URLSearchParams(window.location.search).get(`settings`))}function l_(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function u_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function d_(e,t){return t===void 0?e:e.map(e=>p_(e,t))}function f_(e,t){let n=new Set(Ef(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return d_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?m_(e):e)}function p_(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?m_(e):{...e,shortcut:n}}function m_(e){let t={...e};return delete t.shortcut,t}function h_(e,t){let n=t.api??eo,r=t.pollIntervalMs??1e3,i=t.setTimeout??v_(),a=t.clearTimeout??y_();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:g_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function g_(e,t,n,r,i){return __(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&__(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function __(e){return e.status===`succeeded`||e.status===`failed`}function v_(){return(e,t)=>globalThis.setTimeout(e,t)}function y_(){return e=>{globalThis.clearTimeout(e)}}function b_(e,t=`活动中`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function x_(e,t=`活动中`,n){let r=b_(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var S_=0,C_=120;function w_(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?E_():T_(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-S_,f=n.top-c-S_;return[...d<C_&&f>d?[`bottom: ${D_(a-n.top+S_)};`,`max-height: ${D_(Math.max(0,f))};`]:[`top: ${D_(n.bottom+S_)};`,`max-height: ${D_(Math.max(0,d))};`],`right: ${D_(Math.max(0,i-u))};`,`max-width: ${D_(Math.max(0,u-o))};`].join(` `)}function T_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():E_()}function E_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function D_(e){return`${String(Math.round(e))}px`}var O_=class{constructor(e){this.host=e,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this.host)||this.close()},e.addController(this)}hostConnected(){document.addEventListener(`click`,this.onDocumentClick)}hostDisconnected(){document.removeEventListener(`click`,this.onDocumentClick)}isOpen(e){return this.openId===e}toggle(e,t){if(this.openId===e){this.close();return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openId=e,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===``||(this.openId=void 0,this.menuStyle=``,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},k_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function A_(e){return e.composedPath().some(e=>j_(e,k_))}function j_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function M_(e,t){A_(e)||t()}function N_(e,t){return A_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?F_(e,()=>{I_(e.currentTarget,-1)}):e.key===`ArrowDown`?F_(e,()=>{I_(e.currentTarget,1)}):e.key===`Home`?F_(e,()=>{L_(e.currentTarget,0)}):e.key===`End`?F_(e,()=>{L_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?F_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?F_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&F_(e,t.cancel)}function P_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function F_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function I_(e,t){let n=z_(e),r=V_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||R_(n,i+t)}function L_(e,t){let n=z_(e);n.length!==0&&R_(n,t<0?n.length-1:t)}function R_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function z_(e){let t=V_(e)?.getRootNode();return t===void 0||!B_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function B_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function V_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var H_=h`
829
829
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
830
830
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
831
831
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -1112,7 +1112,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1112
1112
  </div>
1113
1113
  `}renderSession(e,t){let{session:n}=e,r=Math.min(e.depth,2),i=mv(n)===t,a=this.selectionScopes.has(t),o=a&&i,s=o&&this.selectedSessionIds.has(n.id),c=this.statuses[n.id],l=this.activities[n.id],u=Ov(n,c,l,this.sending[n.id]===!0),d=kv(n,this.unreadSessionIds),f=this.sessionPersistenceOptions(),p=Au(n,c,f),m=fv(n,c,f),ee=ju(n,c,f),te=p&&this.canReload,ne=this.pinnedSessionIds.includes(n.id),re=n.persisted!==!1,ie=this.openMenuSessionId===n.id?gv(this.sessions,n):0;return g`
1114
1114
  <div
1115
- class="action-row ${this.selected?.id===n.id?`selected`:``} ${s?`bulk-selected`:``} ${n.archived===!0?`archived`:``} ${a?`selecting`:``} ${d?`unread`:``} ${ne?`pinned`:``}"
1115
+ class="action-row ${this.selected?.id===n.id?`selected`:``} ${s?`bulk-selected`:``} ${n.archived===!0?`archived`:``} ${a?`selecting`:``} ${d?`unread`:``} ${ne?`pinned`:``} ${this.openMenuSessionId===n.id?`menu-open`:``}"
1116
1116
  style=${`--depth:${String(r)}`}
1117
1117
  tabindex="0"
1118
1118
  title=${n.path}
@@ -1165,6 +1165,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
1165
1165
  .action-name, .section-selected { text-align: start; unicode-bidi: plaintext; }
1166
1166
  .action-row.unread .action-name { color: var(--pi-text-bright); font-weight: 650; }
1167
1167
  .action-row { content-visibility: auto; contain-intrinsic-size: auto 58px; }
1168
+ .action-row.menu-open { content-visibility: visible; }
1168
1169
  .session-load-more-sentinel { display: grid; place-items: center; min-height: 36px; margin: 2px 0 6px; }
1169
1170
  .session-load-more-sentinel button { padding: 5px 9px; color: var(--pi-muted); font-size: 12px; }
1170
1171
  .plain-heading { min-width: 0; }
@@ -53,7 +53,7 @@
53
53
  html, body { margin: 0; height: 100%; overflow: hidden; background: var(--pi-bg); color: var(--pi-text); }
54
54
  body { min-height: 100dvh; }
55
55
  </style>
56
- <script type="module" crossorigin src="./assets/index-Bdbjyy7F.js"></script>
56
+ <script type="module" crossorigin src="./assets/index-80SI7dCz.js"></script>
57
57
  <link rel="modulepreload" crossorigin href="./assets/vendor-editor-core-vUi74DnD.js">
58
58
  <link rel="modulepreload" crossorigin href="./assets/vendor-editor-languages-DoaXUodB.js">
59
59
  </head>
@@ -1,4 +1,4 @@
1
- import { statSync } from "node:fs";
1
+ import { realpathSync, statSync } from "node:fs";
2
2
  import { readFile, writeFile } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, getAgentDir, createLsToolDefinition, createReadToolDefinition, createWriteToolDefinition, defineTool, ModelRuntime, readStoredCredential, SessionManager, } from "@earendil-works/pi-coding-agent";
@@ -136,6 +136,20 @@ export function filterManagedGlobalContextFiles(cwd, agentDir, base) {
136
136
  }),
137
137
  };
138
138
  }
139
+ export function filterManagedProjectSkills(cwd, base) {
140
+ const projectRoot = realpathSync(cwd);
141
+ return {
142
+ ...base,
143
+ skills: base.skills.filter((skill) => {
144
+ try {
145
+ return pathInsideOrEqual(projectRoot, realpathSync(skill.filePath));
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }),
151
+ };
152
+ }
139
153
  function pathInsideOrEqual(parent, child) {
140
154
  const normalizedParent = resolve(parent);
141
155
  const normalizedChild = resolve(child);
@@ -319,6 +333,7 @@ function createManagementRuntimeFactory(modelRuntime, resolveSettingsScope, spaw
319
333
  settingsManager,
320
334
  resourceLoaderOptions: {
321
335
  agentsFilesOverride: (base) => filterManagedGlobalContextFiles(cwd, agentDir, base),
336
+ skillsOverride: (base) => filterManagedProjectSkills(cwd, base),
322
337
  },
323
338
  });
324
339
  const managedToolOptions = createManagedAgentToolOptions(cwd);