@vincenthanxiaodu/pi-web 1.202608.14 → 1.202608.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CodeViewer-DNsBvsnm.js → CodeViewer-DTv-zPMN.js} +1 -1
- package/dist/client/assets/{TerminalPanel-CDO2UjCh.js → TerminalPanel-7gR0021c.js} +1 -1
- package/dist/client/assets/{index-CO6A9lVF.js → index-Bg8YBVNq.js} +5 -5
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{P as e,S as t,X as n,Y as r,et as i,l as a,q as o,y as s}from"./vendor-editor-core-CXO8gGab.js";import{c,i as l,l as u,n as d,r as f,s as p,t as m,u as h}from"./vendor-editor-languages-CpW4sJsX.js";import{_ as g,f as _,g as v,m as y,n as b,p as x,u as S}from"./index-
|
|
1
|
+
import{P as e,S as t,X as n,Y as r,et as i,l as a,q as o,y as s}from"./vendor-editor-core-CXO8gGab.js";import{c,i as l,l as u,n as d,r as f,s as p,t as m,u as h}from"./vendor-editor-languages-CpW4sJsX.js";import{_ as g,f as _,g as v,m as y,n as b,p as x,u as S}from"./index-Bg8YBVNq.js";import{t as C}from"./vendor-editor-legacy-CYBnW6ZU.js";var w=class extends y{constructor(...e){super(...e),this.content=``}firstUpdated(){this.recreateEditor()}updated(e){(e.has(`content`)||e.has(`language`))&&this.recreateEditor()}disconnectedCallback(){this.view?.destroy(),this.view=void 0,super.disconnectedCallback()}render(){return v`<div class="host"></div>`}recreateEditor(){this.editorHost&&(this.view?.destroy(),this.view=new o({parent:this.editorHost,state:i.create({doc:this.content,extensions:[n(),r.of(a),e(t,{fallback:!0}),i.readOnly.of(!0),o.editable.of(!1),o.lineWrapping,T,...D(this.language),...O(this.language)]})}))}static{this.styles=g`
|
|
2
2
|
:host { display: block; min-height: 0; height: 100%; }
|
|
3
3
|
.host { height: 100%; min-height: 0; overflow: auto; }
|
|
4
4
|
`}};b([_()],w.prototype,`content`,void 0),b([_()],w.prototype,`language`,void 0),b([S(`.host`)],w.prototype,`editorHost`,void 0),w=b([x(`code-viewer`)],w);var T=o.theme({"&":{height:`100%`,color:`var(--pi-text)`,backgroundColor:`var(--pi-bg)`,fontSize:`12px`},".cm-scroller":{fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,lineHeight:`1.45`},".cm-gutters":{backgroundColor:`var(--pi-bg)`,color:`var(--pi-dim)`,borderRight:`1px solid var(--pi-border-muted)`},".cm-activeLineGutter":{backgroundColor:`transparent`},".cm-activeLine":{backgroundColor:`transparent`},".cm-content":{caretColor:`transparent`},"&.cm-focused":{outline:`none`}}),E=o.theme({".cm-content":{textAlign:`start`},".cm-line":{unicodeBidi:`plaintext`}});function D(e){return e===`markdown`?[o.contentAttributes.of({dir:`auto`}),E]:[]}function O(e){if(e===void 0)return[];switch(e){case`typescript`:return[u({typescript:!0})];case`javascript`:return[u()];case`json`:return[l()];case`markdown`:return[p()];case`css`:return[h()];case`html`:return[c()];case`python`:return[f()];case`rust`:return[d()];case`go`:return[m()];case`diff`:return[s.define(C)];default:return[]}}export{w as CodeViewer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as ee,u as h}from"./index-
|
|
1
|
+
import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as ee,u as h}from"./index-Bg8YBVNq.js";import{n as g,t as _}from"./vendor-terminal-D8k4UKM2.js";var te=`important`,ne=` !important`,v=p(class extends s{constructor(e){if(super(e),e.type!==t.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(ne);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?te:``):n[e]=r}}return o}}),y=`#ffffff`,re=`#000000`,b=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],x=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],ie={black:b[0],red:b[1],green:b[2],yellow:b[3],blue:b[4],magenta:b[5],cyan:b[6],white:b[7],brightBlack:b[8],brightRed:b[9],brightGreen:b[10],brightYellow:b[11],brightBlue:b[12],brightMagenta:b[13],brightCyan:b[14],brightWhite:b[15]};function S(e,t,n={}){let r=Math.max(0,Math.floor(t));if(e.length<=0||r===0)return{text:``,lines:[],physicalLineCount:0,viewportLine:0};let i=ce(n.theme),a=n.theme?.foreground??y,o=n.theme?.background??re,s=[],c=e.getNullCell(),l=-1;for(let t=0;t<e.length;t+=1){let u=e.getLine(t);if(u===void 0){s.push({text:``,runs:[],wrapped:!1});continue}let d=ae(u,r,c,{palette:i,foreground:a,background:o,drawBoldTextInBrightColors:n.drawBoldTextInBrightColors!==!1});s.push(d),(d.text!==``||d.runs.some(e=>e.style.background!==o))&&(l=t)}let u=Math.min(e.length-1,Math.max(0,e.baseY+e.cursorY)),d=Math.max(l,u),f=s.slice(0,d+1),p=[];for(let e of f){let t=p.at(-1);if(e.wrapped&&t!==void 0){t.text+=e.text,T(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
|
|
2
2
|
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function ae(e,t,n,r){let i=[],a=Math.min(t,e.length);for(let t=0;t<a;t+=1){let a=e.getCell(t,n);if(a===void 0){i.push({text:` `,meaningful:!1,style:w(r)});continue}let o=a.getWidth();if(o===0)continue;let s=a.getChars();i.push({text:s===``?` `.repeat(Math.max(1,o)):s,meaningful:s!==``||!a.isAttributeDefault(),style:oe(a,r)})}let o=i.length-1;for(;o>=0&&i[o]?.meaningful!==!0;)--o;let s=[],c=``;for(let e=0;e<=o;e+=1){let t=i[e];t!==void 0&&(c+=t.text,E(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function oe(e,t){let n=e.isInverse()!==0,r=C(e,`foreground`,t),i=C(e,`background`,t);if(n&&([r,i]=[i,r]),e.isBold()!==0&&t.drawBoldTextInBrightColors){let i=n?e.isBgPalette()?e.getBgColor():void 0:e.isFgPalette()?e.getFgColor():void 0;i!==void 0&&i>=0&&i<8&&(r=t.palette[i+8]??r)}return{foreground:r,background:i,bold:e.isBold()!==0,italic:e.isItalic()!==0,dim:e.isDim()!==0,underline:e.isUnderline()!==0,invisible:e.isInvisible()!==0,strikethrough:e.isStrikethrough()!==0,overline:e.isOverline()!==0}}function C(e,t,n){let r=t===`foreground`?e.isFgRGB():e.isBgRGB(),i=t===`foreground`?e.isFgPalette():e.isBgPalette(),a=t===`foreground`?e.getFgColor():e.getBgColor();return r?le(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function w(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function T(e,t){for(let n of t)E(e,n)}function E(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&se(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function se(e,t){return e.foreground===t.foreground&&e.background===t.background&&e.bold===t.bold&&e.italic===t.italic&&e.dim===t.dim&&e.underline===t.underline&&e.invisible===t.invisible&&e.strikethrough===t.strikethrough&&e.overline===t.overline}function ce(e){let t=[...b];for(let n=0;n<x.length;n+=1){let r=x[n];if(r===void 0)continue;let i=e?.[r];typeof i==`string`&&(t[n]=i)}let n=[0,95,135,175,215,255];for(let e=0;e<216;e+=1){let r=n[Math.floor(e/36)%6]??0,i=n[Math.floor(e/6)%6]??0,a=n[e%6]??0;t.push(D(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(D(n,n,n))}for(let n=0;n<Math.min(e?.extendedAnsi?.length??0,240);n+=1){let r=e?.extendedAnsi?.[n];r!==void 0&&(t[n+16]=r)}return t}function le(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function D(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var O=`pi-web.terminal.softKeys`,ue=`(pointer: coarse), (max-width: 760px)`;function de(e,t){return e??t}function fe(e){if(e===`true`)return!0;if(e===`false`)return!1}function k(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(ue):void 0}function A(e){return e?.matches===!0}function j(e=k()){return de(N(),A(e))}function M(){return N()!==void 0}function N(e=F()){if(e!==void 0)try{return fe(e.getItem(O))}catch{return}}function P(e,t=F()){if(t!==void 0)try{t.setItem(O,String(e))}catch{}}function F(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var I=[{id:`escape`,label:`Esc`,ariaLabel:`Escape`,title:`Send Escape`},{id:`tab`,label:`Tab`,ariaLabel:`Tab`,title:`Send Tab`},{id:`ctrl-c`,label:`Ctrl+C`,ariaLabel:`Control C`,title:`Interrupt the foreground process`},{id:`ctrl-d`,label:`Ctrl+D`,ariaLabel:`Control D`,title:`Send EOF / close input`},{id:`ctrl-z`,label:`Ctrl+Z`,ariaLabel:`Control Z`,title:`Suspend the foreground process`},{id:`ctrl-l`,label:`Ctrl+L`,ariaLabel:`Control L`,title:`Clear / redraw the terminal`},{id:`ctrl-r`,label:`Ctrl+R`,ariaLabel:`Control R`,title:`Reverse search history`},{id:`ctrl-u`,label:`Ctrl+U`,ariaLabel:`Control U`,title:`Delete to the start of the line`},{id:`ctrl-w`,label:`Ctrl+W`,ariaLabel:`Control W`,title:`Delete the previous word`},{id:`arrow-left`,label:`←`,ariaLabel:`Left arrow`,title:`Move left`},{id:`arrow-up`,label:`↑`,ariaLabel:`Up arrow`,title:`Move up / previous command`},{id:`arrow-down`,label:`↓`,ariaLabel:`Down arrow`,title:`Move down / next command`},{id:`arrow-right`,label:`→`,ariaLabel:`Right arrow`,title:`Move right`},{id:`home`,label:`Home`,ariaLabel:`Home`,title:`Move to the start`},{id:`end`,label:`End`,ariaLabel:`End`,title:`Move to the end`},{id:`page-up`,label:`PgUp`,ariaLabel:`Page up`,title:`Page up`},{id:`page-down`,label:`PgDn`,ariaLabel:`Page down`,title:`Page down`},{id:`delete`,label:`Del`,ariaLabel:`Delete`,title:`Delete forward`},{id:`backspace`,label:`⌫`,ariaLabel:`Backspace`,title:`Backspace`},{id:`meta-backward-word`,label:`M-B`,ariaLabel:`Meta B`,title:`Move backward one word`},{id:`meta-forward-word`,label:`M-F`,ariaLabel:`Meta F`,title:`Move forward one word`}],L=`\x1B`,R=``;function z(e,t){switch(e){case`escape`:return L;case`tab`:return` `;case`ctrl-c`:return B(`c`);case`ctrl-d`:return B(`d`);case`ctrl-z`:return B(`z`);case`ctrl-l`:return B(`l`);case`ctrl-r`:return B(`r`);case`ctrl-u`:return B(`u`);case`ctrl-w`:return B(`w`);case`arrow-left`:return V(`D`,t);case`arrow-up`:return V(`A`,t);case`arrow-down`:return V(`B`,t);case`arrow-right`:return V(`C`,t);case`home`:return H(`H`,t);case`end`:return H(`F`,t);case`page-up`:return`${L}[5~`;case`page-down`:return`${L}[6~`;case`delete`:return`${L}[3~`;case`backspace`:return R;case`meta-backward-word`:return`${L}b`;case`meta-forward-word`:return`${L}f`}}function B(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function V(e,t){return t?.applicationCursorKeysMode===!0?`${L}O${e}`:`${L}[${e}`}function H(e,t){return t?.applicationCursorKeysMode===!0?`${L}O${e}`:`${L}[${e}`}var pe=8,me=500,U=class extends l{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(z(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType===`mouse`&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){let t=this.pointerStart;t?.pointerId===e.pointerId&&W(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||W(n,e))&&this.sendSoftKey(t,{refocus:e.pointerType===`mouse`}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<me){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return a`
|
|
3
3
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
4
4
|
${I.map(e=>a`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-DTv-zPMN.js","./vendor-editor-core-CXO8gGab.js","./vendor-editor-languages-CpW4sJsX.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-7gR0021c.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,Y as o,Z as s,d as c,et as l,f as u,j as d,l as f,p,q as m,u as ee}from"./vendor-editor-core-CXO8gGab.js";import{a as te,o as ne,s as re}from"./vendor-editor-languages-CpW4sJsX.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 ie=globalThis,ae=ie.ShadowRoot&&(ie.ShadyCSS===void 0||ie.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,oe=Symbol(),se=new WeakMap,ce=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==oe)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(ae&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=se.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&se.set(t,e))}return e}toString(){return this.cssText}},le=e=>new ce(typeof e==`string`?e:e+``,void 0,oe),h=(e,...t)=>new ce(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,oe),ue=(e,t)=>{if(ae)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=ie.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},de=ae?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return le(t)})(e):e,{is:fe,defineProperty:pe,getOwnPropertyDescriptor:me,getOwnPropertyNames:he,getOwnPropertySymbols:ge,getPrototypeOf:_e}=Object,ve=globalThis,ye=ve.trustedTypes,be=ye?ye.emptyScript:``,xe=ve.reactiveElementPolyfillSupport,Se=(e,t)=>e,Ce={toAttribute(e,t){switch(t){case Boolean:e=e?be: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}},we=(e,t)=>!fe(e,t),Te={attribute:!0,type:String,converter:Ce,reflect:!1,useDefault:!1,hasChanged:we};Symbol.metadata??=Symbol(`metadata`),ve.litPropertyMetadata??=new WeakMap;var Ee=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=Te){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&&pe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=me(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)??Te}static _$Ei(){if(this.hasOwnProperty(Se(`elementProperties`)))return;let e=_e(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Se(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Se(`properties`))){let e=this.properties,t=[...he(e),...ge(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(de(e))}else e!==void 0&&t.push(de(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 ue(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?Ce: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?Ce: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??we)(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){}};Ee.elementStyles=[],Ee.shadowRootOptions={mode:`open`},Ee[Se(`elementProperties`)]=new Map,Ee[Se(`finalized`)]=new Map,xe?.({ReactiveElement:Ee}),(ve.reactiveElementVersions??=[]).push(`2.1.2`);var De=globalThis,Oe=e=>e,ke=De.trustedTypes,Ae=ke?ke.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,je=`$lit$`,Me=`lit$${Math.random().toFixed(9).slice(2)}$`,Ne=`?`+Me,Pe=`<${Ne}>`,Fe=document,Ie=()=>Fe.createComment(``),Le=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Re=Array.isArray,ze=e=>Re(e)||typeof e?.[Symbol.iterator]==`function`,Be=`[
|
|
3
3
|
\f\r]`,Ve=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,He=/-->/g,Ue=/>/g,We=RegExp(`>|${Be}(?:([^\\s"'>=/]+)(${Be}*=${Be}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Ge=/'/g,Ke=/"/g,qe=/^(?:script|style|textarea|title)$/i,Je=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Je(1),Ye=Je(2),Xe=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Ze=new WeakMap,Qe=Fe.createTreeWalker(Fe,129);function $e(e,t){if(!Re(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ae===void 0?t:Ae.createHTML(t)}var et=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Ve;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===Ve?c[1]===`!--`?o=He:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=We):(qe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=We):o=Ue:o===We?c[0]===`>`?(o=i??Ve,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?We:c[3]===`"`?Ke:Ge):o===Ke||o===Ge?o=We:o===He||o===Ue?o=Ve:(o=We,i=void 0);let d=o===We&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Ve?n+Pe:l>=0?(r.push(s),n.slice(0,l)+je+n.slice(l)+Me+d):n+Me+(l===-2?t:d)}return[$e(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},tt=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]=et(t,n);if(this.el=e.createElement(l,r),Qe.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Qe.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(je)){let t=u[o++],n=i.getAttribute(e).split(Me),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ot:r[1]===`?`?st:r[1]===`@`?ct:at}),i.removeAttribute(e)}else e.startsWith(Me)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(qe.test(i.tagName)){let e=i.textContent.split(Me),t=e.length-1;if(t>0){i.textContent=ke?ke.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ie()),Qe.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ie())}}}else if(i.nodeType===8)if(i.data===Ne)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Me,e+1))!==-1;)c.push({type:7,index:a}),e+=Me.length-1}a++}}static createElement(e,t){let n=Fe.createElement(`template`);return n.innerHTML=e,n}};function nt(e,t,n=e,r){if(t===Xe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Le(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=nt(e,i._$AS(e,t.values),i,r)),t}var rt=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??Fe).importNode(t,!0);Qe.currentNode=r;let i=Qe.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new it(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new lt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Qe.nextNode(),a++)}return Qe.currentNode=Fe,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++}},it=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=nt(this,e,t),Le(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Xe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?ze(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!==_&&Le(this._$AH)?this._$AA.nextSibling.data=e:this.T(Fe.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=tt.createElement($e(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new rt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Ze.get(e.strings);return t===void 0&&Ze.set(e.strings,t=new tt(e)),t}k(t){Re(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(Ie()),this.O(Ie()),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=Oe(e).nextSibling;Oe(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},at=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=nt(this,e,t,0),a=!Le(e)||e!==this._$AH&&e!==Xe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=nt(this,r[n+o],t,o),s===Xe&&(s=this._$AH[o]),a||=!Le(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??``)}},ot=class extends at{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},st=class extends at{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},ct=class extends at{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=nt(this,e,t,0)??_)===Xe)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)}},lt=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){nt(this,e)}},ut={M:je,P:Me,A:Ne,C:1,L:et,R:rt,D:ze,V:nt,I:it,H:at,N:st,U:ct,B:ot,F:lt},dt=De.litHtmlPolyfillSupport;dt?.(tt,it),(De.litHtmlVersions??=[]).push(`3.3.3`);var ft=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new it(t.insertBefore(Ie(),e),e,void 0,n??{})}return i._$AI(e),i},pt=globalThis,v=class extends Ee{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=ft(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,pt.litElementHydrateSupport?.({LitElement:v});var mt=pt.litElementPolyfillSupport;mt?.({LitElement:v}),(pt.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},ht={attribute:!0,type:String,converter:Ce,reflect:!1,hasChanged:we},gt=(e=ht,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`?gt(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 _t=(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 _t(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 _t(n,r,{get(){return a(this)}})}}function vt(e,t=bt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(xt(e),n).toString()}function yt(e,t=bt()){let n=new URL(vt(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 bt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function xt(e){return e.startsWith(`/`)?`.${e}`:e}async function C(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(vt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(St(e)??i.statusText)}return t(await i.json())}function St(e){if(Ct(e))return typeof e.error==`string`?e.error:void 0}function Ct(e){return typeof e==`object`&&!!e}var wt={pluginLifecycle:`plugins.lifecycle`},Tt=1e3,Et=32*1024,Dt=8*1024,Ot=1e3,kt=4e3,At=1e3,jt=4e3,Mt=1e4,Nt={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Pt(e){if(!Lt(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=Ft(e.machine),a=Ft(e.unattributed),o=It(e.projects),s=It(e.workspaces);if(!(typeof t!=`string`||t===``)&&!(typeof n!=`number`||!Number.isFinite(n))&&!(typeof r!=`string`||r===``)&&!(i===void 0||a===void 0)&&!(o===void 0||s===void 0))return{epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r}}function Ft(e){if(!Lt(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function It(e){if(!Lt(e))return;let t=new Map;for(let[n,r]of Object.entries(e)){let e=Ft(r);e!==void 0&&t.set(n,e)}return Object.fromEntries(t)}function Lt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Rt=Object.values(wt),zt=new Set(Rt);wt.pluginLifecycle,wt.pluginLifecycle;function Bt(e){return typeof e==`string`&&zt.has(e)}function Vt(e,t){return e?.capabilities?.includes(t)===!0}function Ht(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Bt)}function Ut(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Wt(n))continue;let e=n.source,r=n.name,i=n.replacement;e!==`environment`&&e!==`config`||typeof r!=`string`||r===``||i!==void 0&&(typeof i!=`string`||i===``)||t.push({source:e,name:r,...i===void 0?{}:{replacement:i}})}return t}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Gt=/^[a-z][a-z0-9.-]*$/u,Kt=new Set([`core`,`themes`]),qt=`machine.`;function Jt(e){return Gt.test(e)}function Yt(e){return Kt.has(e)||e.startsWith(qt)}var Xt=Object.freeze({showSafeStart:`pi-web plugins safe-start show`,bundledOnly:`pi-web plugins safe-start set bundled-only --restart`,noServerPlugins:`pi-web plugins safe-start set none --restart`,clearSafeStart:`pi-web plugins safe-start clear --restart`});function Zt(e){if(!Jt(e))throw Error(`Invalid PI WEB plugin id: ${e}`);return`pi-web plugins disable ${e} --restart`}function w(e){return typeof e==`object`&&!!e}function T(e){if(!w(e))throw Error(`Expected object response`);return e}function E(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function D(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function O(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function k(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function A(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Qt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function $t(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function en(e){let t=T(e);return{messages:Qt(t.messages),start:O(t,`start`),total:O(t,`total`)}}function tn(e){let t=T(e);return A(nn)(t.machines)}function nn(e){let t=T(e),n=sn(t,`kind`),r=D(t,`baseUrl`),i=cn(t,`status`),a=D(t,`statusMessage`);return{id:E(t,`id`),name:E(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:E(t,`createdAt`),updatedAt:E(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function rn(e){let t=T(e),n=cn(t,`status`),r=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:fa(t.web)},...t.sessiond===void 0?{}:{sessiond:fa(t.sessiond)},...r===void 0?{}:{error:r}}}function an(e){let t=T(e),n=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...M(`packageName`,D(t,`packageName`)),...M(`generatedAt`,D(t,`generatedAt`)),...t.components===void 0?{}:{components:ua(t.components)},...t.capabilities===void 0?{}:{capabilities:va(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:on(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function on(e){let t=Ut(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function sn(e,t){let n=E(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function cn(e,t){let n=D(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 ln(e){let t=T(e);return{id:E(t,`id`),name:E(t,`name`),path:E(t,`path`),createdAt:E(t,`createdAt`)}}function un(e){let t=T(e);return Object.freeze({id:E(t,`id`),projectId:E(t,`projectId`),path:E(t,`path`),label:E(t,`label`),isMain:k(t,`isMain`),...M(`provider`,gn(t.provider)),...M(`removal`,_n(t.removal)),effectiveConfig:bn(t.effectiveConfig)})}function dn(e){let t=T(e),n=fn(t.status),r=E(t,`projectId`),i=D(t,`ownerPluginId`);if(n===`provider`&&i===void 0)throw Error(`Provider workspace resolution is missing ownerPluginId`);if(n===`folder`&&i!==void 0)throw Error(`Folder workspace resolution must not include ownerPluginId`);let a=A(un)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=A(pn)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function fn(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function pn(e){let t=T(e),n=D(t,`pluginId`),r=t.pluginIds===void 0?void 0:$t(t.pluginIds,`pluginIds`);return Object.freeze({code:mn(t.code),message:E(t,`message`),tier:hn(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function mn(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function hn(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function gn(e){if(e===void 0)return;if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace provider field`);let t=e.capabilities;if(!w(t)||Array.isArray(t))throw Error(`Invalid workspace provider capabilities field`);let n=e.metadata;return Object.freeze({pluginId:E(e,`pluginId`),capabilities:Object.freeze({request:k(t,`request`),remove:k(t,`remove`)}),...M(`metadata`,n===void 0?void 0:vn(n,`workspace provider metadata`))})}function _n(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace removal field`);return Object.freeze({actionLabel:j(e,`actionLabel`),confirmation:j(e,`confirmation`),precondition:j(e,`precondition`)})}}function vn(e,t){if(!w(e)||Array.isArray(e))throw Error(`Invalid ${t} field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,yn(n,t)])))}function yn(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>yn(e,t)));if(w(e))return vn(e,t);throw Error(`Invalid ${t} field`)}function bn(e){if(!w(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Bi(e.uploads);return Object.freeze({...M(`uploads`,t===void 0?void 0:Object.freeze({...t}))})}function xn(e){let t=T(e),n=D(t,`name`),r=oa(t.persisted,`persisted`),i=D(t,`parentSessionPath`),a=D(t,`archivedAt`);return{id:E(t,`id`),path:E(t,`path`),cwd:E(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:E(t,`created`),modified:E(t,`modified`),messageCount:O(t,`messageCount`),firstMessage:E(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a}}}function Sn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Cn(e){if(e!==void 0)return{id:E(T(e),`id`)}}function wn(e){let t=T(e),n=Cn(t.dismiss);return{severity:Sn(t.severity),message:E(t,`message`),...M(`source`,D(t,`source`)),...M(`path`,D(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Tn(e){return e===void 0?{}:{warnings:A(wn)(e)}}function En(e){let t=T(e);return{value:hr(t,`value`,128),label:hr(t,`label`,Ot),...M(`detail`,gr(t,`detail`,Ot))}}function Dn(e){let t=T(e),n=Dr(t.options,En,12,`options`);Ln(n.map(e=>e.value),`ask option value`);let r=oa(t.multiple,`multiple`);return{id:hr(t,`id`,128),question:hr(t,`question`,Ot),...M(`detail`,gr(t,`detail`,Ot)),options:n,...r===void 0?{}:{multiple:r}}}function On(e){let t=T(e),n=Dr(t.questions,Dn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Ln(n.map(e=>e.id),`ask question id`),{askId:hr(t,`askId`,128),askedAt:j(t,`askedAt`),questions:n}}function kn(e){return e===void 0?{}:{pendingAsk:On(e)}}function An(e){let t=T(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:On(t.ask)}}function jn(e){let t=T(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:hr(t,`askId`,128),reason:Mn(t.reason)}}function Mn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Nn(e){let t=T(e),n=Dn(t.question),r=Dr(t.values,Or,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=gr(t,`otherText`,kt),o=k(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 Pn(e){let t=T(e),n=Dr(t.questions,Nn,20,`questions`),r=kr(t,`answeredCount`),i=$t(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:hr(t,`askId`,128),reason:Mn(t.reason),askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:j(t,`summary`)}}function Fn(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:Pn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Jn(t.sessionStatus)}}function In(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Kn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Jn(t.sessionStatus)}}function Ln(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Rn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function zn(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function Bn(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function Vn(e){let t=Or(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Hn(e){let t=T(e),n=Rn(t.kind),r=t.options===void 0?void 0:Dr(t.options,Vn,24,`options`);if(r!==void 0&&Ln(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:hr(t,`dialogId`,128),kind:n,title:hr(t,`title`,At),...M(`message`,gr(t,`message`,At)),...r===void 0?{}:{options:r},...M(`placeholder`,gr(t,`placeholder`,At)),askedAt:j(t,`askedAt`),...M(`timeoutAt`,qn(t,`timeoutAt`)),runScoped:k(t,`runScoped`)}}function Un(e){if(e===void 0)return{};let t=A(Hn)(e);return Ln(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Wn(e){let t=T(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Hn(t.dialog)}}function Gn(e){let t=T(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=zn(t.reason),r=t.answer===void 0?void 0:Bn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:hr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Kn(e){let t=T(e),n=zn(t.reason),r=t.answer===void 0?void 0:Bn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:hr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`)}}function qn(e,t){let n=D(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function Jn(e){let t=T(e);return{sessionId:E(t,`sessionId`),...M(`persisted`,oa(t.persisted,`persisted`)),isStreaming:k(t,`isStreaming`),isCompacting:k(t,`isCompacting`),isBashRunning:k(t,`isBashRunning`),pendingMessageCount:O(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:A(Hr)(t.queuedMessages),...M(`messageCount`,Ua(t,`messageCount`)),tokens:Ur(t.tokens),cost:O(t,`cost`),...Gr(t.model),...di(t.contextUsage),...M(`thinkingLevel`,D(t,`thinkingLevel`)),...Tn(t.warnings),...kn(t.pendingAsk),...Un(t.pendingDialogs)}}function Yn(e){let t=T(e);return{seq:O(t,`seq`),partial:t.partial??null}}function Xn(e){let t=T(e),n=t.subtasks===void 0?[]:A(Xn)(t.subtasks);return{id:E(t,`id`),title:E(t,`title`),status:E(t,`status`),...M(`verificationContract`,D(t,`verificationContract`)),...n.length===0?{}:{subtasks:n}}}function Zn(e){let t=T(e);return{id:E(t,`id`),objective:E(t,`objective`),status:E(t,`status`),path:E(t,`path`),sisyphus:k(t,`sisyphus`),autoContinue:k(t,`autoContinue`),...M(`createdAt`,D(t,`createdAt`)),...M(`updatedAt`,D(t,`updatedAt`)),...M(`currentTaskId`,D(t,`currentTaskId`)),...M(`stopReason`,D(t,`stopReason`)),...M(`pauseReason`,D(t,`pauseReason`)),...M(`verificationContract`,D(t,`verificationContract`)),...M(`tokensUsed`,Ua(t,`tokensUsed`)),...M(`activeSeconds`,Ua(t,`activeSeconds`)),tasks:A(Xn)(t.tasks),completedTaskCount:O(t,`completedTaskCount`),totalTaskCount:O(t,`totalTaskCount`)}}function Qn(e){let t=T(e);return{goals:A(Zn)(t.goals),directory:E(t,`directory`),generatedAt:E(t,`generatedAt`)}}function $n(e){let t=T(e),n=A(Jn)(t.statuses),r=new Set;for(let e of n){if(r.has(e.sessionId))throw Error(`Duplicate session status in catalog`);r.add(e.sessionId)}return{statuses:n,generatedAt:E(t,`generatedAt`)}}function er(e){let t=T(e),n=kr(t,`catalogRevision`),r=Dr(t.sessions,fr,Tt,`sessions`);if(pr(r),mr(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:hr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function tr(e){let t=T(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=hr(t,`sessionId`,512),r=hr(t,`cwd`,Et),i=_r(t,`catalogRevision`),a=t.unread===null?null:fr(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:hr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function nr(e){let t=T(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=D(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:rr(t.activity)}}function rr(e){let t=T(e);return{sessionId:j(t,`sessionId`),phase:ar(t,`phase`),label:j(t,`label`),...M(`detail`,D(t,`detail`)),at:j(t,`at`),...M(`startup`,ir(t))}}function ir(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function ar(e,t){let n=E(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function or(e){let t=T(e);switch(t.type){case`message.append`:return{type:`message.append`,message:cr(t,`message`),...M(`clientMessageId`,D(t,`clientMessageId`)),...t.echo===!0?{echo:!0}:{}};case`assistant.delta`:return{type:`assistant.delta`,text:E(t,`text`)};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:E(t,`text`)};case`tool.start`:return{type:`tool.start`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),summary:E(t,`summary`),...M(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),...M(`content`,t.content),...M(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),isError:k(t,`isError`),...M(`content`,t.content),...M(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:E(t,`command`),...M(`excludeFromContext`,oa(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:E(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...M(`output`,D(t,`output`)),...M(`exitCode`,lr(t,`exitCode`)),...M(`cancelled`,oa(t.cancelled,`cancelled`)),...M(`truncated`,oa(t.truncated,`truncated`)),...M(`fullOutputPath`,D(t,`fullOutputPath`)),...M(`isError`,oa(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...M(`message`,t.message)};case`status.update`:return{type:`status.update`,status:Jn(t.status)};case`activity.update`:return{type:`activity.update`,activity:rr(t.activity)};case`command.output`:return ur(t);case`session.error`:return{type:`session.error`,message:E(t,`message`)};case`session.name`:return dr(t);case`session.created`:return{type:`session.created`,session:xn(t.session)};case`pi.event`:return{type:`pi.event`,eventType:E(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function sr(e){let t=T(e);switch(t.type){case`status.update`:return{type:`status.update`,status:Jn(t.status)};case`activity.update`:return{type:`activity.update`,activity:rr(t.activity)};case`session.name`:return dr(t);case`session.created`:return{type:`session.created`,session:xn(t.session)};case`terminal.created`:return{type:`terminal.created`,terminal:Si(t.terminal)};case`terminal.exited`:return{type:`terminal.exited`,terminal:Si(t.terminal)};case`terminal.closed`:return{type:`terminal.closed`,terminalId:j(t,`terminalId`),cwd:j(t,`cwd`)};case`machine.status`:return{type:`machine.status`,status:Ei(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function cr(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function lr(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function ur(e){let t=E(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:E(e,`message`)}}function dr(e){return{type:`session.name`,sessionId:j(e,`sessionId`),...M(`name`,D(e,`name`))}}function fr(e){let t=T(e),n=hr(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:hr(t,`sessionId`,512),cwd:hr(t,`cwd`,Et),completionOrder:_r(t,`completionOrder`),completedAt:n}}function pr(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 mr(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 hr(e,t,n){let r=j(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function gr(e,t,n){let r=D(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 _r(e,t){let n=kr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function vr(e){let t=T(e),n=br(t.summary),r=Dr(t.notifications,xr,100,`notifications`);if(Ar(r),jr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Nr(r))throw Error(`Notification snapshot severity mismatch`);let i=Sr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:j(t,`daemonInstanceId`),catalogRevision:kr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function yr(e){let t=T(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=br(t.summary),r=Sr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Cr(t.delta);if(i.kind===`cleared`&&!Mr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:j(t,`daemonInstanceId`),catalogRevision:kr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function br(e){let t=T(e),n=kr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=kr(t,`discardedCount`),i=Tr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:j(t,`sessionId`),cwd:j(t,`cwd`),inboxRevision:kr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function xr(e){let t=T(e),n=E(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=E(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=kr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:j(t,`id`),message:n,truncated:k(t,`truncated`),severity:wr(t.severity),receivedAt:r,order:i}}function Sr(e){let t=T(e);return{order:kr(t,`order`),overflowWatermark:kr(t,`overflowWatermark`)}}function Cr(e){let t=T(e);switch(t.kind){case`added`:{let e=D(t,`evictedNotificationId`);return{kind:`added`,notification:xr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Dr(t.notificationIds,Or,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:Er(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function wr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Tr(e){return e===void 0?void 0:wr(e)}function Er(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 Dr(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 Or(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function j(e,t){let n=E(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function kr(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 Ar(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 jr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Mr(e){return e.retainedCount===0&&e.discardedCount===0}function Nr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Pr(e){let t=T(e),n=t.skippedBusySessionIds===void 0?void 0:$t(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:E(t,`generatedAt`),thresholds:zr(t.thresholds),projects:A(Br)(t.projects),totals:Vr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Fr(e){let t=T(e);return{...Pr(t),archivedSessionIds:$t(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:$t(t.deletedSessionIds,`deletedSessionIds`)}}function Ir(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:$t(t.archivedSessionIds,`archivedSessionIds`),failures:A(Rr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Lr(e){let t=T(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:$t(t.deletedSessionIds,`deletedSessionIds`),failures:A(Rr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Rr(e){let t=T(e);return{sessionId:E(t,`sessionId`),error:E(t,`error`)}}function zr(e){let t=T(e);return{...M(`archiveIdleDays`,Ua(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,Ua(t,`deleteArchivedDays`))}}function Br(e){let t=T(e);return{cwd:E(t,`cwd`),archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Vr(e){let t=T(e);return{archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Hr(e){let t=T(e),n=E(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:E(t,`text`),...M(`clientMessageId`,D(t,`clientMessageId`))}}function Ur(e){let t=T(e);return{input:O(t,`input`),output:O(t,`output`),cacheRead:O(t,`cacheRead`),cacheWrite:O(t,`cacheWrite`),total:O(t,`total`)}}function Wr(e){let t=T(e);return{...M(`provider`,D(t,`provider`)),...M(`id`,D(t,`id`)),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ua(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Gr(e){return e===void 0?{}:{model:Wr(e)}}function Kr(e){let t=T(e);return{models:A(Wr)(t.models)}}function qr(e){let t=T(e);return{provider:E(t,`provider`),id:E(t,`id`),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ua(t,`contextWindow`)),...M(`reasoning`,t.reasoning),enabled:k(t,`enabled`)}}function Jr(e){let t=T(e);return{models:A(qr)(t.models)}}function Yr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Xr(e){let t=T(e);return{levels:A(Yr)(t.levels)}}function Zr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Qr(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 $r(e){let t=T(e),n=t.source===void 0?void 0:Qr(t.source);return{configured:k(t,`configured`),...M(`source`,n),...M(`label`,D(t,`label`))}}function ei(e){let t=T(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:E(t,`id`),name:E(t,`name`),authType:Zr(t.authType),status:$r(t.status),...n===void 0?{}:{loginFlow:n}}}function ti(e){let t=T(e);return{providers:A(ei)(t.providers)}}function ni(e){let t=T(e);return{flowId:E(t,`flowId`),providerId:E(t,`providerId`),providerName:E(t,`providerName`),status:ri(t.status),progress:A(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,D(t,`error`)),...M(`auth`,ii(t.auth)),...M(`prompt`,oi(t.prompt)),...M(`select`,ci(t.select)),...M(`info`,li(t.info))}}function ri(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ii(e){if(e===void 0)return;let t=T(e);return{url:E(t,`url`),...M(`instructions`,D(t,`instructions`)),...M(`deviceCode`,ai(t.deviceCode))}}function ai(e){if(e===void 0)return;let t=T(e);return{userCode:E(t,`userCode`),...M(`intervalSeconds`,Ua(t,`intervalSeconds`)),...M(`expiresInSeconds`,Ua(t,`expiresInSeconds`))}}function oi(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),promptType:si(t.promptType),...M(`placeholder`,D(t,`placeholder`)),...M(`allowEmpty`,Ha(t,`allowEmpty`))}}function si(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function ci(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),options:A(Aa)(t.options)}}function li(e){if(e!==void 0)return A(e=>{let t=T(e);return{message:E(t,`message`),...M(`links`,t.links===void 0?void 0:A(ui)(t.links))}})(e)}function ui(e){let t=T(e);return{url:E(t,`url`),...M(`label`,D(t,`label`))}}function di(e){if(e===void 0)return{};let t=T(e);return{contextUsage:{tokens:Wa(t,`tokens`),contextWindow:O(t,`contextWindow`),percent:Wa(t,`percent`)}}}function fi(e){let t=T(e),n=E(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:E(t,`name`),source:n,...M(`description`,D(t,`description`))}}function pi(e){let t=T(e),n=E(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:E(t,`path`),kind:n}}function mi(e){let t=T(e);return{path:E(t,`path`),entries:A(hi)(t.entries),scannedAt:E(t,`scannedAt`),truncated:k(t,`truncated`)}}function hi(e){let t=T(e),n=E(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:E(t,`name`),path:E(t,`path`),type:n,...M(`size`,Ua(t,`size`)),...M(`modifiedAt`,D(t,`modifiedAt`))}}function gi(e){let t=T(e),n=E(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:E(t,`path`),...M(`language`,D(t,`language`)),...M(`mediaType`,bi(t.mediaType)),...M(`mimeType`,D(t,`mimeType`)),encoding:n,size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),content:E(t,`content`),truncated:k(t,`truncated`),binary:k(t,`binary`)}}function _i(e){let t=T(e);return{path:E(t,`path`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),created:k(t,`created`)}}function vi(e){let t=T(e);return{path:E(t,`path`),existed:k(t,`existed`)}}function yi(e){let t=T(e);return{fromPath:E(t,`fromPath`),toPath:E(t,`toPath`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`)}}function bi(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function xi(e){let t=T(e),n=t.decision;if(n!==!0&&n!==!1&&n!==null)throw Error(`Invalid workspace trust decision`);return{path:E(t,`path`),decision:n,trusted:k(t,`trusted`)}}function Si(e){let t=T(e);return{id:E(t,`id`),cwd:E(t,`cwd`),name:E(t,`name`),createdAt:E(t,`createdAt`),exited:k(t,`exited`),...M(`exitCode`,Ua(t,`exitCode`)),...M(`commandRunId`,D(t,`commandRunId`))}}function Ci(e){let t=T(e);return{id:E(t,`id`),origin:E(t,`origin`),projectId:E(t,`projectId`),workspaceId:E(t,`workspaceId`),terminalId:E(t,`terminalId`),title:E(t,`title`),command:E(t,`command`),status:wi(t.status),...M(`exitCode`,Ua(t,`exitCode`)),createdAt:E(t,`createdAt`),...M(`startedAt`,D(t,`startedAt`)),...M(`completedAt`,D(t,`completedAt`)),metadata:Ti(t.metadata,`metadata`)}}function wi(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Ti(e,t){let n=T(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 Ei(e){let t=Pt(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Di(e){let t=T(e),n=t.enabled===!0,r=typeof t.disabledReason==`string`?t.disabledReason:void 0,i=typeof t.latest==`string`?t.latest:void 0,a=typeof t.branch==`string`?t.branch:void 0;return n?{enabled:!0,current:E(t,`current`),latest:i,available:t.available===!0,branch:a,checkedAt:E(t,`checkedAt`)}:{enabled:!1,current:``,latest:i,available:!1,branch:a,checkedAt:E(t,`checkedAt`),...r===void 0?{}:{disabledReason:r}}}function Oi(e){let t=T(e);return{goalId:E(t,`goalId`),archivedPath:typeof t.archivedPath==`string`?t.archivedPath:``,alreadyArchived:t.alreadyArchived===!0,agentMayRecreate:t.agentMayRecreate===!0}}function ki(e){let t=T(e);return{hub:ji(t.hub),machines:A(Mi)(t.machines)}}function Ai(e){let t=T(e),n=E(t,`operation`);if(n!==`restart`&&n!==`update`)throw Error(`Invalid fleet operation`);return{operation:n,hub:ji(t.hub),outcomes:A(Ni)(t.outcomes)}}function ji(e){let t=T(e);return{machineId:E(t,`machineId`),name:E(t,`name`)}}function Mi(e){let t=T(e),n=E(t,`kind`);if(n!==`local`&&n!==`remote`)throw Error(`Invalid machine kind`);return{...ji(e),kind:n,online:t.online===!0,...M(`version`,D(t,`version`)),...M(`piVersion`,D(t,`piVersion`)),...M(`error`,D(t,`error`))}}function Ni(e){let t=T(e);return{...ji(e),started:t.started===!0,...M(`error`,D(t,`error`))}}function Pi(e){let t=T(e);return{path:E(t,`path`),exists:k(t,`exists`),config:Fi(t.config),effectiveConfig:Fi(t.effectiveConfig),envOverrides:Gi(t.envOverrides)}}function Fi(e){let t=T(e);return{...M(`host`,D(t,`host`)),...M(`port`,Ua(t,`port`)),...M(`allowedHosts`,Li(t.allowedHosts)),...M(`shortcuts`,Ui(t.shortcuts)),...M(`plugins`,Wi(t.plugins)),...M(`pathAccess`,Ri(t.pathAccess)),...M(`uploads`,Bi(t.uploads)),...M(`maxUploadBytes`,Ua(t,`maxUploadBytes`)),...M(`agent`,Ii(t.agent)),...M(`spawnSessions`,Ha(t,`spawnSessions`)),...M(`subsessions`,Ha(t,`subsessions`)),...M(`askUser`,Ha(t,`askUser`))}}function Ii(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,D(e,`command`)),...M(`dir`,D(e,`dir`))}}}function Li(e){if(e!==void 0){if(e===!0)return!0;if(Vi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function Ri(e){if(e===void 0)return;if(!w(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,zi(t,`pathAccess.allowedPaths`))}}function zi(e,t){if(e!==void 0){if(Hi(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Bi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,D(e,`defaultFolder`))}}}function Vi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Hi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ui(e){if(e!==void 0){if(!w(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 Wi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!w(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&&(!w(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Gi(e){let t=T(e);return{host:k(t,`host`),port:k(t,`port`),allowedHosts:k(t,`allowedHosts`),spawnSessions:k(t,`spawnSessions`),subsessions:k(t,`subsessions`),askUser:k(t,`askUser`)}}function Ki(e){let t=T(e);return{packages:A(Ji)(t.packages)}}function qi(e){let t=T(e),n=D(t,`source`),r=t.scope===void 0?void 0:Yi(t.scope),i=oa(t.removed,`removed`);return{action:Xi(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:A(Ji)(t.packages)}}function Ji(e){let t=T(e);return{source:E(t,`source`),scope:Yi(t.scope),filtered:k(t,`filtered`),...M(`installedPath`,D(t,`installedPath`))}}function Yi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Xi(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Zi(e){let t=T(e),n=A(Qi)(t.plugins);if(t.lifecycleVersion===void 0)return{lifecycleVersion:1,plugins:n,diagnostics:[],serverRuntime:{status:`incompatible`,restartRequired:!1,message:`PI WEB does not support plugin lifecycle diagnostics. Update and restart PI WEB, then try again.`,recovery:ia()}};if(t.lifecycleVersion!==1)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:1,plugins:n,diagnostics:A(ta)(t.diagnostics),serverRuntime:na(t.serverRuntime)}}function Qi(e){let t=T(e),n=E(t,`id`),r=t.server===void 0?void 0:$i(t.server,n);return{id:n,...M(`module`,D(t,`module`)),source:E(t,`source`),scope:aa(t.scope),machineSpecific:oa(t.machineSpecific,`machineSpecific`)??!1,enabled:k(t,`enabled`),discovered:oa(t.discovered,`discovered`)??!0,conflict:oa(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function $i(e,t){let n=T(e),r=n.state,i=n.phase;if(r!==`active`&&r!==`failed`&&r!==`incompatible`&&r!==`disabled`&&r!==`missing`&&r!==`unknown`)throw Error(`Invalid PI WEB server plugin state`);if(i!==void 0&&i!==`import`&&i!==`activate`&&i!==`validate`&&i!==`start`&&i!==`health`&&i!==`stop`)throw Error(`Invalid PI WEB server plugin phase`);let a=n.health===void 0?void 0:ea(n.health),o=E(n,`disableCommand`);if(o!==Zt(t))throw Error(`Invalid PI WEB server plugin recovery command`);return{state:r,...M(`desiredRevision`,D(n,`desiredRevision`)),...M(`activeRevision`,D(n,`activeRevision`)),...i===void 0?{}:{phase:i},...M(`message`,D(n,`message`)),...a===void 0?{}:{health:a},staleRevision:k(n,`staleRevision`),restartRequired:k(n,`restartRequired`),disableCommand:o}}function ea(e){let t=T(e),n=t.status;if(n!==`healthy`&&n!==`degraded`&&n!==`unhealthy`)throw Error(`Invalid PI WEB server plugin health status`);return{status:n,...M(`message`,D(t,`message`))}}function ta(e){let t=T(e),n=t.kind,r=t.snapshot;if(n!==`conflict`&&n!==`discovery`)throw Error(`Invalid PI WEB plugin diagnostic kind`);if(r!==`desired`&&r!==`active`)throw Error(`Invalid PI WEB plugin diagnostic snapshot`);return{kind:n,snapshot:r,source:E(t,`source`),message:E(t,`message`),...M(`pluginId`,D(t,`pluginId`))}}function na(e){let t=T(e),n=t.status,r=t.safeStart,i=t.desiredSafeStart;if(n!==`available`&&n!==`unavailable`&&n!==`incompatible`)throw Error(`Invalid PI WEB server-plugin runtime status`);if(r!==void 0&&r!==`bundled-only`&&r!==`none`)throw Error(`Invalid PI WEB server-plugin safe-start state`);if(i!==void 0&&i!==`off`&&i!==`bundled-only`&&i!==`none`)throw Error(`Invalid desired PI WEB server-plugin safe-start state`);return{status:n,...r===void 0?{}:{safeStart:r},...i===void 0?{}:{desiredSafeStart:i},restartRequired:k(t,`restartRequired`),...M(`message`,D(t,`message`)),recovery:ra(t.recovery)}}function ra(e){let t=T(e),n={showSafeStart:E(t,`showSafeStart`),bundledOnly:E(t,`bundledOnly`),noServerPlugins:E(t,`noServerPlugins`),clearSafeStart:E(t,`clearSafeStart`)};if(n.showSafeStart!==Xt.showSafeStart||n.bundledOnly!==Xt.bundledOnly||n.noServerPlugins!==Xt.noServerPlugins||n.clearSafeStart!==Xt.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function ia(){return{...Xt}}function aa(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function oa(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function sa(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:la(t.components),release:ma(t.release),commands:ha(t.commands),messages:A(ga)(t.messages)}}function ca(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ua(t.components),capabilities:va(t.capabilities)}}function la(e){let t=T(e);return{web:fa(t.web),sessiond:fa(t.sessiond)}}function ua(e){let t=T(e);return{web:da(t.web),sessiond:da(t.sessiond)}}function da(e){let t=T(e);return{component:_a(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`piVersion`,D(t,`piVersion`)),available:k(t,`available`),capabilities:va(t.capabilities),...M(`error`,D(t,`error`))}}function fa(e){let t=T(e);return{component:_a(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`installedVersion`,D(t,`installedVersion`)),...M(`piVersion`,D(t,`piVersion`)),stale:k(t,`stale`),available:k(t,`available`),...M(`installation`,pa(t.installation)),...M(`error`,D(t,`error`))}}function pa(e){if(e===void 0)return;let t=T(e),n=E(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`,D(t,`path`)),...M(`source`,D(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,D(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function ma(e){let t=T(e);return{packageName:E(t,`packageName`),...M(`latestVersion`,D(t,`latestVersion`)),updateAvailable:k(t,`updateAvailable`),...M(`checkedAt`,D(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,D(t,`error`))}}function ha(e){let t=T(e);return{...M(`update`,D(t,`update`)),...M(`restart`,D(t,`restart`)),...M(`restartWeb`,D(t,`restartWeb`)),...M(`restartSessiond`,D(t,`restartSessiond`)),...M(`status`,D(t,`status`))}}function ga(e){let t=T(e);return{id:E(t,`id`),severity:ya(t.severity),title:E(t,`title`),body:E(t,`body`),...M(`command`,D(t,`command`))}}function _a(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function va(e){let t=Ht(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function ya(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function ba(e){let t=T(e),n=E(t,`type`);if(n===`unsupported`)return{type:n,message:E(t,`message`)};if(n===`select`)return{type:n,requestId:E(t,`requestId`),title:E(t,`title`),options:A(Aa)(t.options)};if(n===`tree`)return{type:n,tree:xa(t.tree)};if(n===`done`)return{type:n,...M(`message`,D(t,`message`)),...ja(t.session),...M(`promptDraft`,D(t,`promptDraft`))};throw Error(`Invalid command result type`)}function xa(e){let t=T(e),n=A(Sa)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Da(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:ka(t.activePathIds,`activePathIds`)}}function Sa(e){let t=T(e);return{id:Oa(t,`id`),parentId:Da(t,`parentId`),kind:Ca(t.kind),summary:E(t,`summary`),...M(`timestamp`,D(t,`timestamp`)),...M(`label`,D(t,`label`))}}function Ca(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 wa(e){let t=T(e),n=k(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Ea(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 Ea(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,D(t,`editorText`))}}function Ta(e){let t=T(e),n=k(t,`cancelled`);return n?(Ea(t,`session`,`session tree fork cancellation result`),Ea(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:xn(t.session),...M(`promptDraft`,D(t,`promptDraft`))}}function Ea(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Da(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 Oa(e,t){let n=E(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function ka(e,t){let n=$t(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Aa(e){let t=T(e);return{value:E(t,`value`),label:E(t,`label`),...M(`description`,D(t,`description`))}}function ja(e){return e===void 0?{}:{session:xn(e)}}function Ma(e){if(T(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function Na(e){let t=T(e);return A(Pa)(t.attachments)}function Pa(e){let t=T(e);return{path:E(t,`path`),mimeType:E(t,`mimeType`),size:O(t,`size`)}}function Fa(e){if(T(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Ia(e){let t=T(e);if(t.aborted!==!0)throw Error(`Expected aborted response`);let n=t.discarded;return{aborted:!0,discarded:Array.isArray(n)?A(Hr)(n):[]}}function La(e){if(T(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Ra(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:$t(t.sessionIds,`sessionIds`),r=Ua(t,`archivedCount`),i=Ua(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function za(e){if(T(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Ba(e){if(T(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Va(e){if(T(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ha(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Ua(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Wa(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 Ga(e){if(!w(e))return{runs:[]};let t=e.runs;if(!Array.isArray(t))return{runs:[]};let n=[];for(let e of t){if(!w(e))continue;let t=e.sessionId,r=e.cwd,i=e.interruptedAt;typeof t!=`string`||t===``||typeof r!=`string`||typeof i!=`string`||n.push({sessionId:t,cwd:r,interruptedAt:i})}return{runs:n}}function Ka(e){if(!w(e))return{subsessions:[],toolRuns:[]};let t=[],n=e.subsessions;if(Array.isArray(n))for(let e of n){if(!w(e))continue;let n=e.sessionId,r=e.cwd,i=e.status;typeof n!=`string`||n===``||typeof r==`string`&&(i!==`working`&&i!==`idle`&&i!==`error`&&i!==`unknown`||t.push({sessionId:n,cwd:r,status:i}))}return{subsessions:t,toolRuns:Za(e.toolRuns)}}function qa(e){let t=Jn(e);return{recalled:w(e)&&e.recalled===!0,status:t}}function Ja(e){if(!w(e)||!Array.isArray(e.tasks))return[];let t=[];for(let n of e.tasks){if(!w(n))continue;let e=n.id,r=n.name,i=n.status;typeof e!=`string`||e===``||t.push({id:e,name:typeof r==`string`&&r!==``?r:e,command:typeof n.command==`string`?n.command:``,status:typeof i==`string`?i:`unknown`,...typeof n.startedAt==`string`?{startedAt:n.startedAt}:{},...typeof n.endedAt==`string`?{endedAt:n.endedAt}:{},...typeof n.durationMs==`number`?{durationMs:n.durationMs}:{},...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{},bytesWritten:typeof n.bytesWritten==`number`?n.bytesWritten:0,hasOutput:n.hasOutput===!0})}return t}function Ya(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function Xa(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function Za(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!w(n))continue;let e=n.runId,r=n.agent,i=n.status,a=n.elapsedMs,o=n.startedAt;if(typeof e!=`string`||e===``||typeof r!=`string`||r===``||i!==`running`&&i!==`done`&&i!==`failed`&&i!==`unknown`||typeof a!=`number`||typeof o!=`string`)continue;let s=n.lastActivity,c=n.task,l=n.model,u=n.toolCount;t.push({runId:e,agent:r,status:i,elapsedMs:a,startedAt:o,...typeof s==`string`&&s!==``?{lastActivity:s}:{},...typeof c==`string`&&c!==``?{task:c}:{},...typeof l==`string`&&l!==``?{model:l}:{},...typeof u==`number`?{toolCount:u}:{},hasOutput:n.hasOutput===!0})}return t}function Qa(e){return typeof e==`string`?e:e.id}function $a(e){return typeof e==`string`?void 0:e.cwd}function eo(e,t,n=`local`){let r=new URLSearchParams,i=$a(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(Qa(e))}/messages${a===``?``:`?${a}`}`}function to(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`),vt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function no(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`),`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`}function ro(e,t,n,r){return vt(no(e,t,n,r))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function io(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(e.id)}`}function P(e,t,n=`local`){return`${io(e,n)}/${t}`}function ao(e,t,n=`local`){return`${P(e,t,n)}${oo(e)}`}function oo(e){return`?${new URLSearchParams({cwd:e.cwd}).toString()}`}function F(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function so(e){return JSON.stringify({sessions:e.map(co)})}function co(e){return{id:e.id,cwd:e.cwd}}function lo(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var uo={piWebStatus:(e=`local`)=>C(lo(e),sa),checkForUpdates:(e=`local`)=>C(`${lo(e)}?refresh=1`,sa,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,ca)},fo={machines:()=>C(`api/machines`,tn),addMachine:e=>C(`api/machines`,nn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),updateMachine:(e,t)=>C(`api/machines/${encodeURIComponent(e)}`,nn,{method:`PATCH`,body:JSON.stringify(t)}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,rn),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,an,t?{cache:`no-store`}:{})};function po(e){return e===void 0?`api/config`:`${N(e)}/config`}function mo(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var ho={config:e=>C(po(e),Pi),saveConfig:(e,t)=>C(po(t),Pi,{method:`PUT`,body:JSON.stringify({config:e})})};function go(e){let t=Po(e)?e:{},n=t.started===!0,r=typeof t.error==`string`?t.error:void 0;return r===void 0?{started:n}:{started:n,error:r}}var _o={plugins:e=>C(mo(e),Zi)},vo={status:()=>C(`api/pi-web/update/status`,Di,{cache:`no-store`}),apply:()=>C(`api/pi-web/update/apply`,go,{method:`POST`,body:JSON.stringify({})})},yo={report:()=>C(`api/pi-web/fleet`,ki,{cache:`no-store`}),run:(e,t)=>C(`api/pi-web/fleet/run`,Ai,{method:`POST`,body:JSON.stringify({operation:e,...t===void 0?{}:{machineIds:t}})})};function bo(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var xo={packages:e=>C(bo(``,e),Ki),install:(e,t)=>{let n={source:e};return C(bo(`install`,t),qi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(bo(`remove`,n),qi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(bo(`update`,t),qi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},So={machineStatus:(e=`local`)=>C(`${N(e)}/status`,Ei)},Co={projects:(e=`local`)=>C(`${N(e)}/projects`,A(ln)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,ln,{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)}`,A(pi))};function wo(e,t=`local`){return C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=dn(t);if(n.projectId!==e)throw Error(`Workspace resolution did not match the requested project`);return n})}var To={workspaceResolution:wo,workspaces:async(e,t=`local`)=>[...(await wo(e,t)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ci,{method:`DELETE`,body:JSON.stringify(i)})},archiveWorkspaceGoal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals/${encodeURIComponent(n)}/archive`,Oi,{method:`POST`,body:JSON.stringify({})}),workspaceGoals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals`,Qn,{cache:`no-store`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,mi),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,gi),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,_i,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,vi,{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()}`,yi,{method:`POST`})}},Eo={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,A(xn)),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,er,{cache:`no-store`}),statusCatalog:(e=`local`)=>C(`${N(e)}/sessions/statuses`,$n,{cache:`no-store`}),interruptedRuns:(e=`local`)=>C(`${N(e)}/sessions/interrupted`,Ga,{cache:`no-store`}),subsessions:(e,t=`local`)=>C(`${P(e,`subsessions`,t)}?cwd=${encodeURIComponent(e.cwd)}`,Ka,{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),er,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(ao(e,`notifications`,t),vr),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),vr,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),vr,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,xn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,Pr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Fr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Ir,{method:`POST`,body:so(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,Lr,{method:`POST`,body:so(e)}),messages:(e,t,n=`local`)=>C(eo(e,t,n),en),status:(e,t=`local`)=>C(ao(e,`status`,t),Jn),streamSnapshot:(e,t=`local`)=>C(ao(e,`stream-snapshot`,t),Yn),backgroundTasks:(e,t=`local`)=>C(`${P(e,`background-tasks`,t)}?cwd=${encodeURIComponent(e.cwd)}`,Ja,{cache:`no-store`}),backgroundTaskOutput:(e,t,n=`local`)=>C(`${P(e,`background-tasks/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,Ya,{cache:`no-store`}),subagentRunOutput:(e,t,n=`local`)=>C(`${P(e,`subagent-runs/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,Xa,{cache:`no-store`}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),Jn,{method:`POST`,body:F(e)}),recallQueuedMessage:(e,t,n=`local`)=>C(P(e,`queue/clear`,n),qa,{method:`POST`,body:F(e,{text:t.text,kind:t.kind,...t.clientMessageId===void 0?{}:{clientMessageId:t.clientMessageId}})}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),Jn,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Fn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Fn,{method:`POST`,body:F(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(P(e,`dialogs/answer`,r),In,{method:`POST`,body:F(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(P(e,`dialogs/cancel`,n),In,{method:`POST`,body:F(e,{dialogId:t})}),models:(e,t=`local`)=>C(ao(e,`models`,t),Kr),modelCatalog:(e,t=`local`)=>C(ao(e,`models/catalog`,t),Jr),setModelEnabled:(e,t,n,r,i=`local`)=>C(P(e,`models/enabled`,i),Jr,{method:`POST`,body:F(e,{provider:t,modelId:n,enabled:r})}),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),Jn,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),Jn,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(ao(e,`thinking-levels`,t),Xr),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),Jn,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),Jn,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(ao(e,`commands`,t),A(fi)),prompt:(e,t,n,r=`local`,i,a)=>C(P(e,`prompt`,r),Ma,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{},...a===void 0?{}:{clientMessageId:a}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),Na,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),Ma,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),ba,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),ba,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),wa,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),forkTree:(e,t,n=`local`)=>ko(e,t,n),abort:(e,t=`local`)=>C(P(e,`abort`,t),Ia,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),La,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),Ra,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),Ra,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),za,{method:`POST`,body:F(e)}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),Ba,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),Va,{method:`POST`,body:F(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return C(`${N(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,ti)},startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${N(t)}/auth/api-key/interactive`,ni,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${N(t)}/auth/logout`,Ma,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${N(t)}/auth/oauth`,ni,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}`,ni),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${N(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ni,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ni,{method:`POST`})},Do={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,A(Si)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Si,{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`,Si,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ci,{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${Mo(e)}`,A(Ci)),getCommandRun:(e,t=`local`)=>jo(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ci,{method:`POST`})},Oo=class extends Error{constructor(){super(`Fork from the session tree is unavailable. Restart the session daemon to enable it.`),this.name=`SessionTreeForkUnavailableError`}};async function ko(e,t,n){let r=await fetch(vt(P(e,`tree/fork`,n)),{method:`POST`,headers:{"content-type":`application/json`},body:F(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Ao(r.status,e)?new Oo:Error(No(e)??r.statusText)}return Ta(await r.json())}function Ao(e,t){if(e!==404||!Po(t)||t.statusCode!==404||t.error!==`Not Found`)return!1;let n=t.message;return typeof n==`string`&&/^Route POST:.*\/tree\/fork not found$/i.test(n)}async function jo(e,t){let n=await fetch(vt(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(No(e)??n.statusText)}return Ci(await n.json())}}function Mo(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 No(e){if(!Po(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Po(e){return typeof e==`object`&&!!e}var Fo={files:(e,t)=>{let n=new URLSearchParams({q:e});return t.kind!==void 0&&n.set(`kind`,t.kind),t.mode!==void 0&&n.set(`mode`,t.mode),t.scope!==void 0&&n.set(`scope`,t.scope),C(`${N(t.machineId)}/projects/${encodeURIComponent(t.projectId)}/workspaces/${encodeURIComponent(t.workspaceId)}/files?${n.toString()}`,A(pi))}},Io=(e,t,n)=>`${N(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/trust`,Lo=(e,t)=>{let n=new URLSearchParams({path:t});return`${N(e)}/projects/trust?${n.toString()}`},Ro={projectTrust:(e,t=`local`)=>C(Lo(t,e),xi),workspaceTrust:(e,t,n=`local`)=>C(Io(n,e,t),xi),setWorkspaceTrust:(e,t,n,r=`local`)=>C(Io(r,e,t),xi,{method:`PUT`,body:JSON.stringify({trusted:n})})},I={...uo,...fo,...ho,..._o,...xo,...Co,...To,...Eo,...Do,...Fo,...Ro},zo=256*1024,Bo=8*1024*1024,Vo=266240,Ho=8392704,Uo=/^[a-z][a-z0-9.-]*$/u,Wo=64;function Go(e){return e.length<=128&&Uo.test(e)}function Ko(e){if(!Go(e))throw Error(`Plugin backend operation must match ${String(Uo)} and be at most 128 characters`);return e}function qo(e){if(typeof e!=`string`||e===``||e.length>512)throw Error(`Plugin backend revision must be a non-empty string of at most 512 characters`);return e}function Jo(e,t,n=zo){let r=Zo(e,new Set,t,0);if(Xo(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function Yo(e,t,n=zo){if(Xo(e)>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);let r;try{r=JSON.parse(e)}catch(e){throw Error(`${t} must be valid JSON`,{cause:e})}return Jo(r,t,n)}function Xo(e){return new TextEncoder().encode(e).byteLength}function Zo(e,t,n,r){if(r>Wo)throw Error(`${n} exceeds the maximum JSON depth of ${String(Wo)}`);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`${n} must contain only finite JSON numbers`);return e}if(Array.isArray(e)){if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i=e.map(e=>Zo(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!$o(e))throw Error(`${n} must contain only JSON values`);if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i={};for(let[a,o]of Object.entries(e))Qo(i,a,Zo(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function Qo(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function $o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function es(e,t){if(!Jt(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);let n=Ko(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}/plugin-backends/${encodeURIComponent(e.pluginId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/${encodeURIComponent(n)}`}function ts(e,t,n){let r=es(e,t);return n===void 0?vt(r):vt(r,n)}async function ns(e,t,n){let r=qo(e.backendRevision),i=Jo(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(Xo(a)>266240)throw Error(`Plugin backend request exceeds the ${String(Vo)} byte wire limit`);let o;try{o=await fetch(ts(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${os(e)}`,{cause:e})}let s=await rs(o);if(!o.ok)throw Error(as(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return Yo(s,`Plugin backend response`,Bo)}async function rs(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(Ho)} byte wire limit`);if(e.body===null){let t=await e.text();if(Xo(t)>8392704)throw is();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),is();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function is(){return Error(`Plugin backend response exceeds the ${String(Ho)} byte wire limit`)}function as(e){try{let t=JSON.parse(e);return ss(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function os(e){return e instanceof Error?e.message:String(e)}function ss(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cs(e,t=`local`){let n=`?${new URLSearchParams({cwd:e.cwd}).toString()}`;return new WebSocket(yt(`${ds(t)}/sessions/${encodeURIComponent(e.id)}/events${n}`))}function ls(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(yt(`${ds(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function us(e=`local`){return new WebSocket(yt(`${ds(e)}/events`))}function ds(e){return`api/machines/${encodeURIComponent(e)}`}var fs=`.pi-web/uploads`,ps=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},ms=class extends Error{constructor(e,t){super(Ts(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function hs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function gs(e,t){return e.uploads?.defaultFolder??t}function _s(e,t){let n=Os(e,`upload destination`,{allowEmpty:!0}),r=Os(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function vs(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`,to(e,t,n.path,xs(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Ss(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(_i(As(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(js(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new ps(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function ys(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:_s(i,e.name),loaded:0,total:e.size,percent:ws(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Cs(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 ps;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=vs(e,t,{path:p.path,file:f},{...bs(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(Ds(e,c))throw e;let t=Es(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 ms(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function bs(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 xs(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Ss(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ws(e.loaded,n),lengthComputable:e.lengthComputable}}function Cs(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:ws(i,r),done:n}}function ws(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Ts(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Es(e){return e instanceof Error?e.message:String(e)}function Ds(e,t){return t.requested||e instanceof ps}function Os(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(ks(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function ks(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function As(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function js(e){let t=Ms(e);return Ns(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Ms(e){try{return As(e)}catch{return}}function Ns(e){return typeof e==`object`&&!!e}function Ps(){return{sessions:[],workspaceGoals:[],workspaceGoalsLoading:!1,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,selectedFileLoadError:void 0,fileTreeStale:!1,selectedTerminalId:void 0,error:``}}function Fs(){return{machines:[],selfUpdate:void 0,selfUpdateApplying:!1,selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,subagents:[],backgroundTasks:[],subagentRuns:[],status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],workspaceGoals:[],workspaceGoalsLoading:!1,sessionStatuses:{},sessionActivities:{},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,selectedFileLoadError:void 0,fileTreeStale:!1,workspaceUploadBatches:{},activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function Is(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Ls=`machine.`;function Rs(e,t){if(e===``)throw Error(`Machine id is required`);if(!Jt(t))throw Error(`Invalid PI WEB plugin id: ${t}`);if(Yt(t))throw Error(`Reserved PI WEB plugin id: ${t}`);return`${Ls}${zs(e)}.${t}`}function zs(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Bs(e,t){return`${e}:${t}`}function Vs(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var Hs=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.authOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.advanceAuthOperation()}handleSlashCommand(e){let t=Gs(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){let t=this.advanceAuthOperation(),n=L(this.getState());if(e!==void 0&&e!==``){await this.openLoginProvider(e,n,t);return}this.setState({authDialog:{step:`method`,machineId:n}})}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.authOperationGeneration,{machineId:r}=t;try{let{providers:i}=await this.api.authProviders({mode:`login`,authType:e,machineId:r});if(!this.isCurrentAuthOperation(n)||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,machineId:r,authType:e,providers:i}})}catch(e){this.isCurrentAuthOperation(n)&&this.getState().authDialog===t&&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));if(r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`)){let e=this.advanceAuthOperation();await this.startLoginFlow(r,n.machineId,e)}}async openLogout(e){let t=this.advanceAuthOperation(),n=L(this.getState());try{let{providers:r}=await this.api.authProviders({mode:`logout`,machineId:n});if(!this.isCurrentAuthOperation(t))return;if(e!==void 0&&e!==``){let i=r.find(t=>t.id===e);i===void 0?this.setState({error:`No stored credentials for ${e}`}):await this.logoutProviderOnMachine(i.id,n,t);return}this.setState({authDialog:{step:`logout`,machineId:n,providers:r}})}catch(e){this.isCurrentAuthOperation(t)&&this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog;if(t?.step!==`logout`)return;let n=this.advanceAuthOperation();await this.logoutProviderOnMachine(e,t.machineId,n)}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.authOperationGeneration,i=t.flow.flowId,a=n.requestId,o={flowId:i,requestId:a};if(Us(this.inFlightResponse,o))return;let s=e??t.inputValue??``,c={...t};delete c.error,this.inFlightResponse=o,this.setState({authDialog:{...c,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,s,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Ws(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Ws(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{Us(this.inFlightResponse,o)&&(this.inFlightResponse=void 0)}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t,n){try{let{providers:r}=await this.api.authProviders({mode:`login`,machineId:t});if(!this.isCurrentAuthOperation(n))return;let i=r.filter(t=>t.id===e);if(i.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(i.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,machineId:t,providers:i}});return}let a=i[0];if(a===void 0)return;(a.authType===`oauth`||a.loginFlow===`interactive`)&&await this.startLoginFlow(a,t,n)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async logoutProviderOnMachine(e,t,n){if(this.isCurrentAuthOperation(n))try{if(await this.api.logoutProvider(e,t),!this.isCurrentAuthOperation(n))return;this.closeDialog(),this.refreshStatus(t)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async startLoginFlow(e,t,n){if(this.isCurrentAuthOperation(n))try{let r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,t):await this.api.startInteractiveApiKeyLogin(e.id,t);if(!this.isCurrentAuthOperation(n)){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){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&this.advanceAuthOperation();let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Ws(n.flow):void 0,a=Ws(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.authOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=Ws(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||Ws(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Ws(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}advanceAuthOperation(){return this.authOperationGeneration+=1,this.stopPolling(),this.authOperationGeneration}isCurrentAuthOperation(e){return e===this.authOperationGeneration}currentOAuthDialog(e,t){if(!this.isCurrentAuthOperation(e))return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=L(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(L(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Us(e,t){return e?.flowId===t.flowId&&e.requestId===t.requestId}function Ws(e){return e.prompt?.requestId??e.select?.requestId}function Gs(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 Ks(e){return e.replaceAll(`:`,`.`)}function qs(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 Js(e,t){let n=qs(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Ys(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));Xs(i,r)}function Xs(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 Zs(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:_s(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:rc(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:rc(0,n),status:`uploading`,startedAt:e.startedAt}}function Qs(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 $s(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=nc(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function ec(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...nc(r),status:`error`,error:t,completedAt:n}}function tc(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...nc(r),status:`cancelled`,error:n,completedAt:t}}function nc(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function rc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var ic=class{constructor(e,t){this.getState=e,this.setState=t}report(e){this.reported=e,this.setState({error:e})}clear(){let e=this.reported;this.reported=void 0,!(e===void 0||this.getState().error!==e)&&this.setState({error:``})}},ac=Ks(`core:workspace.files`),oc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.fileRequestGeneration=0,this.reportedError=new ic(e,t),this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??ys,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=L(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1}),this.reportedError.clear()}catch(e){this.reportedError.report(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:lc(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}}),this.reportedError.clear()}catch(e){this.reportedError.report(String(e))}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Ys(ac,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=++this.fileRequestGeneration,n=this.getState(),r=n.selectedProject,i=n.selectedWorkspace;if(r===void 0||i===void 0)return;let a={generation:t,machineId:L(n),projectId:r.id,workspaceId:i.id,path:e};this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0});try{let e=await this.api.workspaceFile(a.projectId,a.workspaceId,a.path,a.machineId);if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:e,selectedFileLoadError:void 0}),this.reportedError.clear()}catch(e){if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:void 0,selectedFileLoadError:cc(e)})}}isCurrentFileRequest(e){let t=this.getState();return e.generation===this.fileRequestGeneration&&t.selectedFilePath===e.path&&t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.reportedError.report(`Select a workspace before uploading files.`);return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=Zs({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.reportedError.report(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(tc(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:lc(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(Qs(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch($s(r,t,this.now())),this.reportedError.clear(),!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 ms)||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(sc(t)){let e=tc(n,this.now());return this.setUploadBatch(e),e}let r=cc(t),i=ec(n,r,this.now());return this.setUploadBatch(i),this.reportedError.report(r),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e}})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function sc(e){return e instanceof ps}function cc(e){return e instanceof Error?e.message:String(e)}function lc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var uc=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,machineRuntimes:fc(this.getState().machineRuntimes,r),machineStatusSnapshots:fc(this.getState().machineStatusSnapshots,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:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Ps()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async updateMachine(e,t){this.setState({error:``});try{let n=await I.updateMachine(e.id,t);return this.setState({machines:this.getState().machines.map(e=>e.id===n.id?n:e)}),n}catch(e){this.setState({error:String(e)});return}}async addMachine(e){this.setState({error:``});try{let t=await I.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await I.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:dc(this.getState().machineStatuses,e.id),machineRuntimes:dc(this.getState().machineRuntimes,e.id),machineStatusSnapshots:dc(this.getState().machineStatusSnapshots,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await I.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await I.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await I.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>I.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>I.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function dc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function fc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var pc=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let n=r.latestRefresh;t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},mc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new pc,this.api=n.api??So}refresh(e){return this.refreshes.request(e,async()=>{this.apply(e,await this.api.machineStatus(e))})}apply(e,t){let n=this.getState().machineStatusSnapshots;hc(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function hc(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}var gc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I}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})}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=L(this.getState());try{let i=await this.api.addProject(e.trim(),void 0,t,r);if(L(this.getState())!==r)return;let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i),n?.changed===!0&&await this.applyTrustChoice(i,n.trusted,r)}catch(e){L(this.getState())===r&&this.setState({error:String(e)})}}async applyTrustChoice(e,t,n){let r=this.getState().workspaces.find(e=>e.isMain);r!==void 0&&await this.api.setWorkspaceTrust(e.id,r.id,t,n)}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)}),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}},_c=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??uo,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}),vc(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 vc(e){if(e.release.error!==void 0)throw Error(`PI WEB update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`)}var yc=`pi-web:cached-new-sessions:v1`,bc=`browserCachedNew`,xc=`local`;function Sc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Cc(e,t=xc,n=Sc()){if(e.messageCount!==0||e.archived===!0)return;let r=kc(n).filter(n=>n.id!==e.id||n.machineId!==t);Ac([wc(e,t),...r],n)}function wc(e,t=xc){return{...e,browserCachedNew:!0,machineId:t}}function Tc(e,t=xc,n=Sc()){Ac(kc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Ec(e,t,n=xc,r=Sc()){let i=new Set(t.map(e=>e.id)),a=kc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Ac(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Dc(e){return e!==void 0&&Mc(e)&&e.browserCachedNew===!0}function Oc(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:xc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function kc(e=Sc()){try{let t=e?.getItem(yc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>jc(e)):[]}catch{return[]}}function Ac(e,t=Sc()){try{e.length===0?t?.removeItem(yc):t?.setItem(yc,JSON.stringify(e))}catch{}}function jc(e){if(!Nc(e))return[];let t=Pc(e,`id`),n=Pc(e,`path`),r=Pc(e,`cwd`),i=Pc(e,`created`),a=Pc(e,`modified`),o=Pc(e,`firstMessage`),s=Ic(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=Fc(e,`name`),l=Fc(e,`parentSessionPath`),u=Fc(e,`machineId`)??xc;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 Mc(e){return bc in e}function Nc(e){return typeof e==`object`&&!!e}function Pc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Fc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Ic(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Lc(e){return al(e.flatMap(Hc)).filter(e=>e.parts.length>0)}function Rc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function zc(e,t){let n=Jc(t);return n===void 0?e:{...e,meta:n}}function Bc(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,Rc(t,n)]}function Vc(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 Hc(e){if(Wc(e))return[e];if(R(e,`role`)===`bashExecution`)return[zc(Zc(e),e)];let t=R(e,`role`),n=Qc(t),r=$c(pl(e,`content`),e),i=t===`toolResult`?tl(R(e,`toolName`)??``,pl(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?Gc(a):void 0;if(o!==void 0)return o.map(t=>zc(t,e));let s=qc(e);if(n===`tool`)return[zc({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?[zc({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Uc(e);return d===void 0?u:[...u,zc(d,e)]}function Uc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return Rc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Wc(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(pl(e,`parts`))}function Gc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Kc(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 Kc(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 qc(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Jc(e){let t=Yc(pl(e,`timestamp`)),n=Xc(e),r=R(e,`thinkingLevel`);if(!(t===void 0&&n===void 0&&(r===void 0||r===``)))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function Yc(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 Xc(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 Zc(e){let t=R(e,`command`)??``,n=ml(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=pl(e,`output`);r!=null&&n.push(``,gl(r));let i=pl(e,`exitCode`);i!=null&&n.push(``,`exit ${gl(i)}`),ml(e,`cancelled`)===!0&&n.push(``,`cancelled`),ml(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function Qc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function $c(e,t){let n=el(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=pl(e,`arguments`),r=R(e,`id`),i=t===`read`?il(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:ul(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 ll(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?rl(e.text,t):e):ll(e):[n]}function el(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return nl(pl(e,`details`))}function tl(e,t){if(e===`ask_user`)return nl(pl(t,`superseded`))}function nl(e){try{return{type:`askUserRecord`,outcome:Pn(e)}}catch{return}}function rl(e,t){let n=R(t,`toolCallId`),r=pl(t,`content`),i=pl(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:ml(t,`isError`)===!0}}function il(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 al(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=ol(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&&sl(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function ol(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 sl(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=cl(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 cl(e){let t=pl(e,`preview`);if(!fl(t))return;let n=R(t,`diff`),r=R(t,`error`),i=hl(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 ll(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:ul(e)}]:[{type:`text`,text:gl(e)}]}function ul(e){if(!fl(e))return gl(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}: ${dl(t)}`).join(` · `)}function dl(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 fl(e){return typeof e==`object`&&!!e}function pl(e,t){return fl(e)?e[t]:void 0}function R(e,t){let n=pl(e,t);return typeof n==`string`?n:void 0}function ml(e,t){let n=pl(e,t);return typeof n==`boolean`?n:void 0}function hl(e,t){let n=pl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function gl(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var _l=`pi-web:prompt-draft:`;function vl(e){return`${_l}${e}`}function yl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function bl(e,t=yl()){try{return t?.getItem(vl(e))??``}catch{return``}}function xl(e,t,n=yl()){try{t?n?.setItem(vl(e),t):n?.removeItem(vl(e))}catch{}}function Sl(e,t=yl()){try{t?.removeItem(vl(e))}catch{}}function Cl(e,t,n=yl()){let r=bl(e,n);r!==``&&(xl(t,r,n),Sl(e,n))}var wl=`pi-web:ask-draft:`;function Tl(e,t){return`${wl}${e}:${t}`}function El(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Dl(e,t,n=El()){try{let r=n?.getItem(Tl(e,t));return r==null?{}:Al(r)}catch{return{}}}function Ol(e,t,n,r=El()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Tl(e,t)):r?.setItem(Tl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function kl(e,t,n=El()){try{n?.removeItem(Tl(e,t))}catch{}}function Al(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=jl(r);t!==void 0&&(n[e]=t)}return n}function jl(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 Ml(e,t){return e.filter(e=>Fl(e,t[e.id])!==void 0).length}function Nl(e,t){return e.filter(e=>Fl(e,t[e.id])===void 0)}function Pl(e,t){let n=[];for(let r of e){let e=Fl(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function Fl(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=Il(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 Il(e){if(e===void 0)return;let t=e.trim().slice(0,kt);return t===``?void 0:t}function Ll(){let e=globalThis.crypto.randomUUID?.();return e===void 0?`cm-${String(Date.now())}-${Math.random().toString(36).slice(2,10)}`:e}function Rl(e,t){return{role:`user`,parts:[{type:`text`,text:e}],meta:{delivery:{clientMessageId:t,state:`sending`}}}}function zl(e,t){return e.findIndex(e=>e.meta?.delivery?.clientMessageId===t)}function Bl(e,t,n,r){let i=zl(e,t);if(i===-1)return e;let a=e[i],o=a?.meta?.delivery;if(a===void 0||o===void 0||!Ul(o.state,n)&&!Vl(o.kind,r,o.state,n))return e;let s=[...e],c=Ul(o.state,n)?n:o.state,l=r??o.kind;return s[i]={...a,meta:{...a.meta,delivery:{clientMessageId:t,state:c,...l===void 0?{}:{kind:l}}}},s}function Vl(e,t,n,r){return t!==void 0&&t!==e&&n===`queued`&&r===`queued`}var Hl={failed:-1,sending:0,received:1,queued:2,delivered:3};function Ul(e,t){return e===t?!1:t===`failed`?e!==`delivered`:e!==`failed`&&Hl[t]>Hl[e]}function Wl(e,t){let n=new Set;for(let e of t){let t=e.meta?.delivery?.clientMessageId;t!==void 0&&n.add(t)}return e.filter(e=>e.clientMessageId===void 0||!n.has(e.clientMessageId))}function Gl(e,t){let n=zl(e,t);return n===-1?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function Kl(e,t){let n=e,r=new Map;for(let e of t)e.clientMessageId!==void 0&&r.set(e.clientMessageId,e.kind);for(let t of e){let e=t.meta?.delivery;if(e===void 0)continue;let i=r.get(e.clientMessageId);if(i!==void 0){n=Bl(n,e.clientMessageId,`queued`,i);continue}(e.state===`received`||e.state===`queued`)&&(n=Bl(n,e.clientMessageId,`delivered`))}return n}function ql(e,t){return t!==void 0&&zl(e,t)!==-1}function Jl(e,t){let n=e.meta?.delivery;return n===void 0?t:{...t,meta:{...t.meta,delivery:{...n,state:n.state===`failed`?n.state:`delivered`}}}}function Yl(e,t){return t===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.delivery!==void 0&&Xl(e)===t)}function Xl(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
@@ -18,7 +18,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
18
18
|
`)}function Ou(e,t,n,r=!1){let i=Hc(t);if(i.length===0)return e;if(r)return ku(e,i,n);let a=Au(e,i[0]);if(a!==-1){let t=e[a],n=i[0];if(t!==void 0&&n!==void 0)return[...e.slice(0,a),Jl(t,n),...e.slice(a+1),...i.slice(1)]}if(ql(e,n))return e;let o=i[0];if(o?.role===`user`){let t=Du(o);if(t!==``&&e.some(e=>e.role===`user`&&e.meta?.delivery!==void 0&&Du(e)===t))return e;let n=e.at(-1);if(n?.role===`user`&&t!==``&&Du(n)===t)return e}return[...e,...i]}function ku(e,t,n){if(ql(e,n))return e;let r=t[0];if(r===void 0)return e;let i={...r,meta:{...r.meta,echo:!0}};return[...e,i,...t.slice(1)]}function Au(e,t){if(t?.role!==`user`)return-1;let n=Du(t);return n===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.echo===!0&&Du(e)===n)}function ju(e,t){let n=e.at(-1);return Mu(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function Mu(e,t){let n=Su(t);if(t.role!==`skill`||n.length===0)return!1;let r=Pu(e)+1;return n.every(t=>Nu(e,t,r))}function Nu(e,t,n){for(let r=e.length-1;r>=n;r--)if(Su(e[r]).some(e=>wu(e,t)))return!0;return!1}function Pu(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function Fu(e){return typeof e==`object`&&!!e}function Iu(e,t){return Fu(e)?e[t]:void 0}function Lu(e,t){let n=Iu(e,t);return typeof n==`string`?n:void 0}function Ru(e,t){let n=Iu(e,t);return typeof n==`boolean`?n:void 0}var zu=`pi-web:chat-history:v2:`,Bu=1800*1e3;function Vu(e){try{let t=sessionStorage.getItem(Ju(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!Yu(n))return;if(Date.now()-n.savedAt>Bu){sessionStorage.removeItem(Ju(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function Hu(e,t){try{sessionStorage.setItem(Ju(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Uu(e){try{sessionStorage.removeItem(Ju(e))}catch{}}function Wu(e,t){if(e===void 0||!Xu(e))return t;if(!Xu(t))return e;if(Gu(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return qu(i,n,e),qu(i,n,t),Ku(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function Gu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Ku(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function qu(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function Ju(e){return`${zu}${e}`}function Yu(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&Xu({messages:t,start:n,total:r})}function Xu(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Zu)}function Zu(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var Qu={read:Vu,write:Hu,remove:Uu},$u=class{constructor(e=Qu){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return ed(this.rawHistoryPage(e))}mergeHistory(e,t){let n=Wu(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.cache.write(e,n),ed(n)}applyLiveEvent(e,t){return nu(e,t)}seedStreamingPartial(e,t){return tu(e,t)}discard(e){this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function ed(e){let t=e?.start??0;return{messages:Lc(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function td(e){return e.trim().toLowerCase().split(/\s+/u).filter(Boolean)}function nd(e,t){let n=td(t),r=e.toLowerCase();if(n.length===0)return 0;let i=0;for(let e of n){let t=r.indexOf(e);if(t!==-1){i+=100,t===0?i+=30:od(r.charAt(t-1))&&(i+=20);continue}if(!id(e,r))return;i+=25}return i}function rd(e,t,n){if(td(t).length===0)return[...e];let r=[];return e.forEach((e,i)=>{let a=nd(n(e),t);a!==void 0&&r.push({item:e,score:a,index:i})}),r.sort((e,t)=>t.score-e.score||e.index-t.index),r.map(e=>e.item)}function id(e,t){if(e===``)return!0;if(t===``)return!1;let n=new Set([0]);for(let r of e){let e=new Set;for(let i of n)for(let n=i;n<t.length;n+=1)t.charAt(n)===r&&(n!==i&&!ad(t,n)||e.add(n+1));if(e.size===0)return!1;n=e}return!0}function ad(e,t){return t===0||od(e.charAt(t-1))}function od(e){return e===``||/[\s\-_/.:@]/u.test(e)}function sd(e,t=e.length){let n=e.slice(0,t),r=pd(n,t);if(r!==void 0)return r;let i=md(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
|
|
19
19
|
`))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`};if(o.startsWith(`#`))return{kind:`model`,query:o.slice(1),from:a,to:t}}var cd=12;function ld(e,t){return rd(e.filter(ud),t,dd).slice(0,cd).map(e=>({insertText:`#${e.provider}/${e.id}`,detail:e.provider,...e.name!==void 0&&e.name!==``&&e.name!==e.id?{description:e.name}:{}}))}function ud(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function dd(e){return`${e.provider}/${e.id} ${e.id}${e.name===void 0||e.name===``?``:` ${e.name}`}`}function fd(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function pd(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function md(e,t){let n=e.lastIndexOf(`
|
|
20
20
|
`)+1,r=e.slice(n),i=hd(r,`@ `),a=hd(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function hd(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||gd(e[n-1]))return n;return-1}function gd(e){return e===` `||e===` `}function _d(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(bd(e).startsWith(`/`))return{kind:`command`};let n=sd(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function vd(e){return _d(e).kind===`shell`}function yd(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function bd(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
|
|
21
|
-
`))+1;return e.slice(t)}var xd=5e4,Sd=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`,this.lastFrameAt=0}checkLiveness(e=Date.now()){let t=this.socket;t===void 0||!this.shouldReconnect||t.readyState===WebSocket.OPEN&&(this.lastFrameAt===0||e-this.lastFrameAt<xd||Ad(t))}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Ad(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=cs(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500,this.lastFrameAt=Date.now();let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){this.socket===t&&(this.lastFrameAt=Date.now());let r=wd(await kd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Cd=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`,this.lastFrameAt=0}checkLiveness(e=Date.now()){let t=this.socket;t===void 0||!this.shouldReconnect||t.readyState===WebSocket.OPEN&&(this.lastFrameAt===0||e-this.lastFrameAt<xd||Ad(t))}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Ad(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=us(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.lastFrameAt=Date.now(),this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){this.socket===t&&(this.lastFrameAt=Date.now());let n=Td(await kd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function wd(e){let t=Od(e);if(t===`notifications.inbox`)return Dd(()=>yr(e));if(t===`ask.opened`)return Dd(()=>An(e));if(t===`ask.closed`)return Dd(()=>jn(e));if(t===`dialog.opened`)return Dd(()=>Wn(e));if(t===`dialog.closed`)return Dd(()=>Gn(e));let n=Dd(()=>or(e));return n===void 0?void 0:Ed(n,e)}function Td(e){let t=Od(e);return Dd(t===`sessions.unread`?()=>tr(e):t===`session.startup`?()=>nr(e):()=>sr(e))}function Ed(e,t){if(typeof t!=`object`||!t||!(`seq`in t))return e;let n=t.seq;return typeof n==`number`?{...e,seq:n}:e}function Dd(e){try{return e()}catch{return}}function Od(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function kd(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Ad(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function jd(e,t){if(e===void 0)return`unknown`;let n=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return n===!0?`persisted`:n===!1||Dc(e)?`transient`:`unknown`}function Md(e,t){return e!==void 0&&e.archived!==!0&&jd(e,t)===`persisted`}function Nd(e,t){return e!==void 0&&e.archived!==!0&&jd(e,t)===`transient`}function Pd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Fd=class{constructor(e,t,n=Pd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ld(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Id(e){return typeof e==`string`&&e!==``?e:void 0}function Ld(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Rd(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Rd(e){return!zd(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function zd(e){return typeof e==`object`&&!!e}var Bd=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Vd=`pi-web:session-selection:v1`,Hd=class{constructor(e=Pd()){this.sessionIdsByCwd=new Fd(Vd,Id,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Ud(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return Gd(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Wd(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Gd(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function Kd(e,t,n){return qd(e,[t],n)}function qd(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function Jd(e,t,n){return Yd(e,t,[n])}function Yd(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var Xd=100,Zd=100,Qd=class{constructor(e,t,n,r=new Bd,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new pc,this.socket=i.socket??new Sd,this.api=i.api??I,this.transcripts=i.transcripts??new $u,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Wd(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=L(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}preferredSession(e,t,n){return Ud(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(z(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let r=L(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.getState().sessionStatuses[e.id]?.pendingAsk,pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:Xd},L(this.getState()));if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a=[];if(o=a,this.socket.connect(e,e=>a.push(e),()=>{this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh({session:e,machineId:r,selectionSeq:n}),!this.isCurrentRefreshTarget({session:e,machineId:r,selectionSeq:n}))return;this.refreshAvailableThinkingLevels();for(let e of a)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(Dc(e)&&_f(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{let n=await this.api.messages(t,{before:e.messagePageStart,limit:Xd},L(this.getState()));if(this.getState().selectedSession?.id!==t.id)return;let r=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),n);this.setState(r)}catch(e){this.setState({error:String(e)})}finally{this.getState().selectedSession?.id===t.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,t,n,r=`inline`){let i=this.getState().selectedSession;if(!i||i.archived===!0)return!1;let a=e.trim(),o=n!==void 0&&n.length>0;return z(i)?(!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&vd(e)?this.enqueuePendingSessionSend(i,{type:`shell`,text:e}):this.enqueuePendingSessionSend(i,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r}),!0):!o&&a.startsWith(`/`)?(await this.runCommand(e),!0):!o&&vd(e)?(await this.runShell(e),!0):await this.deliverPromptToSession(i,e,t,n,r,L(this.getState()),{markSending:o})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:tf(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(z(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,L(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(z(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,L(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`});return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=sf(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,lf(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);let c=this.beginTrackedSend(e,t);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>fd(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a,void 0,c)}else await this.api.prompt(e,t,n,a,r,c);return c!==void 0&&this.markDelivery(e.id,c,`received`),this.markCachedNewSessionPersisted(e),!0}catch(t){return c!==void 0&&this.markDelivery(e.id,c,`failed`),this.setState({error:String(t)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}beginTrackedSend(e,t){if(t.trim()===``||this.getState().selectedSession?.id!==e.id)return;let n=Ll();return this.setState({messages:[...this.getState().messages,Rl(t,n)]}),n}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?tf(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,L(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||z(r))throw Error(`The session tree navigator is no longer available`);let a=L(n),o=this.selectionSeq,s=Vs(a,r.id),c;try{c=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}if(c.cancelled)return c;let l=c.editorText??``;if(xl(s,l),this.transcripts.discard(s),!this.isSelectedSessionIdentity(r.id,a))return c;this.clearPendingUpdates();let u;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){u={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return c;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:l})}catch(e){throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(e)}),e}if(u!==void 0)throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(u.error)}),u.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),c}async forkFromTree(e){let t=this.getState(),n=t.selectedSession,r=t.treeDialog;if(n===void 0||r===void 0||n.archived===!0||z(n))throw Error(`The session tree navigator is no longer available`);let i=L(t),a=this.selectionSeq,o=Vs(i,n.id),s;try{s=await this.api.forkTree(n,{entryId:e,expectedLeafId:r.activeLeafId},i)}catch(e){throw this.isCurrentSessionSelection(n.id,i,a)&&this.setState({error:String(e)}),e}if(s.cancelled)return s;let c=s.session;if(s.promptDraft!==void 0&&xl(Vs(i,c.id),s.promptDraft),this.transcripts.discard(o),!this.isSelectedSessionIdentity(n.id,i))return s;let l=[c,...this.getState().sessions.filter(e=>e.id!==c.id)];return this.setState({sessions:l,treeDialog:void 0}),this.selectSession(c),s}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||z(t))return;let n=L(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e);if(Nd(e,t)){await this.deleteCachedNewSession(e);return}if(Md(e,t))try{await this.api.archive(e,L(this.getState()));let t=this.getState(),n=Kd(t.sessions,e.id,new Date().toISOString()),r=Jd(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!Md(e,this.statusForSession(e))))try{let t=await this.api.archiveWithDescendants(e,L(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=qd(r.sessions,n,new Date().toISOString()),a=Yd(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=ff(e).filter(e=>Md(e,this.statusForSession(e)));if(t.length!==0)try{let e=L(this.getState()),{succeededIds:n,failures:r,generatedAt:i}=await this.archiveSessionBatch(t,e);if(n.length>0){let e=this.getState(),t=qd(e.sessions,n,i??new Date().toISOString()),r=Yd(t,e.selectedSession?.id,n);this.setState({sessions:t}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${mf(e)}`})}}async deleteArchivedSessions(e){let t=ff(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=L(this.getState());try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${mf(e)}`})}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:pf(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:pf(n.failures)}}async applySessionCleanupResult(e,t=L(this.getState())){if(L(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=qd(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:nf(t.sessionStatuses,a),sessionActivities:nf(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=Yd(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=L(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Ec(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(L(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){L(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}finally{this.hydrateSessionStatuses(e)}}async loadInterruptedRuns(e=L(this.getState())){try{let t=await this.api.interruptedRuns(e);return new Set(t.runs.map(e=>e.sessionId))}catch{return new Set}}async hydrateSessionStatuses(e=L(this.getState()),t){let n;try{n=await this.api.statusCatalog(e)}catch{return}if(L(this.getState())!==e)return;let r=this.getState(),i=t?.replaceKnown===!0,a={};for(let e of n.statuses)!i&&r.sessionStatuses[e.sessionId]!==void 0||(a[e.sessionId]=e);Object.keys(a).length!==0&&this.setState({sessionStatuses:{...r.sessionStatuses,...a}})}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Nd(e,this.statusForSession(e)))return;let t=z(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,L(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Tc(e.id,L(this.getState())),Sl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:tf(n.sessionStatuses,e.id),sessionActivities:ef(n.sessionActivities,e.id),sendingPrompts:tf(n.sendingPrompts,e.id),clientQueuedSessionMessages:tf(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,L(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Md(e,this.statusForSession(e)))return;let t=L(this.getState());try{await this.api.reloadSession(e,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,L(this.getState()));let t={...e};delete t.parentSessionPath,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,L(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.modelCatalog(e,L(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{return(await this.api.setModelEnabled(r,e,t,n,L(this.getState()))).models}catch(e){this.setState({error:String(e)});return}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,L(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}checkSocketLiveness(){this.socket.checkLiveness?.()}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||z(t))return;let n=L(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async recallQueuedMessage(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||n.archived===!0||z(n))return!1;let r=L(t),i=this.selectionSeq;try{let{recalled:t,status:a}=await this.api.recallQueuedMessage(n,e,r);if(!this.isCurrentSessionSelection(n.id,r,i))return!1;let o=e.clientMessageId;return t&&o!==void 0&&this.setState({messages:Gl(this.getState().messages,o)}),this.applyStatus(a),t}catch(e){return this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)}),!1}}async openSubagentRunOutput(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t);try{let t=await this.api.subagentRunOutput(n,e.runId,r);this.setState({messages:[...this.getState().messages,Rc(`tool`,`Subagent ${e.agent} (${e.runId.slice(0,8)}):\n\n${t}`)]})}catch(e){this.setState({error:String(e)})}}async openBackgroundTaskOutput(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t);try{let t=await this.api.backgroundTaskOutput(n,e.id,r);this.setState({messages:[...this.getState().messages,Rc(`tool`,`Background task ${e.name} (${e.id}):\n\n${t}`)]})}catch(e){this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(z(r)){await this.closePendingStartDialog(r,e,t);return}let i=L(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;let n=e.outcome;if(n!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===n.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:n.reason,...n.answer===void 0?{}:{answer:n.answer}})}this.applyStatus(e.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=t.outcome;if(o!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===o.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:o.reason,...o.answer===void 0?{}:{answer:o.answer}})}this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){a===this.selectionSeq&&this.getState().selectedSession?.id===e.id&&this.setState({error:String(t)})}}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||z(r))return;let i=L(n),a=this.selectionSeq;try{let n=await t(r,i);kl(Vs(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return[];try{let t=await this.api.abort(e,L(this.getState()));for(let e of t.discarded)e.clientMessageId!==void 0&&this.setState({messages:Gl(this.getState().messages,e.clientMessageId)});return t.discarded}catch(e){return this.setState({error:String(e)}),[]}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.getState().selectedSession;if(e===void 0||t?.id!==e||t.archived===!0||z(t))return Promise.resolve();let n={session:t,machineId:L(this.getState()),selectionSeq:this.selectionSeq};return this.requestSelectedSessionRefresh(n).catch(e=>{this.isCurrentRefreshTarget(n)&&this.setState({error:String(e)})})}requestSelectedSessionRefresh(e){let t=Vs(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:Xd},e.machineId),this.api.status(e.session,e.machineId),this.api.streamSnapshot(e.session,e.machineId),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r)})}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return L(n)===t&&r?.id===e&&r.archived!==!0&&!z(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return Vs(L(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}workspaceSelectionKey(e){return`${L(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`New session`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:sf(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:sf(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Sl(Vs(n.machineId,e)),this.setState({clientQueuedSessionMessages:tf(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Cc(t,n.machineId),Cl(Vs(n.machineId,e),Vs(n.machineId,t.id));let a=wc(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:tf(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:af(o.sessions,e,a),sessionActivities:ef(o.sessionActivities,e),sendingPrompts:rf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:rf(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:o.sessionStatuses[a.id]?.pendingAsk,pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r||!a){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=this.getState(),s=mf(t),c=cf(e,s,n.queuedSends.length),l=o.sessions.some(t=>t.id===e);this.setState({sessions:l?o.sessions:[n.session,...o.sessions],sessionActivities:{...o.sessionActivities,[e]:c},activity:o.selectedSession?.id===e?c:o.activity,...o.selectedSession?.id===e?{pendingDialogs:[]}:{},error:`Failed to start session: ${s}`}),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return L(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||L(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>z(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=L(this.getState()),r=await this.api.startSession(e.cwd,n);Cc(r,n),Cl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Tc(e.id,n);let i=wc(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!Dc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Oc(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,Rc(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&xl(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=L(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=n?Kl(t.messages,e.queuedMessages):t.messages,i=t.sessionActivities[e.sessionId]?.phase===`active`&&!Is(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...hf(t,e.sessionId,e.messageCount),...i?{sessionActivities:ef(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&i?void 0:t.activity,...n?{pendingAsk:e.pendingAsk}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{},...r===t.messages?{}:{messages:r}})}markDelivery(e,t,n){let r=this.getState();if(r.selectedSession?.id!==e)return;let i=Bl(r.messages,t,n);i!==r.messages&&this.setState({messages:i})}applyOpenedDialog(e){let t=this.getState();t.selectedSession!==void 0&&(t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]}))}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),...$d(e)?{closedDialogs:[...t.closedDialogs,e]}:{}})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){this.getState().selectedSession!==void 0&&this.setState({pendingAsk:e})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}async renameSession(e,t,n=L(this.getState())){let r=t.trim();if(r===``)return;let i=e.name;this.applySessionName(e.id,r);try{await this.api.runCommand({id:e.id,cwd:e.cwd},`/name ${r}`,n)}catch(t){this.applySessionName(e.id,i),this.setState({error:String(t)})}}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(L(this.getState()),e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(gf(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?sf(t.tempId,t.queuedSends.length):of(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame??=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}),this.pendingFlushTimer??=setTimeout(()=>{this.pendingFlushTimer=void 0,this.flushPendingUpdates()},Zd)}cancelScheduledFlush(){this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0),this.pendingFlushTimer!==void 0&&(clearTimeout(this.pendingFlushTimer),this.pendingFlushTimer=void 0)}flushPendingUpdates(){if(this.cancelScheduledFlush(),this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.cancelScheduledFlush()}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function $d(e){return e.reason!==`timeout`||e.dialog.runScoped}function ef(e,t){return tf(e,t)}function tf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function nf(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function rf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...tf(e,t),[n]:r}}function af(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function z(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function of(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function sf(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function cf(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function lf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:uf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function uf(e,t){let n=df(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function df(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function ff(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function pf(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function mf(e){return e instanceof Error?e.message:String(e)}function hf(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function gf(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function _f(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var vf={order:0,overflowWatermark:0};function yf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:vf,optimisticDismissedIds:[],announcements:[]}}function bf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Pf(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function xf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??yf(t),needsRefresh:!1,changed:!1};if(e===void 0||!Pf(e,t))return{value:If(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:If(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!Lf(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Sf(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=zf(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...Bf(Rf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Cf(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function wf(e){return`${Cf(e.severity)} notification received.`}function Tf(e){return e.retainedCount+e.discardedCount}function Ef(e){return`Notifications (${String(Tf(e))})`}function Df(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${Cf(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Of(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function kf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Af(e,t){return e.has(kf(t))}function jf(e,t,n){let r=new Set(e),i=kf(t);return n?r.add(i):r.delete(i),r}function Mf(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Nf(e){if(!e.truncated)return;let t=Dt/1024;return`Message truncated at ${String(t)} KiB.`}function Pf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Ff(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function If(e){return{...yf(e),status:`stale`}}function Lf(e,t){return e.length===t.retainedCount&&Rf(e)===t.highestSeverity}function Rf(e){let t;for(let n of e)t=Ff(t,n.severity);return t}function zf(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function Bf(e){return e===void 0?{}:{highestSeverity:e}}var Vf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??I,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:yf(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=xf(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineIsReachableInState(e,r.machineId);if(!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Sf(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=Hf(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${Wf(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Sf(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=Hf(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${Wf(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}let i=this.getState().selectedNotificationInbox,a=i===void 0||Uf(i,t,r)?bf(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=xf(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Pf(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Pf(r,e))return;if(!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=Uf(r,e,t)?bf(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Pf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Pf(t,e))&&this.setState({selectedNotificationInbox:yf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Pf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Pf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Pf(this.selectedTarget,e)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function Hf(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function Uf(e,t,n){return!Pf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function Wf(e){return e instanceof Error?e.message:String(e)}var Gf=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},Kf=`pi-web:workspace-selection:v1`,qf=class{constructor(e=Pd()){this.workspaceIdsByProject=new Fd(Kf,Id,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function Jf(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var Yf=50,Xf=class{constructor(e,t,n,r,i=new Gf,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.api=a.api??I,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.topologyRefreshes=new pc(a.topologyRefreshDebounceMs??Yf)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Ps()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Bs(L(this.getState()),e));let t=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:t})}async selectProject(e,t){let n=L(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Ps()});try{let r=await this.api.workspaces(e.id,n);if(L(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=Jf(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bs(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({error:String(t),isLoadingWorkspaces:!1})}}async selectWorkspace(e,t){let n=L(this.getState());this.workspaceSelection.rememberWorkspace({...e,projectId:Bs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Ps()});try{let r=Ec(e.path,await this.api.sessions(e.path,n),n);if(L(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedWorkspace?.id===e.id&&this.setState({error:String(t)})}finally{this.refreshWorkspaceGoals(e,n)}}async refreshWorkspaceGoals(e=this.getState().selectedWorkspace,t=L(this.getState())){if(e===void 0)return;this.setState({workspaceGoalsLoading:!0});let n;try{n=(await this.api.workspaceGoals(e.projectId,e.id,t)).goals}catch{n=[]}L(this.getState())!==t||this.getState().selectedWorkspace?.id!==e.id||this.setState({workspaceGoals:n,workspaceGoalsLoading:!1})}async archiveWorkspaceGoal(e,t=this.getState().selectedWorkspace){if(t===void 0)return;let n=L(this.getState());try{(await this.api.archiveWorkspaceGoal(t.projectId,t.id,e,n)).agentMayRecreate&&this.setState({error:`Goal archived. A session already working it keeps its own copy until it reloads, so run /goal-refresh there if it comes back.`})}catch(e){this.setState({error:`Could not archive the goal: ${e instanceof Error?e.message:String(e)}`})}await this.refreshWorkspaceGoals(t,n)}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`Project not found`);let n=await this.api.workspaces(t.id,L(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=L(e);await this.topologyRefreshes.request(Bs(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(L(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=Zf(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||Qf(e,n)))return{selectedWorkspace:n}}};function Zf(e){return e.find(e=>e.isMain)??e[0]}function Qf(e,t){return $f(e,t)}function $f(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>$f(e,t[n]));if(!ep(e)||!ep(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&$f(e[n],t[n]))}function ep(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var tp=`pi-web:machine-navigation:v1`,np=class{constructor(e=Pd()){this.snapshotsByMachine=new Fd(tp,sp,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?op(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,op(e))}forget(e){this.snapshotsByMachine.delete(e)}};function rp(e){return{machineId:e,surface:{}}}function ip(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function ap(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view===`navigation`?void 0:e.view}}function op(e){return{...e,surface:{...e.surface}}}function sp(e){if(!pp(e))return;let t=fp(e,`machineId`);if(t===void 0)return;let n=up(fp(e,`tool`)),r=lp(fp(e,`view`));return{machineId:t,projectId:fp(e,`projectId`),workspaceId:fp(e,`workspaceId`),sessionId:fp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:cp(e.surface)}}function cp(e){return pp(e)?{selectedFilePath:fp(e,`selectedFilePath`),selectedTerminalId:fp(e,`selectedTerminalId`)}:{}}function lp(e){return e===`navigation`||e===`chat`?e:up(e)}function up(e){return dp(e)?e:void 0}function dp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function fp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function pp(e){return typeof e==`object`&&!!e}var mp=`pi-web:terminal-selection:v1`,hp=class{constructor(e=Pd()){this.terminalIdsByCwd=new Fd(mp,Id,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function gp(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function _p(e){return e.find(e=>!e.exited)??e[0]}var vp=1200,yp=[`mod`,`alt`,`shift`],bp=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Tp(e);if(r===void 0)return!1;let i=xp(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!Ep(r))return!1}else if(!Ep(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>Up(t.tokens,e));return n===void 0?t.some(t=>Wp(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},vp)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function xp(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Dp(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(jp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(Mp),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Np(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:Ap(t),i=n?[...s.get(e)??[]].sort(jp).map(Ap):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Sp(e){return Ip(e,{requireFirstChordActivator:!0})}function Cp(e){let t=Ip(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function wp(e){return Cp(e).map(e=>e.split(`+`).map(Hp).join(`+`)).join(` `)}function Tp(e){if(e.isComposing)return;let t=Bp(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function Ep(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Dp(e,t,n){let r=Op(e,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Cp(i),o=a[0];if(!(o===void 0||!Ep(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:kp(a),order:n}}function Op(e,t){if(t!==void 0){for(let n of[e.id,...e.shortcutAliases??[]])if(Object.hasOwn(t,n))return t[n]}}function kp(e){return e.join(`\0`)}function Ap(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function jp(e,t){return Pp(e.source)-Pp(t.source)||Fp(e.action.id,t.action.id)||Fp(e.action.title,t.action.title)||e.order-t.order}function Mp(e,t){return e.tokens.length-t.tokens.length||jp(e,t)}function Np(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&Wp(e.tokens,t.tokens))}function Pp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Fp(e,t){return e<t?-1:+(e>t)}function Ip(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`Enter a shortcut, choose None, or reset to the default.`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=Lp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Ep(i.token))return{ok:!1,message:`Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured.`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function Lp(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`Shortcut chords must include a key.`};let n=new Set,r;for(let e of t){let t=Rp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${Hp(t)} modifiers.`};n.add(t);continue}let i=zp(e);if(i===void 0)return{ok:!1,message:`Unsupported shortcut key: ${e}`};if(r!==void 0)return{ok:!1,message:`Each shortcut chord can include only one non-modifier key.`};r=i}return r===void 0?{ok:!1,message:`Shortcut chords must include a key.`}:{ok:!0,token:[...yp.filter(e=>n.has(e)),r].join(`+`)}}function Rp(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function zp(e){let t=Vp(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Bp(e){return e===` `?`space`:zp(e.toLowerCase())}function Vp(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function Hp(e){return e===`mod`?Gp()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?Gp()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Up(e,t){return e.length===t.length&&Wp(e,t)}function Wp(e,t){return t.every((t,n)=>e[n]===t)}function Gp(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function Kp(e,t,n=24){if(t===void 0||!Number.isFinite(e)||e<=0||!Number.isFinite(t.height)||t.height<=0)return 0;let r=e-(t.offsetTop+t.height);return!Number.isFinite(r)||r<n?0:Math.min(r,e)}var qp={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Jp(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`Enable at least one cleanup action.`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=nm(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=nm(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Yp(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Xp(e){if(e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Jp(e.draft);return!t.ok||Yp(t.request)!==Yp(e.previewRequest)?!1:Zp(e.preview)}function Zp(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Qp(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function $p(e,t){let n=new Set(Qp(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function em(e,t){return t(tm(e))}function tm(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`archive ${String(t)} idle ${t===1?`session`:`sessions`}`),n>0&&r.push(`permanently delete ${String(n)} archived ${n===1?`session`:`sessions`}`),`Run cleanup and ${r.length===0?`run cleanup`:r.join(` and `)}?\n\nPermanent deletion only applies to archived sessions and cannot be undone.`}function nm(e,t){let n=e.trim();if(n===``)return`${t} must be set.`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t} must be a non-negative whole number of days.`:r}var rm=new Set,im=Tt+1,am={unreadCatalog:e=>Eo.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Eo.acknowledgeUnread(e,t,n,r)},om=class{constructor(e={}){this.machines=new Map,this.api=e.api??am,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return rm;let r=new Set;for(let e of t)n.summariesByIdentity.has(fm(e))&&r.add(e.id);return r.size===0?rm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(fm(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=sm(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(fm(t));if(i===void 0)return Promise.resolve();let a=pm(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=lm(t),a=`fresh`,o=!1;for(let e of n.events){let t=sm(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=im?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!dm(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function sm(e,t,n){if(e===void 0){let e=um(n.catalogId);return n.catalogRevision===1?cm(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=um(n.catalogId);return n.catalogRevision===1?cm(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?cm(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function cm(e,t,n){let r=new Map(e.summariesByIdentity),i=fm(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function lm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[fm(e),{...e}]))}}function um(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function dm(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function fm(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function pm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}function mm(){return{selectedSessionKey:void 0,warningSetSignature:hm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function hm(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function gm(e,t,n){let r=hm(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function _m(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function vm(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function ym(e){return e.collapsed?vm(e):_m(e)}var bm=`themes:classic`,xm={themeId:`themes:pi-web-dark`,auto:!0},Sm=`pi-web-app-theme`,Cm=`--pi-bg.--pi-surface.--pi-surface-hover.--pi-terminal-bg.--pi-terminal-text.--pi-border.--pi-border-muted.--pi-text.--pi-text-secondary.--pi-text-bright.--pi-muted.--pi-dim.--pi-accent.--pi-accent-border.--pi-selection-bg.--pi-success.--pi-success-border.--pi-success-bg.--pi-success-surface.--pi-success-ring.--pi-warning.--pi-warning-border.--pi-warning-surface.--pi-danger.--pi-purple.--pi-purple-border.--pi-purple-surface.--pi-overlay.--pi-shadow-soft.--pi-shadow.--pi-shadow-strong.--pi-bg-overlay-soft.--pi-bg-overlay.--pi-success-bg-overlay.--pi-terminal-selection`.split(`.`),wm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Tm(){try{let e=window.localStorage.getItem(Sm);return e===null?void 0:jm(e)}catch{return}}function Em(e){try{window.localStorage.setItem(Sm,JSON.stringify(e))}catch{}}function Dm(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of Cm){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function Om(e){let t=km(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=Am(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function km(e,t=bm){return e.find(e=>e.id===t)??e[0]}function Am(e,t){return e.find(e=>e.light===t||e.dark===t)}function jm(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return Mm(e)?e:void 0}catch{return}}function Mm(e){if(!Nm(e))return!1;let t=e.themeId,n=e.auto;return Pm(t)&&typeof n==`boolean`}function Nm(e){return typeof e==`object`&&!!e}function Pm(e){return typeof e==`string`&&wm.test(e)}var Fm=`workspace.delete`,Im=`pi.operation`,Lm=`target.workspaceId`;function Rm(e){return e?.removal!==void 0&&!e.isMain}function zm(e){return e.removal?.confirmation}function Bm(e){return{...e===void 0?{}:{projectId:e},metadata:{[Im]:Fm}}}function Vm(e){let t={};for(let n of e){let e=Wm(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Hm(e){return Object.entries(e).filter(([,e])=>Gm(e)).map(([e])=>e)}function Um(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Gm(n)}function Wm(e){return e.metadata[Lm]}function Gm(e){return e.status===`queued`||e.status===`running`}function Km(){return[{id:`actions.show`,title:`Show Actions`,description:`Open the command palette`,shortcut:`mod+k`,group:`General`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`Focus Prompt`,description:`Move keyboard focus to the message composer`,shortcut:`mod+g c`,group:`General`,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`Add Machine`,description:`Register another PI WEB runtime reachable from this gateway`,group:`Machine`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`Refresh Selected Machine`,description:`Check whether the selected PI WEB runtime is online`,group:`Machine`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`Open Selected Machine PI WEB`,description:`Open the selected remote PI WEB directly in a new tab`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`Remove Selected Machine`,description:`Remove the selected remote machine from this gateway`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`Add Project`,group:`Project`,run:e=>e.addProject()},{id:`auth.login`,title:`Configure Provider Authentication`,description:`Run /login without tying authentication to a session`,group:`General`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`Remove Provider Authentication`,description:`Run /logout for stored pi credentials`,group:`General`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`Select Theme`,description:`Choose the PI WEB color theme`,group:`Preferences`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`Open Settings`,description:`Manage PI WEB configuration and keyboard shortcuts`,shortcut:`mod+,`,group:`Preferences`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`Full Page Reload`,description:`Reload the PI WEB browser page`,group:`General`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`Go to Chat`,shortcut:`mod+1`,group:`Navigation`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`Go to Files`,shortcut:`mod+2`,group:`Navigation`,enabled:qm,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+3`,group:`Navigation`,enabled:qm,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:qm,run:e=>e.refreshFiles()},{id:`workspace.delete`,title:`Remove Workspace`,description:`Run the owning provider's workspace removal operation`,group:`Workspace`,enabled:Jm,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:qm,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:Ym,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:Ym,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:Xm,run:e=>e.archiveSession()},{id:`session.reload`,title:`Reload Session from Disk`,description:`Close and re-open the selected session from its session file. Use /reload in the prompt for Pi runtime resources.`,group:`Session`,enabled:Qm,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:Zm,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&Is(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function qm(e){return e.state.selectedWorkspace!==void 0}function Jm(e){let t=e.state.selectedWorkspace;return Rm(t)&&!Um(e.state,t)}function Ym(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Xm(e){return Md(e.state.selectedSession,e.state.status)}function Zm(e){return Nd(e.state.selectedSession,e.state.status)}function Qm(e){return Md(e.state.selectedSession,e.state.status)?!Is(e.state.status,e.state.activity):!1}function $m(e){return typeof e==`string`?eh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function eh(e){switch(e){case`navigation`:return Ye`
|
|
21
|
+
`))+1;return e.slice(t)}var xd=5e4,Sd=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`,this.lastFrameAt=0}checkLiveness(e=Date.now()){let t=this.socket;t===void 0||!this.shouldReconnect||t.readyState===WebSocket.OPEN&&(this.lastFrameAt===0||e-this.lastFrameAt<xd||Ad(t))}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Ad(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=cs(e,this.machineId);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500,this.lastFrameAt=Date.now();let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){this.socket===t&&(this.lastFrameAt=Date.now());let r=wd(await kd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Cd=class{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`,this.lastFrameAt=0}checkLiveness(e=Date.now()){let t=this.socket;t===void 0||!this.shouldReconnect||t.readyState===WebSocket.OPEN&&(this.lastFrameAt===0||e-this.lastFrameAt<xd||Ad(t))}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Ad(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=us(this.machineId);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.lastFrameAt=Date.now(),this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){this.socket===t&&(this.lastFrameAt=Date.now());let n=Td(await kd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function wd(e){let t=Od(e);if(t===`notifications.inbox`)return Dd(()=>yr(e));if(t===`ask.opened`)return Dd(()=>An(e));if(t===`ask.closed`)return Dd(()=>jn(e));if(t===`dialog.opened`)return Dd(()=>Wn(e));if(t===`dialog.closed`)return Dd(()=>Gn(e));let n=Dd(()=>or(e));return n===void 0?void 0:Ed(n,e)}function Td(e){let t=Od(e);return Dd(t===`sessions.unread`?()=>tr(e):t===`session.startup`?()=>nr(e):()=>sr(e))}function Ed(e,t){if(typeof t!=`object`||!t||!(`seq`in t))return e;let n=t.seq;return typeof n==`number`?{...e,seq:n}:e}function Dd(e){try{return e()}catch{return}}function Od(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function kd(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Ad(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function jd(e,t){if(e===void 0)return`unknown`;let n=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return n===!0?`persisted`:n===!1||Dc(e)?`transient`:`unknown`}function Md(e,t){return e!==void 0&&e.archived!==!0&&jd(e,t)===`persisted`}function Nd(e,t){return e!==void 0&&e.archived!==!0&&jd(e,t)===`transient`}function Pd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Fd=class{constructor(e,t,n=Pd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ld(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Id(e){return typeof e==`string`&&e!==``?e:void 0}function Ld(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Rd(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Rd(e){return!zd(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function zd(e){return typeof e==`object`&&!!e}var Bd=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Vd=`pi-web:session-selection:v1`,Hd=class{constructor(e=Pd()){this.sessionIdsByCwd=new Fd(Vd,Id,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Ud(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return Gd(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Wd(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Gd(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function Kd(e,t,n){return qd(e,[t],n)}function qd(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function Jd(e,t,n){return Yd(e,t,[n])}function Yd(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var Xd=100,Zd=100,Qd=class{constructor(e,t,n,r=new Bd,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new pc,this.socket=i.socket??new Sd,this.api=i.api??I,this.transcripts=i.transcripts??new $u,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady,this.onSelectedSessionIdle=i.onSelectedSessionIdle}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Wd(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=L(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}preferredSession(e,t,n){return Ud(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(z(e)){this.selectClientPendingStartSession(e,t);return}this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let n=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let r=L(this.getState());this.notifications?.prepareSelectedSession(e,r);let i=this.sessionCacheKey(e.id),a=this.transcripts.cachedView(i);this.setState({selectedSession:e,...a,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.getState().sessionStatuses[e.id]?.pendingAsk,pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let o;try{if(e.archived===!0){let a=await this.api.messages(e,{limit:Xd},L(this.getState()));if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=this.transcripts.mergeHistory(i,a);this.setState({...o,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}let a=[];if(o=a,this.socket.connect(e,e=>a.push(e),()=>{this.refreshSelectedSession(e.id)},r,()=>{this.notifications?.refreshSelectedSession(e,r)}),await this.requestSelectedSessionRefresh({session:e,machineId:r,selectionSeq:n}),!this.isCurrentRefreshTarget({session:e,machineId:r,selectionSeq:n}))return;this.refreshAvailableThinkingLevels();for(let e of a)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:r,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(i){if(n!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,r))throw i;return}if(Dc(e)&&_f(i)){await this.recreateCachedNewSession(e,t);return}if(o!==void 0){for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.setState({error:String(i)}),t?.propagateRefreshError===!0)throw i}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{let n=await this.api.messages(t,{before:e.messagePageStart,limit:Xd},L(this.getState()));if(this.getState().selectedSession?.id!==t.id)return;let r=this.transcripts.mergeHistory(this.sessionCacheKey(t.id),n);this.setState(r)}catch(e){this.setState({error:String(e)})}finally{this.getState().selectedSession?.id===t.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,t,n,r=`inline`){let i=this.getState().selectedSession;if(!i||i.archived===!0)return!1;let a=e.trim(),o=n!==void 0&&n.length>0;return z(i)?(!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&vd(e)?this.enqueuePendingSessionSend(i,{type:`shell`,text:e}):this.enqueuePendingSessionSend(i,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r}),!0):!o&&a.startsWith(`/`)?(await this.runCommand(e),!0):!o&&vd(e)?(await this.runShell(e),!0):await this.deliverPromptToSession(i,e,t,n,r,L(this.getState()),{markSending:o})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:tf(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(z(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,L(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(z(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,L(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.setState({error:`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`});return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=sf(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,lf(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o){let s=r!==void 0&&r.length>0;o.markSending&&this.markSendingPrompt(e.id,!0);let c=this.beginTrackedSend(e,t);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>fd(e.path,!1)).join(` `),o=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,o,n,a,void 0,c)}else await this.api.prompt(e,t,n,a,r,c);return c!==void 0&&this.markDelivery(e.id,c,`received`),this.markCachedNewSessionPersisted(e),!0}catch(t){return c!==void 0&&this.markDelivery(e.id,c,`failed`),this.setState({error:String(t)}),!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}beginTrackedSend(e,t){if(t.trim()===``||this.getState().selectedSession?.id!==e.id)return;let n=Ll();return this.setState({messages:[...this.getState().messages,Rl(t,n)]}),n}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`system`,String(t))]}),this.setState({error:String(t)}),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.setState({error:`Queued command “${t}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Rc(`system`,String(t))]}),this.setState({error:String(t)}),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?tf(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(n){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(n,e,t,L(this.getState())))}catch(e){this.setState({error:String(e)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||z(r))throw Error(`The session tree navigator is no longer available`);let a=L(n),o=this.selectionSeq,s=Vs(a,r.id),c;try{c=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.isCurrentSessionSelection(r.id,a,o)&&this.setState({error:String(e)}),e}if(c.cancelled)return c;let l=c.editorText??``;if(xl(s,l),this.transcripts.discard(s),!this.isSelectedSessionIdentity(r.id,a))return c;this.clearPendingUpdates();let u;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){u={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return c;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:l})}catch(e){throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(e)}),e}if(u!==void 0)throw this.isSelectedSessionIdentity(r.id,a)&&this.setState({error:String(u.error)}),u.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),c}async forkFromTree(e){let t=this.getState(),n=t.selectedSession,r=t.treeDialog;if(n===void 0||r===void 0||n.archived===!0||z(n))throw Error(`The session tree navigator is no longer available`);let i=L(t),a=this.selectionSeq,o=Vs(i,n.id),s;try{s=await this.api.forkTree(n,{entryId:e,expectedLeafId:r.activeLeafId},i)}catch(e){throw this.isCurrentSessionSelection(n.id,i,a)&&this.setState({error:String(e)}),e}if(s.cancelled)return s;let c=s.session;if(s.promptDraft!==void 0&&xl(Vs(i,c.id),s.promptDraft),this.transcripts.discard(o),!this.isSelectedSessionIdentity(n.id,i))return s;let l=[c,...this.getState().sessions.filter(e=>e.id!==c.id)];return this.setState({sessions:l,treeDialog:void 0}),this.selectSession(c),s}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||z(t))return;let n=L(e),r=this.selectionSeq;try{await this.api.abort(t,n)}catch(e){throw this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)}),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e);if(Nd(e,t)){await this.deleteCachedNewSession(e);return}if(Md(e,t))try{await this.api.archive(e,L(this.getState()));let t=this.getState(),n=Kd(t.sessions,e.id,new Date().toISOString()),r=Jd(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(!(e===void 0||!Md(e,this.statusForSession(e))))try{let t=await this.api.archiveWithDescendants(e,L(this.getState())),n=t.sessionIds!==void 0&&t.sessionIds.length>0?t.sessionIds:[e.id],r=this.getState(),i=qd(r.sessions,n,new Date().toISOString()),a=Yd(i,r.selectedSession?.id,n);this.setState({sessions:i}),a.type===`select`?await this.selectSession(a.session):a.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(e){this.setState({error:String(e)})}}async archiveSessions(e){let t=ff(e).filter(e=>Md(e,this.statusForSession(e)));if(t.length!==0)try{let e=L(this.getState()),{succeededIds:n,failures:r,generatedAt:i}=await this.archiveSessionBatch(t,e);if(n.length>0){let e=this.getState(),t=qd(e.sessions,n,i??new Date().toISOString()),r=Yd(t,e.selectedSession?.id,n);this.setState({sessions:t}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`Archive`,r)}catch(e){this.setState({error:`Archive failed: ${mf(e)}`})}}async deleteArchivedSessions(e){let t=ff(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=L(this.getState());try{let{succeededIds:e,failures:r}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=r.find(e=>e.archived!==!0)??r[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}}this.applyBulkSessionFailures(`Delete`,r)}catch(e){this.setState({error:`Delete failed: ${mf(e)}`})}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:pf(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:pf(n.failures)}}async applySessionCleanupResult(e,t=L(this.getState())){if(L(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=qd(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:nf(t.sessionStatuses,a),sessionActivities:nf(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=Yd(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=L(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Ec(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(L(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){L(this.getState())===e&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(n)})}finally{this.hydrateSessionStatuses(e)}}async loadInterruptedRuns(e=L(this.getState())){try{let t=await this.api.interruptedRuns(e);return new Set(t.runs.map(e=>e.sessionId))}catch{return new Set}}async hydrateSessionStatuses(e=L(this.getState()),t){let n;try{n=await this.api.statusCatalog(e)}catch{return}if(L(this.getState())!==e)return;let r=this.getState(),i=t?.replaceKnown===!0,a={};for(let e of n.statuses)!i&&r.sessionStatuses[e.sessionId]!==void 0||(a[e.sessionId]=e);Object.keys(a).length!==0&&this.setState({sessionStatuses:{...r.sessionStatuses,...a}})}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Nd(e,this.statusForSession(e)))return;let t=z(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,L(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Tc(e.id,L(this.getState())),Sl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:tf(n.sessionStatuses,e.id),sessionActivities:ef(n.sessionActivities,e.id),sendingPrompts:tf(n.sendingPrompts,e.id),clientQueuedSessionMessages:tf(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.restore(e,L(this.getState()));let t={...e};delete t.archived,delete t.archivedAt,this.replaceSession(t),this.getState().selectedSession?.id===t.id&&await this.selectSession(t)}catch(e){this.setState({error:String(e)})}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Md(e,this.statusForSession(e)))return;let t=L(this.getState());try{await this.api.reloadSession(e,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(e){this.setState({error:String(e)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await this.api.detachParent(e,L(this.getState()));let t={...e};delete t.parentSessionPath,this.replaceSession(t)}catch(e){this.setState({error:String(e)})}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.models(e,L(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.modelCatalog(e,L(this.getState()))).models}catch(e){return this.setState({error:String(e)}),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{return(await this.api.setModelEnabled(r,e,t,n,L(this.getState()))).models}catch(e){this.setState({error:String(e)});return}}async setModel(e,t){let n=this.getState().selectedSession;if(!(!n||n.archived===!0))try{this.applyStatus(await this.api.setModel(n,e,t,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async cycleModel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleModel(t,e,L(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(e){this.setState({error:String(e)})}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await this.api.thinkingLevels(e,L(this.getState()))).levels}catch(e){return this.setState({error:String(e)}),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(t,e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(e,L(this.getState())))}catch(e){this.setState({error:String(e)})}}checkSocketLiveness(){this.socket.checkLiveness?.()}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||z(t))return;let n=L(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.isCurrentSessionSelection(t.id,n,r)&&this.setState({error:String(e)})}}async recallQueuedMessage(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||n.archived===!0||z(n))return!1;let r=L(t),i=this.selectionSeq;try{let{recalled:t,status:a}=await this.api.recallQueuedMessage(n,e,r);if(!this.isCurrentSessionSelection(n.id,r,i))return!1;let o=e.clientMessageId;return t&&o!==void 0&&this.setState({messages:Gl(this.getState().messages,o)}),this.applyStatus(a),t}catch(e){return this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)}),!1}}async openSubagentRunOutput(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t);try{let t=await this.api.subagentRunOutput(n,e.runId,r);this.setState({messages:[...this.getState().messages,Rc(`tool`,`Subagent ${e.agent} (${e.runId.slice(0,8)}):\n\n${t}`)]})}catch(e){this.setState({error:String(e)})}}async openBackgroundTaskOutput(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t);try{let t=await this.api.backgroundTaskOutput(n,e.id,r);this.setState({messages:[...this.getState().messages,Rc(`tool`,`Background task ${e.name} (${e.id}):\n\n${t}`)]})}catch(e){this.setState({error:String(e)})}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||z(n))return;let r=L(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.isCurrentSessionSelection(n.id,r,i)&&this.setState({error:String(e)})}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(z(r)){await this.closePendingStartDialog(r,e,t);return}let i=L(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;let n=e.outcome;if(n!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===n.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:n.reason,...n.answer===void 0?{}:{answer:n.answer}})}this.applyStatus(e.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let o=t.outcome;if(o!==void 0){let e=this.getState().pendingDialogs.find(e=>e.dialogId===o.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:o.reason,...o.answer===void 0?{}:{answer:o.answer}})}this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){a===this.selectionSeq&&this.getState().selectedSession?.id===e.id&&this.setState({error:String(t)})}}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||z(r))return;let i=L(n),a=this.selectionSeq;try{let n=await t(r,i);kl(Vs(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.isCurrentSessionSelection(r.id,i,a)&&this.setState({error:String(e)})}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return[];try{let t=await this.api.abort(e,L(this.getState()));for(let e of t.discarded)e.clientMessageId!==void 0&&this.setState({messages:Gl(this.getState().messages,e.clientMessageId)});return t.discarded}catch(e){return this.setState({error:String(e)}),[]}}refreshSelectedSession(e=this.getState().selectedSession?.id){let t=this.getState().selectedSession;if(e===void 0||t?.id!==e||t.archived===!0||z(t))return Promise.resolve();let n={session:t,machineId:L(this.getState()),selectionSeq:this.selectionSeq};return this.requestSelectedSessionRefresh(n).catch(e=>{this.isCurrentRefreshTarget(n)&&this.setState({error:String(e)})})}requestSelectedSessionRefresh(e){let t=Vs(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:Xd},e.machineId),this.api.status(e.session,e.machineId),this.api.streamSnapshot(e.session,e.machineId),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r)})}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return L(n)===t&&r?.id===e&&r.archived!==!0&&!z(r)}applyBulkSessionFailures(e,t){t.length!==0&&this.setState({error:`${e} failed for ${String(t.length)} session${t.length===1?``:`s`}: ${t.join(`; `)}`})}sessionCacheKey(e){return Vs(L(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}workspaceSelectionKey(e){return`${L(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`New session`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:sf(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:sf(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Sl(Vs(n.machineId,e)),this.setState({clientQueuedSessionMessages:tf(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Cc(t,n.machineId),Cl(Vs(n.machineId,e),Vs(n.machineId,t.id));let a=wc(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:tf(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:af(o.sessions,e,a),sessionActivities:ef(o.sessionActivities,e),sendingPrompts:rf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:rf(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:o.sessionStatuses[a.id]?.pendingAsk,pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r||!a){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=this.getState(),s=mf(t),c=cf(e,s,n.queuedSends.length),l=o.sessions.some(t=>t.id===e);this.setState({sessions:l?o.sessions:[n.session,...o.sessions],sessionActivities:{...o.sessionActivities,[e]:c},activity:o.selectedSession?.id===e?c:o.activity,...o.selectedSession?.id===e?{pendingDialogs:[]}:{},error:`Failed to start session: ${s}`}),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return L(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||L(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>z(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){try{let n=L(this.getState()),r=await this.api.startSession(e.cwd,n);Cc(r,n),Cl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Tc(e.id,n);let i=wc(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(e){this.setState({error:String(e)})}}markCachedNewSessionPersisted(e){if(!Dc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Oc(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,Rc(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&xl(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=L(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=n?Kl(t.messages,e.queuedMessages):t.messages,i=t.sessionActivities[e.sessionId]?.phase===`active`&&!Is(e),a=n&&Is(t.status??e)&&!Is(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...hf(t,e.sessionId,e.messageCount),...i?{sessionActivities:ef(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&i?void 0:t.activity,...n?{pendingAsk:e.pendingAsk}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{},...r===t.messages?{}:{messages:r}}),a&&this.onSelectedSessionIdle?.()}markDelivery(e,t,n){let r=this.getState();if(r.selectedSession?.id!==e)return;let i=Bl(r.messages,t,n);i!==r.messages&&this.setState({messages:i})}applyOpenedDialog(e){let t=this.getState();t.selectedSession!==void 0&&(t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]}))}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),...$d(e)?{closedDialogs:[...t.closedDialogs,e]}:{}})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){this.getState().selectedSession!==void 0&&this.setState({pendingAsk:e})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}async renameSession(e,t,n=L(this.getState())){let r=t.trim();if(r===``)return;let i=e.name;this.applySessionName(e.id,r);try{await this.api.runCommand({id:e.id,cwd:e.cwd},`/name ${r}`,n)}catch(t){this.applySessionName(e.id,i),this.setState({error:String(t)})}}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(L(this.getState()),e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(gf(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?sf(t.tempId,t.queuedSends.length):of(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame??=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}),this.pendingFlushTimer??=setTimeout(()=>{this.pendingFlushTimer=void 0,this.flushPendingUpdates()},Zd)}cancelScheduledFlush(){this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0),this.pendingFlushTimer!==void 0&&(clearTimeout(this.pendingFlushTimer),this.pendingFlushTimer=void 0)}flushPendingUpdates(){if(this.cancelScheduledFlush(),this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.cancelScheduledFlush()}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}};function $d(e){return e.reason!==`timeout`||e.dialog.runScoped}function ef(e,t){return tf(e,t)}function tf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function nf(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function rf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...tf(e,t),[n]:r}}function af(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function z(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function of(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function sf(e,t=0){return{sessionId:e,phase:`active`,label:`Creating session`,detail:t>0?`${String(t)} queued ${t===1?`message`:`messages`} will send when the backend session is ready`:`Waiting for the backend session to be ready`,at:new Date().toISOString()}}function cf(e,t,n=0){return{sessionId:e,phase:`error`,label:`Session creation failed`,detail:`${t}${n>0?` · ${String(n)} queued ${n===1?`message`:`messages`} kept below`:``}`,at:new Date().toISOString()}}function lf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:uf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function uf(e,t){let n=df(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function df(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} ${n===1?`attachment`:`attachments`}`;return t.length===0?`[${r} queued]`:`[${r} queued: ${t.slice(0,3).join(`, `)}${t.length>3?`, +${String(t.length-3)} more`:``}]`}function ff(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function pf(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function mf(e){return e instanceof Error?e.message:String(e)}function hf(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function gf(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function _f(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var vf={order:0,overflowWatermark:0};function yf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:vf,optimisticDismissedIds:[],announcements:[]}}function bf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Pf(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function xf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??yf(t),needsRefresh:!1,changed:!1};if(e===void 0||!Pf(e,t))return{value:If(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:If(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!Lf(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Sf(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=zf(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...Bf(Rf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Cf(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function wf(e){return`${Cf(e.severity)} notification received.`}function Tf(e){return e.retainedCount+e.discardedCount}function Ef(e){return`Notifications (${String(Tf(e))})`}function Df(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${Cf(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Of(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function kf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Af(e,t){return e.has(kf(t))}function jf(e,t,n){let r=new Set(e),i=kf(t);return n?r.add(i):r.delete(i),r}function Mf(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Nf(e){if(!e.truncated)return;let t=Dt/1024;return`Message truncated at ${String(t)} KiB.`}function Pf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Ff(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function If(e){return{...yf(e),status:`stale`}}function Lf(e,t){return e.length===t.retainedCount&&Rf(e)===t.highestSeverity}function Rf(e){let t;for(let n of e)t=Ff(t,n.severity);return t}function zf(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function Bf(e){return e===void 0?{}:{highestSeverity:e}}var Vf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??I,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:yf(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=xf(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineIsReachableInState(e,r.machineId);if(!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Sf(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=Hf(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`Failed to dismiss notification: ${Wf(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Sf(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=Hf(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`Failed to dismiss session notifications: ${Wf(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}let i=this.getState().selectedNotificationInbox,a=i===void 0||Uf(i,t,r)?bf(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=xf(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Pf(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Pf(r,e))return;if(!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=Uf(r,e,t)?bf(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Pf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Pf(t,e))&&this.setState({selectedNotificationInbox:yf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Pf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Pf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Pf(this.selectedTarget,e)}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function Hf(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function Uf(e,t,n){return!Pf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function Wf(e){return e instanceof Error?e.message:String(e)}var Gf=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},Kf=`pi-web:workspace-selection:v1`,qf=class{constructor(e=Pd()){this.workspaceIdsByProject=new Fd(Kf,Id,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function Jf(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var Yf=50,Xf=class{constructor(e,t,n,r,i=new Gf,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.api=a.api??I,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.topologyRefreshes=new pc(a.topologyRefreshDebounceMs??Yf)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Ps()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Bs(L(this.getState()),e));let t=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:t})}async selectProject(e,t){let n=L(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Ps()});try{let r=await this.api.workspaces(e.id,n);if(L(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=Jf(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bs(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({error:String(t),isLoadingWorkspaces:!1})}}async selectWorkspace(e,t){let n=L(this.getState());this.workspaceSelection.rememberWorkspace({...e,projectId:Bs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Ps()});try{let r=Ec(e.path,await this.api.sessions(e.path,n),n);if(L(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){L(this.getState())===n&&this.getState().selectedWorkspace?.id===e.id&&this.setState({error:String(t)})}finally{this.refreshWorkspaceGoals(e,n)}}async refreshWorkspaceGoals(e=this.getState().selectedWorkspace,t=L(this.getState())){if(e===void 0)return;this.setState({workspaceGoalsLoading:!0});let n;try{n=(await this.api.workspaceGoals(e.projectId,e.id,t)).goals}catch{n=[]}L(this.getState())!==t||this.getState().selectedWorkspace?.id!==e.id||this.setState({workspaceGoals:n,workspaceGoalsLoading:!1})}async archiveWorkspaceGoal(e,t=this.getState().selectedWorkspace){if(t===void 0)return;let n=L(this.getState());try{(await this.api.archiveWorkspaceGoal(t.projectId,t.id,e,n)).agentMayRecreate&&this.setState({error:`Goal archived. A session already working it keeps its own copy until it reloads, so run /goal-refresh there if it comes back.`})}catch(e){this.setState({error:`Could not archive the goal: ${e instanceof Error?e.message:String(e)}`})}await this.refreshWorkspaceGoals(t,n)}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`Project not found`);let n=await this.api.workspaces(t.id,L(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=L(e);await this.topologyRefreshes.request(Bs(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(L(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=Zf(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||Qf(e,n)))return{selectedWorkspace:n}}};function Zf(e){return e.find(e=>e.isMain)??e[0]}function Qf(e,t){return $f(e,t)}function $f(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>$f(e,t[n]));if(!ep(e)||!ep(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&$f(e[n],t[n]))}function ep(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var tp=`pi-web:machine-navigation:v1`,np=class{constructor(e=Pd()){this.snapshotsByMachine=new Fd(tp,sp,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?op(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,op(e))}forget(e){this.snapshotsByMachine.delete(e)}};function rp(e){return{machineId:e,surface:{}}}function ip(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function ap(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view===`navigation`?void 0:e.view}}function op(e){return{...e,surface:{...e.surface}}}function sp(e){if(!pp(e))return;let t=fp(e,`machineId`);if(t===void 0)return;let n=up(fp(e,`tool`)),r=lp(fp(e,`view`));return{machineId:t,projectId:fp(e,`projectId`),workspaceId:fp(e,`workspaceId`),sessionId:fp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:cp(e.surface)}}function cp(e){return pp(e)?{selectedFilePath:fp(e,`selectedFilePath`),selectedTerminalId:fp(e,`selectedTerminalId`)}:{}}function lp(e){return e===`navigation`||e===`chat`?e:up(e)}function up(e){return dp(e)?e:void 0}function dp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function fp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function pp(e){return typeof e==`object`&&!!e}var mp=`pi-web:terminal-selection:v1`,hp=class{constructor(e=Pd()){this.terminalIdsByCwd=new Fd(mp,Id,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function gp(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function _p(e){return e.find(e=>!e.exited)??e[0]}var vp=1200,yp=[`mod`,`alt`,`shift`],bp=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Tp(e);if(r===void 0)return!1;let i=xp(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!Ep(r))return!1}else if(!Ep(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>Up(t.tokens,e));return n===void 0?t.some(t=>Wp(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},vp)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function xp(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Dp(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(jp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(Mp),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Np(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:Ap(t),i=n?[...s.get(e)??[]].sort(jp).map(Ap):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Sp(e){return Ip(e,{requireFirstChordActivator:!0})}function Cp(e){let t=Ip(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function wp(e){return Cp(e).map(e=>e.split(`+`).map(Hp).join(`+`)).join(` `)}function Tp(e){if(e.isComposing)return;let t=Bp(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function Ep(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Dp(e,t,n){let r=Op(e,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Cp(i),o=a[0];if(!(o===void 0||!Ep(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:kp(a),order:n}}function Op(e,t){if(t!==void 0){for(let n of[e.id,...e.shortcutAliases??[]])if(Object.hasOwn(t,n))return t[n]}}function kp(e){return e.join(`\0`)}function Ap(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function jp(e,t){return Pp(e.source)-Pp(t.source)||Fp(e.action.id,t.action.id)||Fp(e.action.title,t.action.title)||e.order-t.order}function Mp(e,t){return e.tokens.length-t.tokens.length||jp(e,t)}function Np(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&Wp(e.tokens,t.tokens))}function Pp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Fp(e,t){return e<t?-1:+(e>t)}function Ip(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`Enter a shortcut, choose None, or reset to the default.`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=Lp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Ep(i.token))return{ok:!1,message:`Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured.`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function Lp(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`Shortcut chords must include a key.`};let n=new Set,r;for(let e of t){let t=Rp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${Hp(t)} modifiers.`};n.add(t);continue}let i=zp(e);if(i===void 0)return{ok:!1,message:`Unsupported shortcut key: ${e}`};if(r!==void 0)return{ok:!1,message:`Each shortcut chord can include only one non-modifier key.`};r=i}return r===void 0?{ok:!1,message:`Shortcut chords must include a key.`}:{ok:!0,token:[...yp.filter(e=>n.has(e)),r].join(`+`)}}function Rp(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function zp(e){let t=Vp(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Bp(e){return e===` `?`space`:zp(e.toLowerCase())}function Vp(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function Hp(e){return e===`mod`?Gp()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?Gp()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Up(e,t){return e.length===t.length&&Wp(e,t)}function Wp(e,t){return t.every((t,n)=>e[n]===t)}function Gp(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function Kp(e,t,n=24){if(t===void 0||!Number.isFinite(e)||e<=0||!Number.isFinite(t.height)||t.height<=0)return 0;let r=e-(t.offsetTop+t.height);return!Number.isFinite(r)||r<n?0:Math.min(r,e)}var qp={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Jp(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`Enable at least one cleanup action.`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=nm(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=nm(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Yp(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Xp(e){if(e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Jp(e.draft);return!t.ok||Yp(t.request)!==Yp(e.previewRequest)?!1:Zp(e.preview)}function Zp(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Qp(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function $p(e,t){let n=new Set(Qp(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function em(e,t){return t(tm(e))}function tm(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`archive ${String(t)} idle ${t===1?`session`:`sessions`}`),n>0&&r.push(`permanently delete ${String(n)} archived ${n===1?`session`:`sessions`}`),`Run cleanup and ${r.length===0?`run cleanup`:r.join(` and `)}?\n\nPermanent deletion only applies to archived sessions and cannot be undone.`}function nm(e,t){let n=e.trim();if(n===``)return`${t} must be set.`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t} must be a non-negative whole number of days.`:r}var rm=new Set,im=Tt+1,am={unreadCatalog:e=>Eo.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Eo.acknowledgeUnread(e,t,n,r)},om=class{constructor(e={}){this.machines=new Map,this.api=e.api??am,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return rm;let r=new Set;for(let e of t)n.summariesByIdentity.has(fm(e))&&r.add(e.id);return r.size===0?rm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(fm(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=sm(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(fm(t));if(i===void 0)return Promise.resolve();let a=pm(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=lm(t),a=`fresh`,o=!1;for(let e of n.events){let t=sm(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=im?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!dm(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function sm(e,t,n){if(e===void 0){let e=um(n.catalogId);return n.catalogRevision===1?cm(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=um(n.catalogId);return n.catalogRevision===1?cm(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?cm(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function cm(e,t,n){let r=new Map(e.summariesByIdentity),i=fm(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function lm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[fm(e),{...e}]))}}function um(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function dm(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function fm(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function pm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}function mm(){return{selectedSessionKey:void 0,warningSetSignature:hm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function hm(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function gm(e,t,n){let r=hm(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function _m(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function vm(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function ym(e){return e.collapsed?vm(e):_m(e)}var bm=`themes:classic`,xm={themeId:`themes:pi-web-dark`,auto:!0},Sm=`pi-web-app-theme`,Cm=`--pi-bg.--pi-surface.--pi-surface-hover.--pi-terminal-bg.--pi-terminal-text.--pi-border.--pi-border-muted.--pi-text.--pi-text-secondary.--pi-text-bright.--pi-muted.--pi-dim.--pi-accent.--pi-accent-border.--pi-selection-bg.--pi-success.--pi-success-border.--pi-success-bg.--pi-success-surface.--pi-success-ring.--pi-warning.--pi-warning-border.--pi-warning-surface.--pi-danger.--pi-purple.--pi-purple-border.--pi-purple-surface.--pi-overlay.--pi-shadow-soft.--pi-shadow.--pi-shadow-strong.--pi-bg-overlay-soft.--pi-bg-overlay.--pi-success-bg-overlay.--pi-terminal-selection`.split(`.`),wm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Tm(){try{let e=window.localStorage.getItem(Sm);return e===null?void 0:jm(e)}catch{return}}function Em(e){try{window.localStorage.setItem(Sm,JSON.stringify(e))}catch{}}function Dm(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of Cm){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function Om(e){let t=km(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=Am(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function km(e,t=bm){return e.find(e=>e.id===t)??e[0]}function Am(e,t){return e.find(e=>e.light===t||e.dark===t)}function jm(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return Mm(e)?e:void 0}catch{return}}function Mm(e){if(!Nm(e))return!1;let t=e.themeId,n=e.auto;return Pm(t)&&typeof n==`boolean`}function Nm(e){return typeof e==`object`&&!!e}function Pm(e){return typeof e==`string`&&wm.test(e)}var Fm=`workspace.delete`,Im=`pi.operation`,Lm=`target.workspaceId`;function Rm(e){return e?.removal!==void 0&&!e.isMain}function zm(e){return e.removal?.confirmation}function Bm(e){return{...e===void 0?{}:{projectId:e},metadata:{[Im]:Fm}}}function Vm(e){let t={};for(let n of e){let e=Wm(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Hm(e){return Object.entries(e).filter(([,e])=>Gm(e)).map(([e])=>e)}function Um(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Gm(n)}function Wm(e){return e.metadata[Lm]}function Gm(e){return e.status===`queued`||e.status===`running`}function Km(){return[{id:`actions.show`,title:`Show Actions`,description:`Open the command palette`,shortcut:`mod+k`,group:`General`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`Focus Prompt`,description:`Move keyboard focus to the message composer`,shortcut:`mod+g c`,group:`General`,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`Add Machine`,description:`Register another PI WEB runtime reachable from this gateway`,group:`Machine`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`Refresh Selected Machine`,description:`Check whether the selected PI WEB runtime is online`,group:`Machine`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`Open Selected Machine PI WEB`,description:`Open the selected remote PI WEB directly in a new tab`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`Remove Selected Machine`,description:`Remove the selected remote machine from this gateway`,group:`Machine`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`Add Project`,group:`Project`,run:e=>e.addProject()},{id:`auth.login`,title:`Configure Provider Authentication`,description:`Run /login without tying authentication to a session`,group:`General`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`Remove Provider Authentication`,description:`Run /logout for stored pi credentials`,group:`General`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`Select Theme`,description:`Choose the PI WEB color theme`,group:`Preferences`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`Open Settings`,description:`Manage PI WEB configuration and keyboard shortcuts`,shortcut:`mod+,`,group:`Preferences`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`Full Page Reload`,description:`Reload the PI WEB browser page`,group:`General`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`Go to Chat`,shortcut:`mod+1`,group:`Navigation`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`Go to Files`,shortcut:`mod+2`,group:`Navigation`,enabled:qm,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+3`,group:`Navigation`,enabled:qm,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:qm,run:e=>e.refreshFiles()},{id:`workspace.delete`,title:`Remove Workspace`,description:`Run the owning provider's workspace removal operation`,group:`Workspace`,enabled:Jm,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:qm,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:Ym,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:Ym,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:Xm,run:e=>e.archiveSession()},{id:`session.reload`,title:`Reload Session from Disk`,description:`Close and re-open the selected session from its session file. Use /reload in the prompt for Pi runtime resources.`,group:`Session`,enabled:Qm,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:Zm,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&Is(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function qm(e){return e.state.selectedWorkspace!==void 0}function Jm(e){let t=e.state.selectedWorkspace;return Rm(t)&&!Um(e.state,t)}function Ym(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Xm(e){return Md(e.state.selectedSession,e.state.status)}function Zm(e){return Nd(e.state.selectedSession,e.state.status)}function Qm(e){return Md(e.state.selectedSession,e.state.status)?!Is(e.state.status,e.state.activity):!1}function $m(e){return typeof e==`string`?eh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function eh(e){switch(e){case`navigation`:return Ye`
|
|
22
22
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
23
23
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
24
24
|
<path d="M10 7h8"></path>
|
|
@@ -966,7 +966,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
966
966
|
.viewer-header { align-items: flex-start; flex-direction: column; }
|
|
967
967
|
.viewer-actions { width: 100%; flex-wrap: wrap; }
|
|
968
968
|
}
|
|
969
|
-
`]}};U([b({attribute:!1})],q_.prototype,`machineId`,void 0),U([b({attribute:!1})],q_.prototype,`projectId`,void 0),U([b({attribute:!1})],q_.prototype,`workspaceId`,void 0),U([b({attribute:!1})],q_.prototype,`selectedPath`,void 0),U([b({attribute:!1})],q_.prototype,`file`,void 0),U([b({attribute:!1})],q_.prototype,`loadError`,void 0),U([b({attribute:!1})],q_.prototype,`previewUrlBuilder`,void 0),U([b({attribute:!1})],q_.prototype,`modeStore`,void 0),q_=U([y(`workspace-file-viewer`)],q_);function J_(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function Y_(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function X_(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Z_(e){return e===`html`?``:void 0}function Q_(e){return e===`image`||e===`html`||e===`pdf`}function $_(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${nh(e.size)}${e.truncated?` · truncated`:``}`}function ev(){K_(()=>import(`./CodeViewer-
|
|
969
|
+
`]}};U([b({attribute:!1})],q_.prototype,`machineId`,void 0),U([b({attribute:!1})],q_.prototype,`projectId`,void 0),U([b({attribute:!1})],q_.prototype,`workspaceId`,void 0),U([b({attribute:!1})],q_.prototype,`selectedPath`,void 0),U([b({attribute:!1})],q_.prototype,`file`,void 0),U([b({attribute:!1})],q_.prototype,`loadError`,void 0),U([b({attribute:!1})],q_.prototype,`previewUrlBuilder`,void 0),U([b({attribute:!1})],q_.prototype,`modeStore`,void 0),q_=U([y(`workspace-file-viewer`)],q_);function J_(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function Y_(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function X_(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Z_(e){return e===`html`?``:void 0}function Q_(e){return e===`image`||e===`html`||e===`pdf`}function $_(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${nh(e.size)}${e.truncated?` · truncated`:``}`}function ev(){K_(()=>import(`./CodeViewer-DTv-zPMN.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var tv=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=sv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{cv(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{cv(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{cv(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!cv(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=sv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&av(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&ov(t)!==ov(this.context)&&this.resetPendingUpload()}updated(){this.syncUploadModal()}disconnectedCallback(){this.releaseUploadModal(),super.disconnectedCallback()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
|
|
970
970
|
<section
|
|
971
971
|
class=${this.dragActive?`files-panel dragging`:`files-panel`}
|
|
972
972
|
@dragenter=${this.handleDragEnter}
|
|
@@ -1136,7 +1136,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1136
1136
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1137
1137
|
.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; }
|
|
1138
1138
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1139
|
-
`]}};U([b({attribute:!1})],tv.prototype,`context`,void 0),U([S(`#workspace-upload-input`)],tv.prototype,`uploadInput`,void 0),U([S(`.dialog-backdrop`)],tv.prototype,`uploadDialogBackdrop`,void 0),U([S(`.upload-dialog`)],tv.prototype,`uploadDialog`,void 0),U([x()],tv.prototype,`pendingUpload`,void 0),U([x()],tv.prototype,`destinationFolder`,void 0),U([x()],tv.prototype,`overwrite`,void 0),U([x()],tv.prototype,`createDirs`,void 0),U([x()],tv.prototype,`formError`,void 0),U([x()],tv.prototype,`dragActive`,void 0),tv=U([y(`workspace-files-panel`)],tv);function nv(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 rv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{_s(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function iv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function av(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function ov(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function sv(e){return e==null?[]:Array.from(e)}function cv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function lv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function uv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function dv(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function fv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return gv(e.percent)}}function pv(e){return e.status===`uploading`?e.percent:1}function mv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return gv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function hv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${nh(e.loaded)} / ${nh(e.total)}`:`Wrote ${e.response.path}`:e.error}function gv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function _v(){return[{id:`workspace.files`,title:`Files`,icon:eh(`files`),order:10,routeAliases:[`files`],render:vv},{id:`workspace.terminal`,title:`Terminal`,icon:eh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:yv}]}function vv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function yv(e){return bv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function bv(){K_(()=>import(`./TerminalPanel-CDO2UjCh.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var xv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Km(),workspacePanels:_v()}})},Sv={"--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`},Cv={"--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`},wv={"--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`},Tv={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},Ev={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},Dv={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},Ov={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:Cv},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:wv},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Sv},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:Tv},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:Ev},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:Dv}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function kv(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await Mv(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=Av(e.module,n),a=Lv(await(t.moduleLoader??jv)(r),r);i.push({id:t.machineId===void 0?e.id:Rs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function Av(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function jv(e){return K_(()=>import(e),[],import.meta.url)}async function Mv(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await Pv(t));return Nv(await t.json())}}function Nv(e){if(!zv(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!zv(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!Jt(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Yt(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...Fv(e.backendRevision),machineSpecific:Iv(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function Pv(e){let t;try{let n=await e.json();if(zv(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function Fv(e){if(e===void 0)return{};try{return{backendRevision:qo(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function Iv(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function Lv(e,t){if(!zv(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(zv(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!Rv(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function Rv(e){return zv(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function zv(e){return typeof e==`object`&&!!e}var Bv=/^[a-z][a-z0-9.-]*$/u,Vv=/^[a-z][a-z0-9.-]*$/u,Hv=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,Uv=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,Wv=new WeakMap,Gv=new WeakMap,Kv=new WeakMap,qv=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&ty(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=iy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Jv(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.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),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))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}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,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=ey(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Yv(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Yv(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Yv(t,u)):void 0},render:e=>t.render(Yv(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=ey(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Xv(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Xv(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}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)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!ny(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(ny)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!Uv.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!Bv.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Vv.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return qo(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${ry(t)}`);return t}};function Jv(e,t){return Wv.get(e)?.(t)??e}function Yv(e,t){return Gv.get(e)?.(t)??e}function Xv(e,t){return Kv.get(e)?.(t)??e}function Zv(e,t){return Wv.set(e,t),e}function Qv(e,t){return Gv.set(e,t),e}function $v(e,t){return Kv.set(e,t),e}function ey(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function ty(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function ny(e){return Hv.test(e)}function ry(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 iy(e){return e.state.selectedMachine?.id??`local`}function ay(e,t,n,r=ns){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function oy(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var sy=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function cy(){return typeof window>`u`||!(`matchMedia`in window)?[]:sy.map(e=>window.matchMedia(e))}function ly(e,t=uy()){return e.some(e=>e.matches)||dy(t)}function uy(){return typeof navigator>`u`?void 0:navigator}function dy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var fy=class{constructor(e=py()){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 py(){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 my=`(max-width: 760px)`,hy=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ly(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??gy(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??cy(),this.viewportPositionRepairer=t.viewportPositionRepairer??new fy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=ly(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function gy(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(my)}var _y=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new pc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??vy(),this.documentTarget=t.documentTarget??yy(),this.isDocumentVisible=t.isDocumentVisible??by,this.scheduleFrame=t.scheduleFrame??xy}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 vy(){return typeof window>`u`?void 0:window}function yy(){return typeof document>`u`?void 0:document}function by(){return typeof document>`u`||document.visibilityState===`visible`}function xy(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 Sy=[`machines`,`projects`,`workspaces`,`sessions`];function Cy(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function wy(e,t){if(e!==`none`)return e??Cy(t)}function Ty(e,t){return wy(t.expanded,t.state)!==e}function Ey(e,t,n){return wy(e,n.state)===t?`none`:t}function Dy(e){return e.workspaceCount===1?`sessions`:`workspaces`}function Oy(e){return Sy[Sy.indexOf(e)+1]}var ky=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return wy(this.expanded,this.getState())}isCollapsed(e){return Ty(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(Ey(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?Dy({workspaceCount:t?.workspaceCount}):Oy(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},Ay=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,t=!0){return[`shell`,My(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...jy(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function jy(e,t){return!e&&t}function My(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Ny=`pi-web:panel-sizes:v1`,Py={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Fy=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Yy(),this.panelSizes=Vy(this.storage)}hostConnected(){}constraints(e){return Iy(e)}panelWidth(e,t){return By(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=By(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Gy(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Ky(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(){Hy(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Jy(By(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Jy(By(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Iy(e){return Py[e]}function Ly(e,t,n){return e===`navigation`?n-t:t-n}function Ry(e,t,n,r,i=Iy(e)){return By(e,t+Ly(e,n,r),i)}function zy(e,t,n,r={}){let i=r.constraints??Iy(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=qy(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return By(e,t+a,i)}function By(e,t,n=Iy(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Vy(e=Yy()){try{let t=e?.getItem(Ny);return t==null||t===``?{}:Uy(JSON.parse(t))}catch{return{}}}function Hy(e,t=Yy()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ny);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=By(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=By(`workspace`,e.workspacePanelWidth)),t.setItem(Ny,JSON.stringify(n))}catch{}}function Uy(e){if(!Xy(e)||e.version!==1)return{};let t={},n=Wy(e.navigationPanelWidth),r=Wy(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=By(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=By(`workspace`,r)),t}function Wy(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Gy(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Ky(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function qy(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 Jy(e){return`${String(Math.round(e))}px`}function Yy(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Xy(e){return typeof e==`object`&&!!e}function Zy(){let e=new URLSearchParams(window.location.search);return{machineId:tb(e.get(`machine`)),projectId:tb(e.get(`project`)),workspaceId:tb(e.get(`workspace`)),sessionId:tb(e.get(`session`)),tool:tb(e.get(`tool`)),view:tb(e.get(`view`))}}function Qy(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:$y(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:$y(e.view,t)}}function $y(e,t){return t(e)??(nb(e)?e:void 0)}function eb(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&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&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 tb(e){return e===null||e===``?void 0:e}function nb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function rb(){return ab(new URLSearchParams(window.location.search).get(`settings`))}function ib(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 ab(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function ob(e,t){return t===void 0?e:e.map(e=>cb(e,t))}function sb(e,t){let n=new Set(xp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return ob(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?lb(e):e)}function cb(e,t){let n=Op(e,t);return n===void 0?e:n===null?lb(e):{...e,shortcut:n}}function lb(e){let t={...e};return delete t.shortcut,t}function ub(e,t){let n=t.api??Do,r=t.pollIntervalMs??1e3,i=t.setTimeout??pb(),a=t.clearTimeout??mb();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:db(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function db(e,t,n,r,i){return fb(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&&fb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function fb(e){return e.status===`succeeded`||e.status===`failed`}function pb(){return(e,t)=>globalThis.setTimeout(e,t)}function mb(){return e=>{globalThis.clearTimeout(e)}}var hb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},gb=class{constructor(e){this.open=e,this.longPress=new hb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},_b=0,vb=120;function yb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?xb():bb(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-_b,f=n.top-c-_b;return[...d<vb&&f>d?[`bottom: ${Sb(a-n.top+_b)};`,`max-height: ${Sb(Math.max(0,f))};`]:[`top: ${Sb(n.bottom+_b)};`,`max-height: ${Sb(Math.max(0,d))};`],`right: ${Sb(Math.max(0,i-u))};`,`max-width: ${Sb(Math.max(0,u-o))};`].join(` `)}function bb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():xb()}function xb(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Sb(e){return`${String(Math.round(e))}px`}function Cb(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function wb(e){if(e!==void 0)return e[Nt.working]===!0?`session`:e[Nt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==Nt.unread)?`session`:void 0}function Tb(e){return e?.[Nt.unread]===!0}var Eb={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function Db(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:Eb[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function Ob(e,t=`Active`,n){let r=Cb(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var kb=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Ab(e){return e.composedPath().some(e=>jb(e,kb))}function jb(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 Mb(e,t){return Ab(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?Pb(e,()=>{Fb(e.currentTarget,-1)}):e.key===`ArrowDown`?Pb(e,()=>{Fb(e.currentTarget,1)}):e.key===`Home`?Pb(e,()=>{Ib(e.currentTarget,0)}):e.key===`End`?Pb(e,()=>{Ib(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?Pb(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?Pb(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&Pb(e,t.cancel)}function Nb(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 Pb(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Fb(e,t){let n=Rb(e),r=Bb(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||Lb(n,i+t)}function Ib(e,t){let n=Rb(e);n.length!==0&&Lb(n,t<0?n.length-1:t)}function Lb(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function Rb(e){let t=Bb(e)?.getRootNode();return t===void 0||!zb(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function zb(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function Bb(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var Vb=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new gb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Nb(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1139
|
+
`]}};U([b({attribute:!1})],tv.prototype,`context`,void 0),U([S(`#workspace-upload-input`)],tv.prototype,`uploadInput`,void 0),U([S(`.dialog-backdrop`)],tv.prototype,`uploadDialogBackdrop`,void 0),U([S(`.upload-dialog`)],tv.prototype,`uploadDialog`,void 0),U([x()],tv.prototype,`pendingUpload`,void 0),U([x()],tv.prototype,`destinationFolder`,void 0),U([x()],tv.prototype,`overwrite`,void 0),U([x()],tv.prototype,`createDirs`,void 0),U([x()],tv.prototype,`formError`,void 0),U([x()],tv.prototype,`dragActive`,void 0),tv=U([y(`workspace-files-panel`)],tv);function nv(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 rv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{_s(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function iv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function av(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function ov(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function sv(e){return e==null?[]:Array.from(e)}function cv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function lv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function uv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function dv(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function fv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return gv(e.percent)}}function pv(e){return e.status===`uploading`?e.percent:1}function mv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return gv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function hv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${nh(e.loaded)} / ${nh(e.total)}`:`Wrote ${e.response.path}`:e.error}function gv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function _v(){return[{id:`workspace.files`,title:`Files`,icon:eh(`files`),order:10,routeAliases:[`files`],render:vv},{id:`workspace.terminal`,title:`Terminal`,icon:eh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:yv}]}function vv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function yv(e){return bv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function bv(){K_(()=>import(`./TerminalPanel-7gR0021c.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var xv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Km(),workspacePanels:_v()}})},Sv={"--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`},Cv={"--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`},wv={"--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`},Tv={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},Ev={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},Dv={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},Ov={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:Cv},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:wv},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Sv},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:Tv},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:Ev},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:Dv}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function kv(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await Mv(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=Av(e.module,n),a=Lv(await(t.moduleLoader??jv)(r),r);i.push({id:t.machineId===void 0?e.id:Rs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function Av(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function jv(e){return K_(()=>import(e),[],import.meta.url)}async function Mv(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await Pv(t));return Nv(await t.json())}}function Nv(e){if(!zv(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!zv(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!Jt(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Yt(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...Fv(e.backendRevision),machineSpecific:Iv(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function Pv(e){let t;try{let n=await e.json();if(zv(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function Fv(e){if(e===void 0)return{};try{return{backendRevision:qo(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function Iv(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function Lv(e,t){if(!zv(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(zv(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!Rv(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function Rv(e){return zv(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function zv(e){return typeof e==`object`&&!!e}var Bv=/^[a-z][a-z0-9.-]*$/u,Vv=/^[a-z][a-z0-9.-]*$/u,Hv=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,Uv=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,Wv=new WeakMap,Gv=new WeakMap,Kv=new WeakMap,qv=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&ty(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=iy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Jv(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.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),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))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}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,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=ey(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Yv(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Yv(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Yv(t,u)):void 0},render:e=>t.render(Yv(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=ey(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Xv(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Xv(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}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)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!ny(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(ny)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!Uv.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!Bv.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Vv.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return qo(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${ry(t)}`);return t}};function Jv(e,t){return Wv.get(e)?.(t)??e}function Yv(e,t){return Gv.get(e)?.(t)??e}function Xv(e,t){return Kv.get(e)?.(t)??e}function Zv(e,t){return Wv.set(e,t),e}function Qv(e,t){return Gv.set(e,t),e}function $v(e,t){return Kv.set(e,t),e}function ey(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function ty(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function ny(e){return Hv.test(e)}function ry(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 iy(e){return e.state.selectedMachine?.id??`local`}function ay(e,t,n,r=ns){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function oy(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var sy=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function cy(){return typeof window>`u`||!(`matchMedia`in window)?[]:sy.map(e=>window.matchMedia(e))}function ly(e,t=uy()){return e.some(e=>e.matches)||dy(t)}function uy(){return typeof navigator>`u`?void 0:navigator}function dy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var fy=class{constructor(e=py()){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 py(){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 my=`(max-width: 760px)`,hy=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ly(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??gy(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??cy(),this.viewportPositionRepairer=t.viewportPositionRepairer??new fy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=ly(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function gy(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(my)}var _y=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new pc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??vy(),this.documentTarget=t.documentTarget??yy(),this.isDocumentVisible=t.isDocumentVisible??by,this.scheduleFrame=t.scheduleFrame??xy}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 vy(){return typeof window>`u`?void 0:window}function yy(){return typeof document>`u`?void 0:document}function by(){return typeof document>`u`||document.visibilityState===`visible`}function xy(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 Sy=[`machines`,`projects`,`workspaces`,`sessions`];function Cy(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function wy(e,t){if(e!==`none`)return e??Cy(t)}function Ty(e,t){return wy(t.expanded,t.state)!==e}function Ey(e,t,n){return wy(e,n.state)===t?`none`:t}function Dy(e){return e.workspaceCount===1?`sessions`:`workspaces`}function Oy(e){return Sy[Sy.indexOf(e)+1]}var ky=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return wy(this.expanded,this.getState())}isCollapsed(e){return Ty(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(Ey(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?Dy({workspaceCount:t?.workspaceCount}):Oy(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},Ay=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,t=!0){return[`shell`,My(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...jy(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function jy(e,t){return!e&&t}function My(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Ny=`pi-web:panel-sizes:v1`,Py={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Fy=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Yy(),this.panelSizes=Vy(this.storage)}hostConnected(){}constraints(e){return Iy(e)}panelWidth(e,t){return By(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=By(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Gy(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Ky(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(){Hy(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Jy(By(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Jy(By(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Iy(e){return Py[e]}function Ly(e,t,n){return e===`navigation`?n-t:t-n}function Ry(e,t,n,r,i=Iy(e)){return By(e,t+Ly(e,n,r),i)}function zy(e,t,n,r={}){let i=r.constraints??Iy(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=qy(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return By(e,t+a,i)}function By(e,t,n=Iy(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Vy(e=Yy()){try{let t=e?.getItem(Ny);return t==null||t===``?{}:Uy(JSON.parse(t))}catch{return{}}}function Hy(e,t=Yy()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ny);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=By(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=By(`workspace`,e.workspacePanelWidth)),t.setItem(Ny,JSON.stringify(n))}catch{}}function Uy(e){if(!Xy(e)||e.version!==1)return{};let t={},n=Wy(e.navigationPanelWidth),r=Wy(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=By(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=By(`workspace`,r)),t}function Wy(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Gy(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Ky(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function qy(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 Jy(e){return`${String(Math.round(e))}px`}function Yy(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Xy(e){return typeof e==`object`&&!!e}function Zy(){let e=new URLSearchParams(window.location.search);return{machineId:tb(e.get(`machine`)),projectId:tb(e.get(`project`)),workspaceId:tb(e.get(`workspace`)),sessionId:tb(e.get(`session`)),tool:tb(e.get(`tool`)),view:tb(e.get(`view`))}}function Qy(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:$y(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:$y(e.view,t)}}function $y(e,t){return t(e)??(nb(e)?e:void 0)}function eb(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&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&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 tb(e){return e===null||e===``?void 0:e}function nb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function rb(){return ab(new URLSearchParams(window.location.search).get(`settings`))}function ib(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 ab(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function ob(e,t){return t===void 0?e:e.map(e=>cb(e,t))}function sb(e,t){let n=new Set(xp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return ob(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?lb(e):e)}function cb(e,t){let n=Op(e,t);return n===void 0?e:n===null?lb(e):{...e,shortcut:n}}function lb(e){let t={...e};return delete t.shortcut,t}function ub(e,t){let n=t.api??Do,r=t.pollIntervalMs??1e3,i=t.setTimeout??pb(),a=t.clearTimeout??mb();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:db(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function db(e,t,n,r,i){return fb(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&&fb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function fb(e){return e.status===`succeeded`||e.status===`failed`}function pb(){return(e,t)=>globalThis.setTimeout(e,t)}function mb(){return e=>{globalThis.clearTimeout(e)}}var hb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},gb=class{constructor(e){this.open=e,this.longPress=new hb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},_b=0,vb=120;function yb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?xb():bb(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-_b,f=n.top-c-_b;return[...d<vb&&f>d?[`bottom: ${Sb(a-n.top+_b)};`,`max-height: ${Sb(Math.max(0,f))};`]:[`top: ${Sb(n.bottom+_b)};`,`max-height: ${Sb(Math.max(0,d))};`],`right: ${Sb(Math.max(0,i-u))};`,`max-width: ${Sb(Math.max(0,u-o))};`].join(` `)}function bb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():xb()}function xb(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Sb(e){return`${String(Math.round(e))}px`}function Cb(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function wb(e){if(e!==void 0)return e[Nt.working]===!0?`session`:e[Nt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==Nt.unread)?`session`:void 0}function Tb(e){return e?.[Nt.unread]===!0}var Eb={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function Db(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:Eb[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function Ob(e,t=`Active`,n){let r=Cb(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var kb=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Ab(e){return e.composedPath().some(e=>jb(e,kb))}function jb(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 Mb(e,t){return Ab(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?Pb(e,()=>{Fb(e.currentTarget,-1)}):e.key===`ArrowDown`?Pb(e,()=>{Fb(e.currentTarget,1)}):e.key===`Home`?Pb(e,()=>{Ib(e.currentTarget,0)}):e.key===`End`?Pb(e,()=>{Ib(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?Pb(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?Pb(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&Pb(e,t.cancel)}function Nb(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 Pb(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Fb(e,t){let n=Rb(e),r=Bb(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||Lb(n,i+t)}function Ib(e,t){let n=Rb(e);n.length!==0&&Lb(n,t<0?n.length-1:t)}function Lb(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function Rb(e){let t=Bb(e)?.getRootNode();return t===void 0||!zb(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function zb(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function Bb(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var Vb=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new gb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Nb(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1140
1140
|
<section>
|
|
1141
1141
|
<h2>${this.renderHeading()}</h2>
|
|
1142
1142
|
${this.collapsed?null:g`
|
|
@@ -5473,7 +5473,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5473
5473
|
<button type="button" class="error-dismiss" aria-label="Dismiss error" title="Dismiss error" @click=${()=>{t()}}>✕</button>
|
|
5474
5474
|
</div>`}function ZO(e){return $O(e)!==void 0}var QO=6e3;function $O(e){if(/session daemon workspace authority unavailable: connect (enoent|econnrefused)/i.test(e)&&/sessiond\.sock/i.test(e))return`Reconnecting to the session daemon…`;if(/\boperation was aborted\b/i.test(e))return`Previous request was interrupted. Retry if the message did not finish.`;if(/remote machine request cancelled/i.test(e))return`Connection changed while the request was in flight. Retrying is usually enough.`}function ek(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e===void 0||e.length===0||n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function tk(e){let t=e.inputs.map(nk).join(`; `);return`${e.machineName}: ${t}. Support for deprecated agent configuration inputs will be removed in a future release.`}function nk(e){let t=e.source===`config`?`config key ${e.name}`:`environment variable ${e.name}`;return e.replacement===void 0?`${t} is deprecated and ignored; remove it, there is no replacement`:`${t} is deprecated; set ${e.replacement} instead`}function rk(e){return e.length===0?null:g`<div class="deprecation-notice" role="alert">
|
|
5475
5475
|
${e.map(e=>g`<p class="deprecation-notice-text">${tk(e)}</p>`)}
|
|
5476
|
-
</div>`}var ik=900*1e3,ak=750,ok=[1e3,3e3,8e3,15e3,3e4],sk={capture:!0},ck=`auto:on`,lk=`auto:off`,uk=`theme:`,dk=Ks(`core:workspace.files`),fk=Ks(`core:workspace.terminal`),pk=320,mk=2,hk=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Fs(),this.sessionUnread=new om({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Vf(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Qd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Hd,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new mc(()=>this.state,e=>{this.setState(e)}),this.auth=new Hs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Xf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new qf),this.projects=new gc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new _c(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new oc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new bp,this.realtime=new Cd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new np,this.terminalSelection=new hp,this.appShell=new hy(this),this.browserResume=new _y({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Ay(this),this.panelResize=new Fy(this),this.navigationSections=new ky(this,()=>this.state),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=gk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Tm()??xm,this.activeThemeId=bm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=KO(),this.quickSwitcherWorkspaces=[],this.settingsSection=rb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=hs(void 0),this.sessionWarningVisibility=mm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=Kp(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r)=>this.sendPrompt(e,t,n,r),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{e.hasOutput&&this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=bk(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection()}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=gm(this.sessionWarningVisibility,e===void 0?void 0:Vs(L(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=yk(e,t);await this.updateComplete,!(!this.unreadConnected||bk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Eo.subsessions(e,t),Eo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!Dk(n.subsessions,this.state.subagents),a=!Ok(n.toolRuns,this.state.subagentRuns),o=!Ek(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await vo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await vo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
|
|
5476
|
+
</div>`}var ik=900*1e3,ak=750,ok=[1e3,3e3,8e3,15e3,3e4],sk={capture:!0},ck=`auto:on`,lk=`auto:off`,uk=`theme:`,dk=Ks(`core:workspace.files`),fk=Ks(`core:workspace.terminal`),pk=320,mk=2,hk=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Fs(),this.sessionUnread=new om({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Vf(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Qd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Hd,{notifications:this.notifications,onSelectedSessionIdle:()=>{this.workspaces.refreshWorkspaceGoals()},onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new mc(()=>this.state,e=>{this.setState(e)}),this.auth=new Hs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Xf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new qf),this.projects=new gc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new _c(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new oc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new bp,this.realtime=new Cd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new np,this.terminalSelection=new hp,this.appShell=new hy(this),this.browserResume=new _y({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Ay(this),this.panelResize=new Fy(this),this.navigationSections=new ky(this,()=>this.state),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=gk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Tm()??xm,this.activeThemeId=bm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=KO(),this.quickSwitcherWorkspaces=[],this.settingsSection=rb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=hs(void 0),this.sessionWarningVisibility=mm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=Kp(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r)=>this.sendPrompt(e,t,n,r),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{e.hasOutput&&this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=bk(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection()}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=gm(this.sessionWarningVisibility,e===void 0?void 0:Vs(L(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=yk(e,t);await this.updateComplete,!(!this.unreadConnected||bk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Eo.subsessions(e,t),Eo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!Dk(n.subsessions,this.state.subagents),a=!Ok(n.toolRuns,this.state.subagentRuns),o=!Ek(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await vo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await vo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
|
|
5477
5477
|
<div class="self-update-banner applying" role="status" aria-live="polite">
|
|
5478
5478
|
<span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>
|
|
5479
5479
|
<span>正在更新 pi-web(${e.current} → ${e.latest??`new`})… 重启后页面将自动重连。</span>
|
package/dist/client/index.html
CHANGED
|
@@ -114,7 +114,7 @@
|
|
|
114
114
|
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--pi-bg); color: var(--pi-text); }
|
|
115
115
|
body { min-height: 100dvh; }
|
|
116
116
|
</style>
|
|
117
|
-
<script type="module" crossorigin src="./assets/index-
|
|
117
|
+
<script type="module" crossorigin src="./assets/index-Bg8YBVNq.js"></script>
|
|
118
118
|
<link rel="modulepreload" crossorigin href="./assets/vendor-editor-core-CXO8gGab.js">
|
|
119
119
|
<link rel="modulepreload" crossorigin href="./assets/vendor-editor-languages-CpW4sJsX.js">
|
|
120
120
|
</head>
|
package/package.json
CHANGED