@vincenthanxiaodu/pi-web 1.202608.22 → 1.202608.23
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-I72YZTch.js → CodeViewer-Bbc754po.js} +1 -1
- package/dist/client/assets/{TerminalPanel-CCTQ5gix.js → TerminalPanel-C03ZVP61.js} +1 -1
- package/dist/client/assets/{index-DUdT8Swu.js → index-DtVZ1Hqm.js} +12 -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-DtVZ1Hqm.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-DtVZ1Hqm.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,7 +1,7 @@
|
|
|
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-Bbc754po.js","./vendor-editor-core-CXO8gGab.js","./vendor-editor-languages-CpW4sJsX.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-C03ZVP61.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=8e3,Mt=4e3,Nt=1e4,Pt={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Ft(e){if(!Rt(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=It(e.machine),a=It(e.unattributed),o=Lt(e.projects),s=Lt(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 It(e){if(!Rt(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 Lt(e){if(!Rt(e))return;let t=new Map;for(let[n,r]of Object.entries(e)){let e=It(r);e!==void 0&&t.set(n,e)}return Object.fromEntries(t)}function Rt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var zt=Object.values(wt),Bt=new Set(zt);wt.pluginLifecycle,wt.pluginLifecycle;function Vt(e){return typeof e==`string`&&Bt.has(e)}function Ht(e,t){return e?.capabilities?.includes(t)===!0}function Ut(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Vt)}function Wt(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Gt(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 Gt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Kt=/^[a-z][a-z0-9.-]*$/u,qt=new Set([`core`,`themes`]),Jt=`machine.`;function Yt(e){return Kt.test(e)}function Xt(e){return qt.has(e)||e.startsWith(Jt)}var Zt=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 Qt(e){if(!Yt(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 $t(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function en(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function tn(e){let t=T(e);return{messages:$t(t.messages),start:O(t,`start`),total:O(t,`total`)}}function nn(e){let t=T(e);return A(rn)(t.machines)}function rn(e){let t=T(e),n=cn(t,`kind`),r=D(t,`baseUrl`),i=ln(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 an(e){let t=T(e),n=ln(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:pa(t.web)},...t.sessiond===void 0?{}:{sessiond:pa(t.sessiond)},...r===void 0?{}:{error:r}}}function on(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:da(t.components)},...t.capabilities===void 0?{}:{capabilities:ya(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:sn(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function sn(e){let t=Wt(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function cn(e,t){let n=E(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function ln(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 un(e){let t=T(e);return{id:E(t,`id`),name:E(t,`name`),path:E(t,`path`),createdAt:E(t,`createdAt`)}}function dn(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`,_n(t.provider)),...M(`removal`,vn(t.removal)),effectiveConfig:xn(t.effectiveConfig)})}function fn(e){let t=T(e),n=pn(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(dn)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=A(mn)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function pn(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function mn(e){let t=T(e),n=D(t,`pluginId`),r=t.pluginIds===void 0?void 0:en(t.pluginIds,`pluginIds`);return Object.freeze({code:hn(t.code),message:E(t,`message`),tier:gn(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function hn(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function gn(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function _n(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:yn(n,`workspace provider metadata`))})}function vn(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 yn(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,bn(n,t)])))}function bn(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=>bn(e,t)));if(w(e))return yn(e,t);throw Error(`Invalid ${t} field`)}function xn(e){if(!w(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Vi(e.uploads);return Object.freeze({...M(`uploads`,t===void 0?void 0:Object.freeze({...t}))})}function Sn(e){let t=T(e),n=D(t,`name`),r=sa(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 Cn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function wn(e){if(e!==void 0)return{id:E(T(e),`id`)}}function Tn(e){let t=T(e),n=wn(t.dismiss);return{severity:Cn(t.severity),message:E(t,`message`),...M(`source`,D(t,`source`)),...M(`path`,D(t,`path`)),...n===void 0?{}:{dismiss:n}}}function En(e){return e===void 0?{}:{warnings:A(Tn)(e)}}function Dn(e){let t=T(e);return{value:gr(t,`value`,128),label:gr(t,`label`,Ot),...M(`detail`,_r(t,`detail`,Ot))}}function On(e){let t=T(e),n=Or(t.options,Dn,12,`options`);Rn(n.map(e=>e.value),`ask option value`);let r=sa(t.multiple,`multiple`);return{id:gr(t,`id`,128),question:gr(t,`question`,Ot),...M(`detail`,_r(t,`detail`,Ot)),options:n,...r===void 0?{}:{multiple:r}}}function kn(e){let t=T(e),n=Or(t.questions,On,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Rn(n.map(e=>e.id),`ask question id`),{askId:gr(t,`askId`,128),askedAt:j(t,`askedAt`),questions:n}}function An(e){return e===void 0?{}:{pendingAsk:kn(e)}}function jn(e){let t=T(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:kn(t.ask)}}function Mn(e){let t=T(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:gr(t,`askId`,128),reason:Nn(t.reason)}}function Nn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Pn(e){let t=T(e),n=On(t.question),r=Or(t.values,kr,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=_r(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 Fn(e){let t=T(e),n=Or(t.questions,Pn,20,`questions`),r=Ar(t,`answeredCount`),i=en(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:gr(t,`askId`,128),reason:Nn(t.reason),askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:j(t,`summary`)}}function In(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:Fn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Yn(t.sessionStatus)}}function Ln(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:qn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Yn(t.sessionStatus)}}function Rn(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function zn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Bn(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function Vn(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function Hn(e){let t=kr(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Un(e){let t=T(e),n=zn(t.kind),r=t.options===void 0?void 0:Or(t.options,Hn,24,`options`);if(r!==void 0&&Rn(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:gr(t,`dialogId`,128),kind:n,title:gr(t,`title`,jt),...M(`message`,_r(t,`message`,jt)),...r===void 0?{}:{options:r},...M(`placeholder`,_r(t,`placeholder`,At)),askedAt:j(t,`askedAt`),...M(`timeoutAt`,Jn(t,`timeoutAt`)),runScoped:k(t,`runScoped`)}}function Wn(e){if(e===void 0)return{};let t=A(Un)(e);return Rn(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Gn(e){let t=T(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Un(t.dialog)}}function Kn(e){let t=T(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Bn(t.reason),r=t.answer===void 0?void 0:Vn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:gr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function qn(e){let t=T(e),n=Bn(t.reason),r=t.answer===void 0?void 0:Vn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:gr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`)}}function Jn(e,t){let n=D(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function Yn(e){let t=T(e);return{sessionId:E(t,`sessionId`),...M(`persisted`,sa(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(Ur)(t.queuedMessages),...M(`messageCount`,Wa(t,`messageCount`)),tokens:Wr(t.tokens),cost:O(t,`cost`),...Kr(t.model),...fi(t.contextUsage),...M(`thinkingLevel`,D(t,`thinkingLevel`)),...En(t.warnings),...An(t.pendingAsk),...Wn(t.pendingDialogs)}}function Xn(e){let t=T(e);return{seq:O(t,`seq`),partial:t.partial??null}}function Zn(e){let t=T(e),n=t.subtasks===void 0?[]:A(Zn)(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 Qn(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`,Wa(t,`tokensUsed`)),...M(`activeSeconds`,Wa(t,`activeSeconds`)),tasks:A(Zn)(t.tasks),completedTaskCount:O(t,`completedTaskCount`),totalTaskCount:O(t,`totalTaskCount`)}}function $n(e){let t=T(e);return{goals:A(Qn)(t.goals),directory:E(t,`directory`),generatedAt:E(t,`generatedAt`)}}function er(e){let t=T(e),n=A(Yn)(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 tr(e){let t=T(e),n=Ar(t,`catalogRevision`),r=Or(t.sessions,pr,Tt,`sessions`);if(mr(r),hr(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:gr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function nr(e){let t=T(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=gr(t,`sessionId`,512),r=gr(t,`cwd`,Et),i=vr(t,`catalogRevision`),a=t.unread===null?null:pr(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:gr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function rr(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:ir(t.activity)}}function ir(e){let t=T(e);return{sessionId:j(t,`sessionId`),phase:or(t,`phase`),label:j(t,`label`),...M(`detail`,D(t,`detail`)),at:j(t,`at`),...M(`startup`,ar(t))}}function ar(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function or(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 sr(e){let t=T(e);switch(t.type){case`message.append`:return{type:`message.append`,message:lr(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`,sa(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`,ur(t,`exitCode`)),...M(`cancelled`,sa(t.cancelled,`cancelled`)),...M(`truncated`,sa(t.truncated,`truncated`)),...M(`fullOutputPath`,D(t,`fullOutputPath`)),...M(`isError`,sa(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:Yn(t.status)};case`activity.update`:return{type:`activity.update`,activity:ir(t.activity)};case`command.output`:return dr(t);case`session.error`:return{type:`session.error`,message:E(t,`message`)};case`session.name`:return fr(t);case`session.created`:return{type:`session.created`,session:Sn(t.session)};case`pi.event`:return{type:`pi.event`,eventType:E(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function cr(e){let t=T(e);switch(t.type){case`status.update`:return{type:`status.update`,status:Yn(t.status)};case`activity.update`:return{type:`activity.update`,activity:ir(t.activity)};case`session.name`:return fr(t);case`session.created`:return{type:`session.created`,session:Sn(t.session)};case`terminal.created`:return{type:`terminal.created`,terminal:Ci(t.terminal)};case`terminal.exited`:return{type:`terminal.exited`,terminal:Ci(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:Di(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function lr(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function ur(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 dr(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 fr(e){return{type:`session.name`,sessionId:j(e,`sessionId`),...M(`name`,D(e,`name`))}}function pr(e){let t=T(e),n=gr(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:gr(t,`sessionId`,512),cwd:gr(t,`cwd`,Et),completionOrder:vr(t,`completionOrder`),completedAt:n}}function mr(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 hr(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 gr(e,t,n){let r=j(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function _r(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 vr(e,t){let n=Ar(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function yr(e){let t=T(e),n=xr(t.summary),r=Or(t.notifications,Sr,100,`notifications`);if(jr(r),Mr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Pr(r))throw Error(`Notification snapshot severity mismatch`);let i=Cr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:j(t,`daemonInstanceId`),catalogRevision:Ar(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function br(e){let t=T(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=xr(t.summary),r=Cr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=wr(t.delta);if(i.kind===`cleared`&&!Nr(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:Ar(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function xr(e){let t=T(e),n=Ar(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ar(t,`discardedCount`),i=Er(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:j(t,`sessionId`),cwd:j(t,`cwd`),inboxRevision:Ar(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Sr(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=Ar(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:j(t,`id`),message:n,truncated:k(t,`truncated`),severity:Tr(t.severity),receivedAt:r,order:i}}function Cr(e){let t=T(e);return{order:Ar(t,`order`),overflowWatermark:Ar(t,`overflowWatermark`)}}function wr(e){let t=T(e);switch(t.kind){case`added`:{let e=D(t,`evictedNotificationId`);return{kind:`added`,notification:Sr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Or(t.notificationIds,kr,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:Dr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Tr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Er(e){return e===void 0?void 0:Tr(e)}function Dr(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 Or(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 kr(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 Ar(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function jr(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 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.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Nr(e){return e.retainedCount===0&&e.discardedCount===0}function Pr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Fr(e){let t=T(e),n=t.skippedBusySessionIds===void 0?void 0:en(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:E(t,`generatedAt`),thresholds:Br(t.thresholds),projects:A(Vr)(t.projects),totals:Hr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Ir(e){let t=T(e);return{...Fr(t),archivedSessionIds:en(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:en(t.deletedSessionIds,`deletedSessionIds`)}}function Lr(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:en(t.archivedSessionIds,`archivedSessionIds`),failures:A(zr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Rr(e){let t=T(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:en(t.deletedSessionIds,`deletedSessionIds`),failures:A(zr)(t.failures),generatedAt:E(t,`generatedAt`)}}function zr(e){let t=T(e);return{sessionId:E(t,`sessionId`),error:E(t,`error`)}}function Br(e){let t=T(e);return{...M(`archiveIdleDays`,Wa(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,Wa(t,`deleteArchivedDays`))}}function Vr(e){let t=T(e);return{cwd:E(t,`cwd`),archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Hr(e){let t=T(e);return{archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Ur(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 Wr(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 Gr(e){let t=T(e);return{...M(`provider`,D(t,`provider`)),...M(`id`,D(t,`id`)),...M(`name`,D(t,`name`)),...M(`contextWindow`,Wa(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Kr(e){return e===void 0?{}:{model:Gr(e)}}function qr(e){let t=T(e);return{models:A(Gr)(t.models)}}function Jr(e){let t=T(e);return{provider:E(t,`provider`),id:E(t,`id`),...M(`name`,D(t,`name`)),...M(`contextWindow`,Wa(t,`contextWindow`)),...M(`reasoning`,t.reasoning),enabled:k(t,`enabled`)}}function Yr(e){let t=T(e);return{models:A(Jr)(t.models)}}function Xr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Zr(e){let t=T(e);return{levels:A(Xr)(t.levels)}}function Qr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function $r(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 ei(e){let t=T(e),n=t.source===void 0?void 0:$r(t.source);return{configured:k(t,`configured`),...M(`source`,n),...M(`label`,D(t,`label`))}}function ti(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:Qr(t.authType),status:ei(t.status),...n===void 0?{}:{loginFlow:n}}}function ni(e){let t=T(e);return{providers:A(ti)(t.providers)}}function ri(e){let t=T(e);return{flowId:E(t,`flowId`),providerId:E(t,`providerId`),providerName:E(t,`providerName`),status:ii(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`,ai(t.auth)),...M(`prompt`,si(t.prompt)),...M(`select`,li(t.select)),...M(`info`,ui(t.info))}}function ii(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ai(e){if(e===void 0)return;let t=T(e);return{url:E(t,`url`),...M(`instructions`,D(t,`instructions`)),...M(`deviceCode`,oi(t.deviceCode))}}function oi(e){if(e===void 0)return;let t=T(e);return{userCode:E(t,`userCode`),...M(`intervalSeconds`,Wa(t,`intervalSeconds`)),...M(`expiresInSeconds`,Wa(t,`expiresInSeconds`))}}function si(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),promptType:ci(t.promptType),...M(`placeholder`,D(t,`placeholder`)),...M(`allowEmpty`,Ua(t,`allowEmpty`))}}function ci(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function li(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),options:A(ja)(t.options)}}function ui(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(di)(t.links))}})(e)}function di(e){let t=T(e);return{url:E(t,`url`),...M(`label`,D(t,`label`))}}function fi(e){if(e===void 0)return{};let t=T(e);return{contextUsage:{tokens:Ga(t,`tokens`),contextWindow:O(t,`contextWindow`),percent:Ga(t,`percent`)}}}function pi(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 mi(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 hi(e){let t=T(e);return{path:E(t,`path`),entries:A(gi)(t.entries),scannedAt:E(t,`scannedAt`),truncated:k(t,`truncated`)}}function gi(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`,Wa(t,`size`)),...M(`modifiedAt`,D(t,`modifiedAt`))}}function _i(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`,xi(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 vi(e){let t=T(e);return{path:E(t,`path`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),created:k(t,`created`)}}function yi(e){let t=T(e);return{path:E(t,`path`),existed:k(t,`existed`)}}function bi(e){let t=T(e);return{fromPath:E(t,`fromPath`),toPath:E(t,`toPath`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`)}}function xi(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function Si(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 Ci(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`,Wa(t,`exitCode`)),...M(`commandRunId`,D(t,`commandRunId`))}}function wi(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:Ti(t.status),...M(`exitCode`,Wa(t,`exitCode`)),createdAt:E(t,`createdAt`),...M(`startedAt`,D(t,`startedAt`)),...M(`completedAt`,D(t,`completedAt`)),metadata:Ei(t.metadata,`metadata`)}}function Ti(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Ei(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 Di(e){let t=Ft(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Oi(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 ki(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 Ai(e){let t=T(e);return{hub:Mi(t.hub),machines:A(Ni)(t.machines)}}function ji(e){let t=T(e),n=E(t,`operation`);if(n!==`restart`&&n!==`update`)throw Error(`Invalid fleet operation`);return{operation:n,hub:Mi(t.hub),outcomes:A(Pi)(t.outcomes)}}function Mi(e){let t=T(e);return{machineId:E(t,`machineId`),name:E(t,`name`)}}function Ni(e){let t=T(e),n=E(t,`kind`);if(n!==`local`&&n!==`remote`)throw Error(`Invalid machine kind`);return{...Mi(e),kind:n,online:t.online===!0,...M(`version`,D(t,`version`)),...M(`piVersion`,D(t,`piVersion`)),...M(`error`,D(t,`error`))}}function Pi(e){let t=T(e);return{...Mi(e),started:t.started===!0,...M(`error`,D(t,`error`))}}function Fi(e){let t=T(e);return{path:E(t,`path`),exists:k(t,`exists`),config:Ii(t.config),effectiveConfig:Ii(t.effectiveConfig),envOverrides:Ki(t.envOverrides)}}function Ii(e){let t=T(e);return{...M(`host`,D(t,`host`)),...M(`port`,Wa(t,`port`)),...M(`allowedHosts`,Ri(t.allowedHosts)),...M(`shortcuts`,Wi(t.shortcuts)),...M(`plugins`,Gi(t.plugins)),...M(`pathAccess`,zi(t.pathAccess)),...M(`uploads`,Vi(t.uploads)),...M(`maxUploadBytes`,Wa(t,`maxUploadBytes`)),...M(`agent`,Li(t.agent)),...M(`spawnSessions`,Ua(t,`spawnSessions`)),...M(`subsessions`,Ua(t,`subsessions`)),...M(`askUser`,Ua(t,`askUser`))}}function Li(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 Ri(e){if(e!==void 0){if(e===!0)return!0;if(Hi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function zi(e){if(e===void 0)return;if(!w(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,Bi(t,`pathAccess.allowedPaths`))}}function Bi(e,t){if(e!==void 0){if(Ui(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Vi(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 Hi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ui(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Wi(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 Gi(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 Ki(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 qi(e){let t=T(e);return{packages:A(Yi)(t.packages)}}function Ji(e){let t=T(e),n=D(t,`source`),r=t.scope===void 0?void 0:Xi(t.scope),i=sa(t.removed,`removed`);return{action:Zi(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:A(Yi)(t.packages)}}function Yi(e){let t=T(e);return{source:E(t,`source`),scope:Xi(t.scope),filtered:k(t,`filtered`),...M(`installedPath`,D(t,`installedPath`))}}function Xi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Zi(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Qi(e){let t=T(e),n=A($i)(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:aa()}};if(t.lifecycleVersion!==1)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:1,plugins:n,diagnostics:A(na)(t.diagnostics),serverRuntime:ra(t.serverRuntime)}}function $i(e){let t=T(e),n=E(t,`id`),r=t.server===void 0?void 0:ea(t.server,n);return{id:n,...M(`module`,D(t,`module`)),source:E(t,`source`),scope:oa(t.scope),machineSpecific:sa(t.machineSpecific,`machineSpecific`)??!1,enabled:k(t,`enabled`),discovered:sa(t.discovered,`discovered`)??!0,conflict:sa(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function ea(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:ta(n.health),o=E(n,`disableCommand`);if(o!==Qt(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 ta(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 na(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 ra(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:ia(t.recovery)}}function ia(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!==Zt.showSafeStart||n.bundledOnly!==Zt.bundledOnly||n.noServerPlugins!==Zt.noServerPlugins||n.clearSafeStart!==Zt.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function aa(){return{...Zt}}function oa(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function sa(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function ca(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ua(t.components),release:ha(t.release),commands:ga(t.commands),messages:A(_a)(t.messages)}}function la(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:da(t.components),capabilities:ya(t.capabilities)}}function ua(e){let t=T(e);return{web:pa(t.web),sessiond:pa(t.sessiond)}}function da(e){let t=T(e);return{web:fa(t.web),sessiond:fa(t.sessiond)}}function fa(e){let t=T(e);return{component:va(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`piVersion`,D(t,`piVersion`)),available:k(t,`available`),capabilities:ya(t.capabilities),...M(`error`,D(t,`error`))}}function pa(e){let t=T(e);return{component:va(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`,ma(t.installation)),...M(`error`,D(t,`error`))}}function ma(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 ha(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 ga(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 _a(e){let t=T(e);return{id:E(t,`id`),severity:ba(t.severity),title:E(t,`title`),body:E(t,`body`),...M(`command`,D(t,`command`))}}function va(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function ya(e){let t=Ut(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function ba(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function xa(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(ja)(t.options)};if(n===`tree`)return{type:n,tree:Sa(t.tree)};if(n===`done`)return{type:n,...M(`message`,D(t,`message`)),...Ma(t.session),...M(`promptDraft`,D(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Sa(e){let t=T(e),n=A(Ca)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Oa(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Aa(t.activePathIds,`activePathIds`)}}function Ca(e){let t=T(e);return{id:ka(t,`id`),parentId:Oa(t,`parentId`),kind:wa(t.kind),summary:E(t,`summary`),...M(`timestamp`,D(t,`timestamp`)),...M(`label`,D(t,`label`))}}function wa(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 Ta(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){Da(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 Da(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,D(t,`editorText`))}}function Ea(e){let t=T(e),n=k(t,`cancelled`);return n?(Da(t,`session`,`session tree fork cancellation result`),Da(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:Sn(t.session),...M(`promptDraft`,D(t,`promptDraft`))}}function Da(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Oa(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 ka(e,t){let n=E(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Aa(e,t){let n=en(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ja(e){let t=T(e);return{value:E(t,`value`),label:E(t,`label`),...M(`description`,D(t,`description`))}}function Ma(e){return e===void 0?{}:{session:Sn(e)}}function Na(e){if(T(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function Pa(e){let t=T(e);return A(Fa)(t.attachments)}function Fa(e){let t=T(e);return{path:E(t,`path`),mimeType:E(t,`mimeType`),size:O(t,`size`)}}function Ia(e){if(T(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function La(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(Ur)(n):[]}}function Ra(e){if(T(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function za(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:en(t.sessionIds,`sessionIds`),r=Wa(t,`archivedCount`),i=Wa(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ba(e){if(T(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Va(e){if(T(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Ha(e){if(T(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ua(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Wa(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Ga(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function M(e,t){return t===void 0?{}:{[e]:t}}function Ka(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 qa(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:Qa(e.toolRuns)}}function Ja(e){let t=Yn(e);return{recalled:w(e)&&e.recalled===!0,status:t}}function Ya(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 Xa(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function Za(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function Qa(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 $a(e){return typeof e==`string`?e:e.id}function eo(e){return typeof e==`string`?void 0:e.cwd}function to(e,t,n=`local`){let r=new URLSearchParams,i=eo(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($a(e))}/messages${a===``?``:`?${a}`}`}function no(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 ro(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 io(e,t,n,r){return vt(ro(e,t,n,r))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function ao(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(e.id)}`}function P(e,t,n=`local`){return`${ao(e,n)}/${t}`}function oo(e,t,n=`local`){return`${P(e,t,n)}${so(e)}`}function so(e){return`?${new URLSearchParams({cwd:e.cwd}).toString()}`}function F(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function co(e){return JSON.stringify({sessions:e.map(lo)})}function lo(e){return{id:e.id,cwd:e.cwd}}function uo(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var fo={piWebStatus:(e=`local`)=>C(uo(e),ca),checkForUpdates:(e=`local`)=>C(`${uo(e)}?refresh=1`,ca,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,la)},po={machines:()=>C(`api/machines`,nn),addMachine:e=>C(`api/machines`,rn,{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)}`,rn,{method:`PATCH`,body:JSON.stringify(t)}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,an),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,on,t?{cache:`no-store`}:{})};function mo(e){return e===void 0?`api/config`:`${N(e)}/config`}function ho(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var go={config:e=>C(mo(e),Fi),saveConfig:(e,t)=>C(mo(t),Fi,{method:`PUT`,body:JSON.stringify({config:e})})};function _o(e){let t=Fo(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 vo={plugins:e=>C(ho(e),Qi)},yo={status:()=>C(`api/pi-web/update/status`,Oi,{cache:`no-store`}),apply:()=>C(`api/pi-web/update/apply`,_o,{method:`POST`,body:JSON.stringify({})})},bo={report:()=>C(`api/pi-web/fleet`,Ai,{cache:`no-store`}),run:(e,t)=>C(`api/pi-web/fleet/run`,ji,{method:`POST`,body:JSON.stringify({operation:e,...t===void 0?{}:{machineIds:t}})})};function xo(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var So={packages:e=>C(xo(``,e),qi),install:(e,t)=>{let n={source:e};return C(xo(`install`,t),Ji,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(xo(`remove`,n),Ji,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(xo(`update`,t),Ji,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Co={machineStatus:(e=`local`)=>C(`${N(e)}/status`,Di)},wo={projects:(e=`local`)=>C(`${N(e)}/projects`,A(un)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,un,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,Ia,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,A(mi))};function To(e,t=`local`){return C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=fn(t);if(n.projectId!==e)throw Error(`Workspace resolution did not match the requested project`);return n})}var Eo={workspaceResolution:To,workspaces:async(e,t=`local`)=>[...(await To(e,t)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,wi,{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`,ki,{method:`POST`,body:JSON.stringify({})}),workspaceGoals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals`,$n,{cache:`no-store`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,hi),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,_i),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()}`,vi,{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()}`,yi,{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()}`,bi,{method:`POST`})}},Do={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,A(Sn)),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,tr,{cache:`no-store`}),statusCatalog:(e=`local`)=>C(`${N(e)}/sessions/statuses`,er,{cache:`no-store`}),interruptedRuns:(e=`local`)=>C(`${N(e)}/sessions/interrupted`,Ka,{cache:`no-store`}),subsessions:(e,t=`local`)=>C(`${P(e,`subsessions`,t)}?cwd=${encodeURIComponent(e.cwd)}`,qa,{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),tr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(oo(e,`notifications`,t),yr),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),yr,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),yr,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,Sn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,Fr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Ir,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Lr,{method:`POST`,body:co(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,Rr,{method:`POST`,body:co(e)}),messages:(e,t,n=`local`)=>C(to(e,t,n),tn),status:(e,t=`local`)=>C(oo(e,`status`,t),Yn),streamSnapshot:(e,t=`local`)=>C(oo(e,`stream-snapshot`,t),Xn),backgroundTasks:(e,t=`local`)=>C(`${P(e,`background-tasks`,t)}?cwd=${encodeURIComponent(e.cwd)}`,Ya,{cache:`no-store`}),backgroundTaskOutput:(e,t,n=`local`)=>C(`${P(e,`background-tasks/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,Xa,{cache:`no-store`}),subagentRunOutput:(e,t,n=`local`)=>C(`${P(e,`subagent-runs/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,Za,{cache:`no-store`}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),Yn,{method:`POST`,body:F(e)}),recallQueuedMessage:(e,t,n=`local`)=>C(P(e,`queue/clear`,n),Ja,{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),Yn,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),In,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),In,{method:`POST`,body:F(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(P(e,`dialogs/answer`,r),Ln,{method:`POST`,body:F(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(P(e,`dialogs/cancel`,n),Ln,{method:`POST`,body:F(e,{dialogId:t})}),models:(e,t=`local`)=>C(oo(e,`models`,t),qr),modelCatalog:(e,t=`local`)=>C(oo(e,`models/catalog`,t),Yr),setModelEnabled:(e,t,n,r,i=`local`)=>C(P(e,`models/enabled`,i),Yr,{method:`POST`,body:F(e,{provider:t,modelId:n,enabled:r})}),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),Yn,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),Yn,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(oo(e,`thinking-levels`,t),Zr),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),Yn,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),Yn,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(oo(e,`commands`,t),A(pi)),prompt:(e,t,n,r=`local`,i,a)=>C(P(e,`prompt`,r),Na,{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),Pa,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),Na,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),xa,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),xa,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),Ta,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),forkTree:(e,t,n=`local`)=>Ao(e,t,n),abort:(e,t=`local`)=>C(P(e,`abort`,t),La,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),Ra,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),za,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),za,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),Ba,{method:`POST`,body:F(e)}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),Va,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),Ha,{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}`}`,ni)},startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${N(t)}/auth/api-key/interactive`,ri,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${N(t)}/auth/logout`,Na,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${N(t)}/auth/oauth`,ri,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}`,ri),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${N(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ri,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ri,{method:`POST`})},Oo={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,A(Ci)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ci,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ia,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Ia,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,Ci,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,wi,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs${No(e)}`,A(wi)),getCommandRun:(e,t=`local`)=>Mo(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,wi,{method:`POST`})},ko=class extends Error{constructor(){super(`Fork from the session tree is unavailable. Restart the session daemon to enable it.`),this.name=`SessionTreeForkUnavailableError`}};async function Ao(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 jo(r.status,e)?new ko:Error(Po(e)??r.statusText)}return Ea(await r.json())}function jo(e,t){if(e!==404||!Fo(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 Mo(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(Po(e)??n.statusText)}return wi(await n.json())}}function No(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function Po(e){if(!Fo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Fo(e){return typeof e==`object`&&!!e}var Io={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(mi))}},Lo=(e,t,n)=>`${N(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/trust`,Ro=(e,t)=>{let n=new URLSearchParams({path:t});return`${N(e)}/projects/trust?${n.toString()}`},zo={projectTrust:(e,t=`local`)=>C(Ro(t,e),Si),workspaceTrust:(e,t,n=`local`)=>C(Lo(n,e,t),Si),setWorkspaceTrust:(e,t,n,r=`local`)=>C(Lo(r,e,t),Si,{method:`PUT`,body:JSON.stringify({trusted:n})})},I={...fo,...po,...go,...vo,...So,...wo,...Eo,...Do,...Oo,...Io,...zo},Bo=256*1024,Vo=8*1024*1024,Ho=266240,Uo=8392704,Wo=/^[a-z][a-z0-9.-]*$/u,Go=64;function Ko(e){return e.length<=128&&Wo.test(e)}function qo(e){if(!Ko(e))throw Error(`Plugin backend operation must match ${String(Wo)} and be at most 128 characters`);return e}function Jo(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 Yo(e,t,n=Bo){let r=Qo(e,new Set,t,0);if(Zo(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function Xo(e,t,n=Bo){if(Zo(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 Yo(r,t,n)}function Zo(e){return new TextEncoder().encode(e).byteLength}function Qo(e,t,n,r){if(r>Go)throw Error(`${n} exceeds the maximum JSON depth of ${String(Go)}`);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=>Qo(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!es(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))$o(i,a,Qo(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function $o(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function es(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ts(e,t){if(!Yt(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=qo(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 ns(e,t,n){let r=ts(e,t);return n===void 0?vt(r):vt(r,n)}async function rs(e,t,n){let r=Jo(e.backendRevision),i=Yo(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(Zo(a)>266240)throw Error(`Plugin backend request exceeds the ${String(Ho)} byte wire limit`);let o;try{o=await fetch(ns(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${ss(e)}`,{cause:e})}let s=await is(o);if(!o.ok)throw Error(os(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return Xo(s,`Plugin backend response`,Vo)}async function is(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(Uo)} byte wire limit`);if(e.body===null){let t=await e.text();if(Zo(t)>8392704)throw as();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(),as();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function as(){return Error(`Plugin backend response exceeds the ${String(Uo)} byte wire limit`)}function os(e){try{let t=JSON.parse(e);return cs(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function ss(e){return e instanceof Error?e.message:String(e)}function cs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ls(e,t=`local`){let n=`?${new URLSearchParams({cwd:e.cwd}).toString()}`;return new WebSocket(yt(`${fs(t)}/sessions/${encodeURIComponent(e.id)}/events${n}`))}function us(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(`${fs(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function ds(e=`local`){return new WebSocket(yt(`${fs(e)}/events`))}function fs(e){return`api/machines/${encodeURIComponent(e)}`}var ps=`.pi-web/uploads`,ms=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},hs=class extends Error{constructor(e,t){super(Es(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function gs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function _s(e,t){return e.uploads?.defaultFolder??t}function vs(e,t){let n=ks(e,`upload destination`,{allowEmpty:!0}),r=ks(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function ys(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`,no(e,t,n.path,Ss(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Cs(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(vi(js(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Ms(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new ms(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function bs(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:vs(i,e.name),loaded:0,total:e.size,percent:Ts(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(ws(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 ms;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=ys(e,t,{path:p.path,file:f},{...xs(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(Os(e,c))throw e;let t=Ds(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 hs(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}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},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Ss(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Cs(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Ts(e.loaded,n),lengthComputable:e.lengthComputable}}function ws(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:Ts(i,r),done:n}}function Ts(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Es(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Ds(e){return e instanceof Error?e.message:String(e)}function Os(e,t){return t.requested||e instanceof ms}function ks(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(As(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 As(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function js(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Ms(e){let t=Ns(e);return Ps(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Ns(e){try{return js(e)}catch{return}}function Ps(e){return typeof e==`object`&&!!e}function Fs(){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 Is(){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 Ls(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Rs=`machine.`;function zs(e,t){if(e===``)throw Error(`Machine id is required`);if(!Yt(t))throw Error(`Invalid PI WEB plugin id: ${t}`);if(Xt(t))throw Error(`Reserved PI WEB plugin id: ${t}`);return`${Rs}${Bs(e)}.${t}`}function Bs(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Vs(e,t){return`${e}:${t}`}function Hs(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var Us=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=Ks(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(Ws(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||Gs(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Gs(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{Ws(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`?Gs(n.flow):void 0,a=Gs(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=Gs(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||Gs(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Gs(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 Ws(e,t){return e?.flowId===t.flowId&&e.requestId===t.requestId}function Gs(e){return e.prompt?.requestId??e.select?.requestId}function Ks(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 qs(e){return e.replaceAll(`:`,`.`)}function Js(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 Ys(e,t){let n=Js(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Xs(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));Zs(i,r)}function Zs(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 Qs(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:vs(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ic(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:ic(0,n),status:`uploading`,startedAt:e.startedAt}}function $s(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 ec(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=rc(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function tc(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,...rc(r),status:`error`,error:t,completedAt:n}}function nc(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,...rc(r),status:`cancelled`,error:n,completedAt:t}}function rc(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ic(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var ac=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:``})}},oc=qs(`core:workspace.files`),sc=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 ac(e,t),this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??bs,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:uc(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`}),Xs(oc,`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:lc(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=Qs({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(nc(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:uc(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch($s(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ec(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 hs)||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(cc(t)){let e=nc(n,this.now());return this.setUploadBatch(e),e}let r=lc(t),i=tc(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 cc(e){return e instanceof ms}function lc(e){return e instanceof Error?e.message:String(e)}function uc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var dc=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:pc(this.getState().machineRuntimes,r),machineStatusSnapshots:pc(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,...Fs()}),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:fc(this.getState().machineStatuses,e.id),machineRuntimes:fc(this.getState().machineRuntimes,e.id),machineStatusSnapshots:fc(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 fc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function pc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var mc=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}},hc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new mc,this.api=n.api??Co}refresh(e){return this.refreshes.request(e,async()=>{this.apply(e,await this.api.machineStatus(e))})}apply(e,t){let n=this.getState().machineStatusSnapshots;gc(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function gc(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}var _c=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);return}catch(e){return vc(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)})}}};function vc(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|no such file or directory/u.test(t)?`That folder does not exist. Tick “Create the folder if it does not exist” to make it, or correct the path.`:t.includes(`ENOTDIR`)?`That path is a file, not a folder.`:/EACCES|EPERM/u.test(t)?`That folder cannot be read with this account's permissions.`:t.replace(/^Error:\s*/u,``)}var yc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??fo,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}),bc(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 bc(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 xc=`pi-web:cached-new-sessions:v1`,Sc=`browserCachedNew`,Cc=`local`;function wc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Tc(e,t=Cc,n=wc()){if(e.messageCount!==0||e.archived===!0)return;let r=jc(n).filter(n=>n.id!==e.id||n.machineId!==t);Mc([Ec(e,t),...r],n)}function Ec(e,t=Cc){return{...e,browserCachedNew:!0,machineId:t}}function Dc(e,t=Cc,n=wc()){Mc(jc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Oc(e,t,n=Cc,r=wc()){let i=new Set(t.map(e=>e.id)),a=jc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Mc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function kc(e){return e!==void 0&&Pc(e)&&e.browserCachedNew===!0}function Ac(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:Cc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function jc(e=wc()){try{let t=e?.getItem(xc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Nc(e)):[]}catch{return[]}}function Mc(e,t=wc()){try{e.length===0?t?.removeItem(xc):t?.setItem(xc,JSON.stringify(e))}catch{}}function Nc(e){if(!Fc(e))return[];let t=Ic(e,`id`),n=Ic(e,`path`),r=Ic(e,`cwd`),i=Ic(e,`created`),a=Ic(e,`modified`),o=Ic(e,`firstMessage`),s=Rc(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=Lc(e,`name`),l=Lc(e,`parentSessionPath`),u=Lc(e,`machineId`)??Cc;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 Pc(e){return Sc in e}function Fc(e){return typeof e==`object`&&!!e}function Ic(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Lc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Rc(e,t){let n=e[t];return typeof n==`number`?n:void 0}function zc(e){return sl(e.flatMap(Wc)).filter(e=>e.parts.length>0)}function Bc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Vc(e,t){let n=Xc(t);return n===void 0?e:{...e,meta:n}}function Hc(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,Bc(t,n)]}function Uc(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 Wc(e){if(Kc(e))return[e];if(R(e,`role`)===`bashExecution`)return[Vc($c(e),e)];let t=R(e,`role`),n=el(t),r=tl(hl(e,`content`),e),i=t===`toolResult`?rl(R(e,`toolName`)??``,hl(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?qc(a):void 0;if(o!==void 0)return o.map(t=>Vc(t,e));let s=Yc(e);if(n===`tool`)return[Vc({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?[Vc({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Gc(e);return d===void 0?u:[...u,Vc(d,e)]}function Gc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return Bc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Kc(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(hl(e,`parts`))}function qc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Jc(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 Jc(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 Yc(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Xc(e){let t=Zc(hl(e,`timestamp`)),n=Qc(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 Zc(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 Qc(e){if(R(e,`role`)!==`assistant`)return;let t=R(e,`provider`),n=R(e,`model`),r=R(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function $c(e){let t=R(e,`command`)??``,n=gl(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=hl(e,`output`);r!=null&&n.push(``,vl(r));let i=hl(e,`exitCode`);i!=null&&n.push(``,`exit ${vl(i)}`),gl(e,`cancelled`)===!0&&n.push(``,`cancelled`),gl(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
|
-
`)}]}}function el(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function tl(e,t){let n=nl(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=hl(e,`arguments`),r=R(e,`id`),i=t===`read`?ol(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:fl(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 dl(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?al(e.text,t):e):dl(e):[n]}function nl(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return il(hl(e,`details`))}function rl(e,t){if(e===`ask_user`)return il(hl(t,`superseded`))}function il(e){try{return{type:`askUserRecord`,outcome:Fn(e)}}catch{return}}function al(e,t){let n=R(t,`toolCallId`),r=hl(t,`content`),i=hl(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:gl(t,`isError`)===!0}}function ol(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 sl(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=cl(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&&ll(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function cl(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 ll(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=ul(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 ul(e){let t=hl(e,`preview`);if(!ml(t))return;let n=R(t,`diff`),r=R(t,`error`),i=_l(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 dl(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:fl(e)}]:[{type:`text`,text:vl(e)}]}function fl(e){if(!ml(e))return vl(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}: ${pl(t)}`).join(` · `)}function pl(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 ml(e){return typeof e==`object`&&!!e}function hl(e,t){return ml(e)?e[t]:void 0}function R(e,t){let n=hl(e,t);return typeof n==`string`?n:void 0}function gl(e,t){let n=hl(e,t);return typeof n==`boolean`?n:void 0}function _l(e,t){let n=hl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function vl(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var yl=`pi-web:prompt-draft:`;function bl(e){return`${yl}${e}`}function xl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Sl(e,t=xl()){try{return t?.getItem(bl(e))??``}catch{return``}}function Cl(e,t,n=xl()){try{t?n?.setItem(bl(e),t):n?.removeItem(bl(e))}catch{}}function wl(e,t=xl()){try{t?.removeItem(bl(e))}catch{}}function Tl(e,t,n=xl()){let r=Sl(e,n);r!==``&&(Cl(t,r,n),wl(e,n))}var El=`pi-web:ask-draft:`;function Dl(e,t){return`${El}${e}:${t}`}function Ol(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function kl(e,t,n=Ol()){try{let r=n?.getItem(Dl(e,t));return r==null?{}:Ml(r)}catch{return{}}}function Al(e,t,n,r=Ol()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Dl(e,t)):r?.setItem(Dl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function jl(e,t,n=Ol()){try{n?.removeItem(Dl(e,t))}catch{}}function Ml(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=Nl(r);t!==void 0&&(n[e]=t)}return n}function Nl(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 Pl(e,t){return e.filter(e=>Ll(e,t[e.id])!==void 0).length}function Fl(e,t){return e.filter(e=>Ll(e,t[e.id])===void 0)}function Il(e,t){let n=[];for(let r of e){let e=Ll(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function Ll(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=Rl(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 Rl(e){if(e===void 0)return;let t=e.trim().slice(0,kt);return t===``?void 0:t}function zl(){let e=globalThis.crypto.randomUUID?.();return e===void 0?`cm-${String(Date.now())}-${Math.random().toString(36).slice(2,10)}`:e}function Bl(e,t){return{role:`user`,parts:[{type:`text`,text:e}],meta:{delivery:{clientMessageId:t,state:`sending`}}}}function Vl(e,t){if(t.length===0)return[...e];let n=new Map;for(let t of e){let e=t.meta?.delivery;e?.state===`queued`&&n.set(e.clientMessageId,t)}let r=[];for(let e of t){let t=e.clientMessageId===void 0?void 0:n.get(e.clientMessageId);r.push(t??Hl(e))}let i=new Set(r);return[...e.filter(e=>!i.has(e)),...r]}function Hl(e){let t=e.clientMessageId??`queued:${e.kind}:${e.text}`;return{role:`user`,parts:[{type:`text`,text:e.text}],meta:{delivery:{clientMessageId:t,state:`queued`,kind:e.kind}}}}function Ul(e,t){return e.findIndex(e=>e.meta?.delivery?.clientMessageId===t)}function Wl(e,t,n,r){let i=Ul(e,t);if(i===-1)return e;let a=e[i],o=a?.meta?.delivery;if(a===void 0||o===void 0||!ql(o.state,n)&&!Gl(o.kind,r,o.state,n))return e;let s=[...e],c=ql(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 Gl(e,t,n,r){return t!==void 0&&t!==e&&n===`queued`&&r===`queued`}var Kl={failed:-1,sending:0,received:1,queued:2,delivered:3};function ql(e,t){return e===t?!1:t===`failed`?e!==`delivered`:e!==`failed`&&Kl[t]>Kl[e]}function Jl(e,t){let n=Ul(e,t);return n===-1?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function Yl(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=Wl(n,e.clientMessageId,`queued`,i);continue}(e.state===`received`||e.state===`queued`)&&(n=Wl(n,e.clientMessageId,`delivered`))}return n}function Xl(e,t){return t!==void 0&&Ul(e,t)!==-1}function Zl(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 Ql(e,t){return t===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.delivery!==void 0&&$l(e)===t)}function $l(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
4
|
+
`)}]}}function el(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function tl(e,t){let n=nl(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=hl(e,`arguments`),r=R(e,`id`),i=t===`read`?ol(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:fl(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 dl(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?al(e.text,t):e):dl(e):[n]}function nl(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return il(hl(e,`details`))}function rl(e,t){if(e===`ask_user`)return il(hl(t,`superseded`))}function il(e){try{return{type:`askUserRecord`,outcome:Fn(e)}}catch{return}}function al(e,t){let n=R(t,`toolCallId`),r=hl(t,`content`),i=hl(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:gl(t,`isError`)===!0}}function ol(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 sl(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=cl(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&&ll(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function cl(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 ll(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=ul(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 ul(e){let t=hl(e,`preview`);if(!ml(t))return;let n=R(t,`diff`),r=R(t,`error`),i=_l(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 dl(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:fl(e)}]:[{type:`text`,text:vl(e)}]}function fl(e){if(!ml(e))return vl(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}: ${pl(t)}`).join(` · `)}function pl(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 ml(e){return typeof e==`object`&&!!e}function hl(e,t){return ml(e)?e[t]:void 0}function R(e,t){let n=hl(e,t);return typeof n==`string`?n:void 0}function gl(e,t){let n=hl(e,t);return typeof n==`boolean`?n:void 0}function _l(e,t){let n=hl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function vl(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var yl=`pi-web:prompt-draft:`;function bl(e){return`${yl}${e}`}function xl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Sl(e,t=xl()){try{return t?.getItem(bl(e))??``}catch{return``}}function Cl(e,t,n=xl()){try{t?n?.setItem(bl(e),t):n?.removeItem(bl(e))}catch{}}function wl(e,t=xl()){try{t?.removeItem(bl(e))}catch{}}function Tl(e,t,n=xl()){let r=Sl(e,n);r!==``&&(Cl(t,r,n),wl(e,n))}var El=`pi-web:ask-draft:`;function Dl(e,t){return`${El}${e}:${t}`}function Ol(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function kl(e,t,n=Ol()){try{let r=n?.getItem(Dl(e,t));return r==null?{}:Ml(r)}catch{return{}}}function Al(e,t,n,r=Ol()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Dl(e,t)):r?.setItem(Dl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function jl(e,t,n=Ol()){try{n?.removeItem(Dl(e,t))}catch{}}function Ml(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=Nl(r);t!==void 0&&(n[e]=t)}return n}function Nl(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 Pl(e,t){return e.filter(e=>Ll(e,t[e.id])!==void 0).length}function Fl(e,t){return e.filter(e=>Ll(e,t[e.id])===void 0)}function Il(e,t){let n=[];for(let r of e){let e=Ll(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function Ll(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=Rl(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 Rl(e){if(e===void 0)return;let t=e.trim().slice(0,kt);return t===``?void 0:t}function zl(){let e=globalThis.crypto.randomUUID?.();return e===void 0?`cm-${String(Date.now())}-${Math.random().toString(36).slice(2,10)}`:e}function Bl(e,t,n=[]){let r=n.filter(e=>e.kind===`image`).map(e=>({type:`image`,mimeType:e.mimeType,data:e.data}));return{role:`user`,parts:e===``?[...r]:[{type:`text`,text:e},...r],meta:{delivery:{clientMessageId:t,state:`sending`}}}}function Vl(e,t){if(t.length===0)return[...e];let n=new Map;for(let t of e){let e=t.meta?.delivery;e?.state===`queued`&&n.set(e.clientMessageId,t)}let r=[];for(let e of t){let t=e.clientMessageId===void 0?void 0:n.get(e.clientMessageId);r.push(t??Hl(e))}let i=new Set(r);return[...e.filter(e=>!i.has(e)),...r]}function Hl(e){let t=e.clientMessageId??`queued:${e.kind}:${e.text}`;return{role:`user`,parts:[{type:`text`,text:e.text}],meta:{delivery:{clientMessageId:t,state:`queued`,kind:e.kind}}}}function Ul(e,t){return e.findIndex(e=>e.meta?.delivery?.clientMessageId===t)}function Wl(e,t,n,r){let i=Ul(e,t);if(i===-1)return e;let a=e[i],o=a?.meta?.delivery;if(a===void 0||o===void 0||!ql(o.state,n)&&!Gl(o.kind,r,o.state,n))return e;let s=[...e],c=ql(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 Gl(e,t,n,r){return t!==void 0&&t!==e&&n===`queued`&&r===`queued`}var Kl={failed:-1,sending:0,received:1,queued:2,delivered:3};function ql(e,t){return e===t?!1:t===`failed`?e!==`delivered`:e!==`failed`&&Kl[t]>Kl[e]}function Jl(e,t){let n=Ul(e,t);return n===-1?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function Yl(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=Wl(n,e.clientMessageId,`queued`,i);continue}(e.state===`received`||e.state===`queued`)&&(n=Wl(n,e.clientMessageId,`delivered`))}return n}function Xl(e,t){return t!==void 0&&Ul(e,t)!==-1}function Zl(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 Ql(e,t){return t===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.delivery!==void 0&&$l(e)===t)}function $l(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
5
5
|
|
|
6
6
|
`)}function eu(e,t){return Bc(`bash`,`${t===!0?`excluded from context
|
|
7
7
|
|
|
@@ -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 ju(e,t,n,r=!1){let i=Wc(t);if(i.length===0)return e;if(r)return Mu(e,i,n);let a=Nu(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),Zl(t,n),...e.slice(a+1),...i.slice(1)]}if(Xl(e,n))return e;let o=i[0];if(o?.role===`user`){let t=Au(o);if(t!==``&&e.some(e=>e.role===`user`&&e.meta?.delivery!==void 0&&Au(e)===t))return e;let n=e.at(-1);if(n?.role===`user`&&t!==``&&Au(n)===t)return e}return[...e,...i]}function Mu(e,t,n){if(Xl(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 Nu(e,t){if(t?.role!==`user`)return-1;let n=Au(t);return n===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.echo===!0&&Au(e)===n)}function Pu(e,t){let n=e.at(-1);return Fu(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function Fu(e,t){let n=Tu(t);if(t.role!==`skill`||n.length===0)return!1;let r=Lu(e)+1;return n.every(t=>Iu(e,t,r))}function Iu(e,t,n){for(let r=e.length-1;r>=n;r--)if(Tu(e[r]).some(e=>Du(e,t)))return!0;return!1}function Lu(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function Ru(e){return typeof e==`object`&&!!e}function zu(e,t){return Ru(e)?e[t]:void 0}function Bu(e,t){let n=zu(e,t);return typeof n==`string`?n:void 0}function Vu(e,t){let n=zu(e,t);return typeof n==`boolean`?n:void 0}var Hu=`pi-web:chat-history:v2:`,Uu=1800*1e3;function Wu(e){try{let t=sessionStorage.getItem(Zu(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!Qu(n))return;if(Date.now()-n.savedAt>Uu){sessionStorage.removeItem(Zu(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function Gu(e,t){try{sessionStorage.setItem(Zu(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Ku(e){try{sessionStorage.removeItem(Zu(e))}catch{}}function qu(e,t){if(e===void 0||!$u(e))return t;if(!$u(t))return e;if(Ju(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 Xu(i,n,e),Xu(i,n,t),Yu(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function Ju(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Yu(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Xu(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function Zu(e){return`${Hu}${e}`}function Qu(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`&&$u({messages:t,start:n,total:r})}function $u(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(ed)}function ed(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var td={read:Wu,write:Gu,remove:Ku},nd=class{constructor(e=td){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return rd(this.rawHistoryPage(e))}mergeHistory(e,t){let n=qu(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.cache.write(e,n),rd(n)}applyLiveEvent(e,t){return au(e,t)}seedStreamingPartial(e,t){return iu(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 rd(e){let t=e?.start??0;return{messages:zc(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}var id=`pi-web:pending-prompt:`;function ad(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function od(e){return`${id}${e}`}function sd(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`text`)==`string`}function cd(e){return!!(e instanceof TypeError&&/fetch|network|load failed|failed to fetch/i.test(e.message)||e instanceof Error&&/ECONNREFUSED|ENOTFOUND|socket hang up|network.*down/i.test(e.message))}function ld(e,t=ad()){try{let n=t?.getItem(od(e));if(n==null||n===``)return[];let r=JSON.parse(n);return Array.isArray(r)?r.filter(sd):[]}catch{return[]}}function ud(e,t,n=ad()){try{let r=ld(e,n);r.push(t),n?.setItem(od(e),JSON.stringify(r))}catch{}}function dd(e,t=ad()){try{t?.removeItem(od(e))}catch{}}function fd(e){return e.trim().toLowerCase().split(/\s+/u).filter(Boolean)}function pd(e,t){let n=fd(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:_d(r.charAt(t-1))&&(i+=20);continue}if(!hd(e,r))return;i+=25}return i}function md(e,t,n){if(fd(t).length===0)return[...e];let r=[];return e.forEach((e,i)=>{let a=pd(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 hd(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&&!gd(t,n)||e.add(n+1));if(e.size===0)return!1;n=e}return!0}function gd(e,t){return t===0||_d(e.charAt(t-1))}function _d(e){return e===``||/[\s\-_/.:@]/u.test(e)}function vd(e,t=e.length){let n=e.slice(0,t),r=wd(n,t);if(r!==void 0)return r;let i=Td(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 yd=12;function bd(e,t){return md(e.filter(xd),t,Sd).slice(0,yd).map(e=>({insertText:`#${e.provider}/${e.id}`,detail:e.provider,...e.name!==void 0&&e.name!==``&&e.name!==e.id?{description:e.name}:{}}))}function xd(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function Sd(e){return`${e.provider}/${e.id} ${e.id}${e.name===void 0||e.name===``?``:` ${e.name}`}`}function Cd(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function wd(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 Td(e,t){let n=e.lastIndexOf(`
|
|
20
20
|
`)+1,r=e.slice(n),i=Ed(r,`@ `),a=Ed(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 Ed(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Dd(e[n-1]))return n;return-1}function Dd(e){return e===` `||e===` `}function Od(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(jd(e).startsWith(`/`))return{kind:`command`};let n=vd(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function kd(e){return Od(e).kind===`shell`}function Ad(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function jd(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
|
|
21
|
-
`))+1;return e.slice(t)}var Md=5e4;function Nd(e,t=Math.random){return Math.round(e*(.5+t()*.5))}var Pd=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<Md||Hd(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),Hd(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=ls(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=Nd(this.reconnectDelay);this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}reconnectNow(){!this.shouldReconnect||this.socket!==void 0||(window.clearTimeout(this.reconnectTimer),this.reconnectDelay=500,this.open())}async handleMessage(e,t,n){this.socket===t&&(this.lastFrameAt=Date.now());let r=Id(await Vd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Fd=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<Md||Hd(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),Hd(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=ds(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=Nd(this.reconnectDelay);this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}reconnectNow(){!this.shouldReconnect||this.socket!==void 0||(window.clearTimeout(this.reconnectTimer),this.reconnectDelay=500,this.open())}async handleMessage(e,t){this.socket===t&&(this.lastFrameAt=Date.now());let n=Ld(await Vd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Id(e){let t=Bd(e);if(t===`notifications.inbox`)return zd(()=>br(e));if(t===`ask.opened`)return zd(()=>jn(e));if(t===`ask.closed`)return zd(()=>Mn(e));if(t===`dialog.opened`)return zd(()=>Gn(e));if(t===`dialog.closed`)return zd(()=>Kn(e));let n=zd(()=>sr(e));return n===void 0?void 0:Rd(n,e)}function Ld(e){let t=Bd(e);return zd(t===`sessions.unread`?()=>nr(e):t===`session.startup`?()=>rr(e):()=>cr(e))}function Rd(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 zd(e){try{return e()}catch{return}}function Bd(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Vd(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 Hd(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 Ud(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||kc(e)?`transient`:`unknown`}function Wd(e,t){return e!==void 0&&e.archived!==!0&&Ud(e,t)===`persisted`}function Gd(e,t){return e!==void 0&&e.archived!==!0&&Ud(e,t)===`transient`}function Kd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var qd=class{constructor(e,t,n=Kd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Yd(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 Jd(e){return typeof e==`string`&&e!==``?e:void 0}function Yd(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Xd(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 Xd(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 Qd=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)}},$d=`pi-web:session-selection:v1`,ef=class{constructor(e=Kd()){this.sessionIdsByCwd=new qd($d,Jd,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function tf(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return rf(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 nf(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function rf(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function af(e,t,n){return of(e,[t],n)}function of(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function sf(e,t,n){return cf(e,t,[n])}function cf(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 lf=100,uf=100,df=class{constructor(e,t,n,r=new Qd,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 mc,this.socket=i.socket??new Pd,this.api=i.api??I,this.transcripts=i.transcripts??new nd,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();nf(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 tf(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(vf(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:lf},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(kc(e)&&Af(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:lf},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 vf(i)?(!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&kd(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&&kd(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:mf(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(vf(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(vf(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=bf(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Sf(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=>Cd(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(e){if(this.setState({error:String(e)}),c!==void 0&&this.setState({messages:Jl(this.getState().messages,c)}),cd(e))throw e;return!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}beginTrackedSend(e,t){if(t.trim()===``||this.getState().selectedSession?.id!==e.id)return;let n=zl();return this.setState({messages:[...this.getState().messages,Bl(t,n)]}),n}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Bc(`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,Bc(`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,Bc(`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?mf(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||vf(r))throw Error(`The session tree navigator is no longer available`);let a=L(n),o=this.selectionSeq,s=Hs(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(Cl(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||vf(n))throw Error(`The session tree navigator is no longer available`);let i=L(t),a=this.selectionSeq,o=Hs(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&&Cl(Hs(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||vf(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(Gd(e,t)){await this.deleteCachedNewSession(e);return}if(Wd(e,t))try{await this.api.archive(e,L(this.getState()));let t=this.getState(),n=af(t.sessions,e.id,new Date().toISOString()),r=sf(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||!Wd(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=of(r.sessions,n,new Date().toISOString()),a=cf(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=Tf(e).filter(e=>Wd(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=of(e.sessions,n,i??new Date().toISOString()),r=cf(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: ${Df(e)}`})}}async deleteArchivedSessions(e){let t=Tf(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: ${Df(e)}`})}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:Ef(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:Ef(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=of(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:hf(t.sessionStatuses,a),sessionActivities:hf(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=cf(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=Oc(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||!Gd(e,this.statusForSession(e)))return;let t=vf(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,L(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Dc(e.id,L(this.getState())),wl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:mf(n.sessionStatuses,e.id),sessionActivities:pf(n.sessionActivities,e.id),sendingPrompts:mf(n.sendingPrompts,e.id),clientQueuedSessionMessages:mf(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||!Wd(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?.()}reconnectSocketNow(){this.socket.reconnectNow?.()}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||vf(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||vf(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:Jl(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||vf(n))return;let r=L(t);try{let t=await this.api.subagentRunOutput(n,e.runId,r);this.setState({messages:[...this.getState().messages,Bc(`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||vf(n))return;let r=L(t);try{let t=await this.api.backgroundTaskOutput(n,e.id,r);this.setState({messages:[...this.getState().messages,Bc(`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||vf(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(vf(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||vf(r))return;let i=L(n),a=this.selectionSeq;try{let n=await t(r,i);jl(Hs(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:Jl(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||vf(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=Hs(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:lf},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&&!vf(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 Hs(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:bf(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:bf(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){wl(Hs(n.machineId,e)),this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Tc(t,n.machineId),Tl(Hs(n.machineId,e),Hs(n.machineId,t.id));let a=Ec(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:_f(o.sessions,e,a),sessionActivities:pf(o.sessionActivities,e),sendingPrompts:gf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:gf(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=Df(t),c=xf(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=>vf(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);Tc(r,n),Tl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Dc(e.id,n);let i=Ec(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(!kc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Ac(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,Bc(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Cl(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?Yl(t.messages,e.queuedMessages):t.messages,i=t.sessionActivities[e.sessionId]?.phase===`active`&&!Ls(e),a=n&&Ls(t.status??e)&&!Ls(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Of(t,e.sessionId,e.messageCount),...i?{sessionActivities:pf(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=Wl(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),...ff(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(kf(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`?bf(t.tempId,t.queuedSends.length):yf(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()},uf)}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 ff(e){return e.reason!==`timeout`||e.dialog.runScoped}function pf(e,t){return mf(e,t)}function mf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function hf(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 gf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...mf(e,t),[n]:r}}function _f(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 vf(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function yf(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function bf(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 xf(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 Sf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Cf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function Cf(e,t){let n=wf(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function wf(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 Tf(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 Ef(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Df(e){return e instanceof Error?e.message:String(e)}function Of(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 kf(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Af(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var jf={order:0,overflowWatermark:0};function Mf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:jf,optimisticDismissedIds:[],announcements:[]}}function Nf(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&&Gf(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 Pf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Mf(t),needsRefresh:!1,changed:!1};if(e===void 0||!Gf(e,t))return{value:qf(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:qf(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(!Jf(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 Ff(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=Xf(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,...Zf(Yf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function If(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function Lf(e){return`${If(e.severity)} notification received.`}function Rf(e){return e.retainedCount+e.discardedCount}function zf(e){return`Notifications (${String(Rf(e))})`}function Bf(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${If(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Vf(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 Hf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Uf(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Wf(e){if(!e.truncated)return;let t=Dt/1024;return`Message truncated at ${String(t)} KiB.`}function Gf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Kf(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function qf(e){return{...Mf(e),status:`stale`}}function Jf(e,t){return e.length===t.retainedCount&&Yf(e)===t.highestSeverity}function Yf(e){let t;for(let n of e)t=Kf(t,n.severity);return t}function Xf(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 Zf(e){return e===void 0?{}:{highestSeverity:e}}var Qf=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:Mf(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=Pf(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=Ff(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=$f(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: ${tp(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=Ff(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=$f(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: ${tp(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||ep(i,t,r)?Nf(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Pf(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&&Gf(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||!Gf(r,e))return;if(!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=ep(r,e,t)?Nf(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Gf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Gf(t,e))&&this.setState({selectedNotificationInbox:Mf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Gf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Gf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Gf(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 $f(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function ep(e,t,n){return!Gf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function tp(e){return e instanceof Error?e.message:String(e)}var np=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)}},rp=`pi-web:workspace-selection:v1`,ip=class{constructor(e=Kd()){this.workspaceIdsByProject=new qd(rp,Jd,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function ap(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 op=50,sp=class{constructor(e,t,n,r,i=new np,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 mc(a.topologyRefreshDebounceMs??op)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Fs()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Vs(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,...Fs()});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=ap(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Vs(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:Vs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Fs()});try{let r=Oc(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(Vs(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=cp(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||lp(e,n)))return{selectedWorkspace:n}}};function cp(e){return e.find(e=>e.isMain)??e[0]}function lp(e,t){return up(e,t)}function up(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)=>up(e,t[n]));if(!dp(e)||!dp(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&up(e[n],t[n]))}function dp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fp=`pi-web:machine-navigation:v1`,pp=class{constructor(e=Kd()){this.snapshotsByMachine=new qd(fp,vp,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?_p(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,_p(e))}forget(e){this.snapshotsByMachine.delete(e)}};function mp(e){return{machineId:e,surface:{}}}function hp(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 gp(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 _p(e){return{...e,surface:{...e.surface}}}function vp(e){if(!wp(e))return;let t=Cp(e,`machineId`);if(t===void 0)return;let n=xp(Cp(e,`tool`)),r=bp(Cp(e,`view`));return{machineId:t,projectId:Cp(e,`projectId`),workspaceId:Cp(e,`workspaceId`),sessionId:Cp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:yp(e.surface)}}function yp(e){return wp(e)?{selectedFilePath:Cp(e,`selectedFilePath`),selectedTerminalId:Cp(e,`selectedTerminalId`)}:{}}function bp(e){return e===`navigation`||e===`chat`?e:xp(e)}function xp(e){return Sp(e)?e:void 0}function Sp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Cp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function wp(e){return typeof e==`object`&&!!e}var Tp=`pi-web:terminal-selection:v1`,Ep=class{constructor(e=Kd()){this.terminalIdsByCwd=new qd(Tp,Jd,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 Dp(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 Op(e){return e.find(e=>!e.exited)??e[0]}var kp=1200,Ap=[`mod`,`alt`,`shift`],jp=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Ip(e);if(r===void 0)return!1;let i=Mp(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(),!Lp(r))return!1}else if(!Lp(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>em(t.tokens,e));return n===void 0?t.some(t=>tm(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},kp)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function Mp(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Rp(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(Hp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(Up),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Wp(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:Vp(t),i=n?[...s.get(e)??[]].sort(Hp).map(Vp):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Np(e){return qp(e,{requireFirstChordActivator:!0})}function Pp(e){let t=qp(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Fp(e){return Pp(e).map(e=>e.split(`+`).map($p).join(`+`)).join(` `)}function Ip(e){if(e.isComposing)return;let t=Zp(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 Lp(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Rp(e,t,n){let r=zp(e,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Pp(i),o=a[0];if(!(o===void 0||!Lp(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:Bp(a),order:n}}function zp(e,t){if(t!==void 0){for(let n of[e.id,...e.shortcutAliases??[]])if(Object.hasOwn(t,n))return t[n]}}function Bp(e){return e.join(`\0`)}function Vp(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Hp(e,t){return Gp(e.source)-Gp(t.source)||Kp(e.action.id,t.action.id)||Kp(e.action.title,t.action.title)||e.order-t.order}function Up(e,t){return e.tokens.length-t.tokens.length||Hp(e,t)}function Wp(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&tm(e.tokens,t.tokens))}function Gp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Kp(e,t){return e<t?-1:+(e>t)}function qp(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=Jp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Lp(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 Jp(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=Yp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${$p(t)} modifiers.`};n.add(t);continue}let i=Xp(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:[...Ap.filter(e=>n.has(e)),r].join(`+`)}}function Yp(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 Xp(e){let t=Qp(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 Zp(e){return e===` `?`space`:Xp(e.toLowerCase())}function Qp(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 $p(e){return e===`mod`?nm()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?nm()?`⌥`:`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 em(e,t){return e.length===t.length&&tm(e,t)}function tm(e,t){return t.every((t,n)=>e[n]===t)}function nm(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function rm(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 im=[`ask-user-card`,`extension-dialog-card`];function am(e){return e.some(e=>im.includes(sm(e)))}function om(e){let t=[],n=e instanceof Node?e:null;for(;n!==null;)t.push(n),n=n.parentNode??(n instanceof ShadowRoot?n.host:null);return t}function sm(e){return e instanceof Element?e.tagName.toLowerCase():``}function cm(e){return e.hasSelectedSession&&e.documentVisible}function lm(e,t){return t?.phase===`error`?`error`:e===void 0?t?.phase===`active`?`working`:void 0:um(e)?`asking`:e.isStreaming||e.isBashRunning||e.isCompacting||e.pendingMessageCount>0||t?.phase===`active`?`working`:`idle`}function um(e){return e===void 0?!1:e.pendingAsk!==void 0||(e.pendingDialogs?.length??0)>0}var dm={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function fm(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=bm(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=bm(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function pm(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function mm(e){if(e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=fm(e.draft);return!t.ok||pm(t.request)!==pm(e.previewRequest)?!1:hm(e.preview)}function hm(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function gm(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 _m(e,t){let n=new Set(gm(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 vm(e,t){return t(ym(e))}function ym(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 bm(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 xm=new Set,Sm=Tt+1,Cm={unreadCatalog:e=>Do.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Do.acknowledgeUnread(e,t,n,r)},wm=class{constructor(e={}){this.machines=new Map,this.api=e.api??Cm,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 xm;let r=new Set;for(let e of t)n.summariesByIdentity.has(Am(e))&&r.add(e.id);return r.size===0?xm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(Am(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=Tm(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(Am(t));if(i===void 0)return Promise.resolve();let a=jm(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=Dm(t),a=`fresh`,o=!1;for(let e of n.events){let t=Tm(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>=Sm?(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=!km(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 Tm(e,t,n){if(e===void 0){let e=Om(n.catalogId);return n.catalogRevision===1?Em(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=Om(n.catalogId);return n.catalogRevision===1?Em(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?Em(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function Em(e,t,n){let r=new Map(e.summariesByIdentity),i=Am(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 Dm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[Am(e),{...e}]))}}function Om(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function km(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 Am(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function jm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}function Mm(){return{selectedSessionKey:void 0,warningSetSignature:Nm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function Nm(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 Pm(e,t,n){let r=Nm(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 Fm(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 Im(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 Lm(e){return e.collapsed?Im(e):Fm(e)}var Rm=`themes:classic`,zm={themeId:`themes:pi-web-dark`,auto:!0},Bm=`pi-web-app-theme`,Vm=`--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(`.`),Hm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Um(){try{let e=window.localStorage.getItem(Bm);return e===null?void 0:Ym(e)}catch{return}}function Wm(e){try{window.localStorage.setItem(Bm,JSON.stringify(e))}catch{}}function Gm(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of Vm){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function Km(e){let t=qm(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=Jm(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 qm(e,t=Rm){return e.find(e=>e.id===t)??e[0]}function Jm(e,t){return e.find(e=>e.light===t||e.dark===t)}function Ym(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return Xm(e)?e:void 0}catch{return}}function Xm(e){if(!Zm(e))return!1;let t=e.themeId,n=e.auto;return Qm(t)&&typeof n==`boolean`}function Zm(e){return typeof e==`object`&&!!e}function Qm(e){return typeof e==`string`&&Hm.test(e)}var $m=`workspace.delete`,eh=`pi.operation`,th=`target.workspaceId`;function nh(e){return e?.removal!==void 0&&!e.isMain}function rh(e){return e.removal?.confirmation}function ih(e){return{...e===void 0?{}:{projectId:e},metadata:{[eh]:$m}}}function ah(e){let t={};for(let n of e){let e=ch(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 oh(e){return Object.entries(e).filter(([,e])=>lh(e)).map(([e])=>e)}function sh(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&lh(n)}function ch(e){return e.metadata[th]}function lh(e){return e.status===`queued`||e.status===`running`}function uh(){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:dh,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+3`,group:`Navigation`,enabled:dh,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:dh,run:e=>e.refreshFiles()},{id:`workspace.delete`,title:`Remove Workspace`,description:`Run the owning provider's workspace removal operation`,group:`Workspace`,enabled:fh,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:dh,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:ph,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:ph,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:mh,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:gh,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:hh,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&Ls(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function dh(e){return e.state.selectedWorkspace!==void 0}function fh(e){let t=e.state.selectedWorkspace;return nh(t)&&!sh(e.state,t)}function ph(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function mh(e){return Wd(e.state.selectedSession,e.state.status)}function hh(e){return Gd(e.state.selectedSession,e.state.status)}function gh(e){return Wd(e.state.selectedSession,e.state.status)?!Ls(e.state.status,e.state.activity):!1}function _h(e){return typeof e==`string`?vh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function vh(e){switch(e){case`navigation`:return Ye`
|
|
21
|
+
`))+1;return e.slice(t)}var Md=5e4;function Nd(e,t=Math.random){return Math.round(e*(.5+t()*.5))}var Pd=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<Md||Hd(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),Hd(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=ls(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=Nd(this.reconnectDelay);this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}reconnectNow(){!this.shouldReconnect||this.socket!==void 0||(window.clearTimeout(this.reconnectTimer),this.reconnectDelay=500,this.open())}async handleMessage(e,t,n){this.socket===t&&(this.lastFrameAt=Date.now());let r=Id(await Vd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Fd=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<Md||Hd(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),Hd(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=ds(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=Nd(this.reconnectDelay);this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}reconnectNow(){!this.shouldReconnect||this.socket!==void 0||(window.clearTimeout(this.reconnectTimer),this.reconnectDelay=500,this.open())}async handleMessage(e,t){this.socket===t&&(this.lastFrameAt=Date.now());let n=Ld(await Vd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Id(e){let t=Bd(e);if(t===`notifications.inbox`)return zd(()=>br(e));if(t===`ask.opened`)return zd(()=>jn(e));if(t===`ask.closed`)return zd(()=>Mn(e));if(t===`dialog.opened`)return zd(()=>Gn(e));if(t===`dialog.closed`)return zd(()=>Kn(e));let n=zd(()=>sr(e));return n===void 0?void 0:Rd(n,e)}function Ld(e){let t=Bd(e);return zd(t===`sessions.unread`?()=>nr(e):t===`session.startup`?()=>rr(e):()=>cr(e))}function Rd(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 zd(e){try{return e()}catch{return}}function Bd(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Vd(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 Hd(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 Ud(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||kc(e)?`transient`:`unknown`}function Wd(e,t){return e!==void 0&&e.archived!==!0&&Ud(e,t)===`persisted`}function Gd(e,t){return e!==void 0&&e.archived!==!0&&Ud(e,t)===`transient`}function Kd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var qd=class{constructor(e,t,n=Kd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Yd(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 Jd(e){return typeof e==`string`&&e!==``?e:void 0}function Yd(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Xd(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 Xd(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 Qd=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)}},$d=`pi-web:session-selection:v1`,ef=class{constructor(e=Kd()){this.sessionIdsByCwd=new qd($d,Jd,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function tf(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return rf(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 nf(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function rf(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function af(e,t,n){return of(e,[t],n)}function of(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function sf(e,t,n){return cf(e,t,[n])}function cf(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 lf=100,uf=100,df=class{constructor(e,t,n,r=new Qd,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 mc,this.socket=i.socket??new Pd,this.api=i.api??I,this.transcripts=i.transcripts??new nd,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();nf(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 tf(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(vf(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:lf},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(kc(e)&&Af(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:lf},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 vf(i)?(!o&&a.startsWith(`/`)?this.enqueuePendingSessionSend(i,{type:`command`,text:e}):!o&&kd(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&&kd(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:mf(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(vf(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(vf(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=bf(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Sf(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,r??[]);try{if(s&&i===`folder`){let i=(await this.api.saveAttachments(e,r,a)).map(e=>Cd(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(e){if(this.setState({error:String(e)}),c!==void 0&&this.setState({messages:Jl(this.getState().messages,c)}),cd(e))throw e;return!1}finally{o.markSending&&this.markSendingPrompt(e.id,!1)}}beginTrackedSend(e,t,n=[]){if(t.trim()===``&&n.length===0||this.getState().selectedSession?.id!==e.id)return;let r=zl();return this.setState({messages:[...this.getState().messages,Bl(t,r,n)]}),r}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,Bc(`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,Bc(`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,Bc(`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?mf(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||vf(r))throw Error(`The session tree navigator is no longer available`);let a=L(n),o=this.selectionSeq,s=Hs(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(Cl(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||vf(n))throw Error(`The session tree navigator is no longer available`);let i=L(t),a=this.selectionSeq,o=Hs(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&&Cl(Hs(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||vf(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(Gd(e,t)){await this.deleteCachedNewSession(e);return}if(Wd(e,t))try{await this.api.archive(e,L(this.getState()));let t=this.getState(),n=af(t.sessions,e.id,new Date().toISOString()),r=sf(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||!Wd(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=of(r.sessions,n,new Date().toISOString()),a=cf(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=Tf(e).filter(e=>Wd(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=of(e.sessions,n,i??new Date().toISOString()),r=cf(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: ${Df(e)}`})}}async deleteArchivedSessions(e){let t=Tf(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: ${Df(e)}`})}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t);return{succeededIds:n.archivedSessionIds,failures:Ef(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t);return{succeededIds:n.deletedSessionIds,failures:Ef(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=of(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:hf(t.sessionStatuses,a),sessionActivities:hf(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=cf(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=Oc(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||!Gd(e,this.statusForSession(e)))return;let t=vf(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,L(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Dc(e.id,L(this.getState())),wl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:mf(n.sessionStatuses,e.id),sessionActivities:pf(n.sessionActivities,e.id),sendingPrompts:mf(n.sendingPrompts,e.id),clientQueuedSessionMessages:mf(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||!Wd(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?.()}reconnectSocketNow(){this.socket.reconnectNow?.()}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||vf(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||vf(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:Jl(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||vf(n))return;let r=L(t);try{let t=await this.api.subagentRunOutput(n,e.runId,r);this.setState({messages:[...this.getState().messages,Bc(`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||vf(n))return;let r=L(t);try{let t=await this.api.backgroundTaskOutput(n,e.id,r);this.setState({messages:[...this.getState().messages,Bc(`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||vf(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(vf(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||vf(r))return;let i=L(n),a=this.selectionSeq;try{let n=await t(r,i);jl(Hs(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:Jl(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||vf(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=Hs(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:lf},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&&!vf(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 Hs(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:bf(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:bf(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){wl(Hs(n.machineId,e)),this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Tc(t,n.machineId),Tl(Hs(n.machineId,e),Hs(n.machineId,t.id));let a=Ec(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:_f(o.sessions,e,a),sessionActivities:pf(o.sessionActivities,e),sendingPrompts:gf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:gf(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=Df(t),c=xf(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=>vf(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);Tc(r,n),Tl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Dc(e.id,n);let i=Ec(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(!kc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Ac(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,Bc(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Cl(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?Yl(t.messages,e.queuedMessages):t.messages,i=t.sessionActivities[e.sessionId]?.phase===`active`&&!Ls(e),a=n&&Ls(t.status??e)&&!Ls(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Of(t,e.sessionId,e.messageCount),...i?{sessionActivities:pf(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=Wl(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),...ff(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(kf(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`?bf(t.tempId,t.queuedSends.length):yf(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()},uf)}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 ff(e){return e.reason!==`timeout`||e.dialog.runScoped}function pf(e,t){return mf(e,t)}function mf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function hf(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 gf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...mf(e,t),[n]:r}}function _f(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 vf(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function yf(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function bf(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 xf(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 Sf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Cf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function Cf(e,t){let n=wf(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function wf(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 Tf(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 Ef(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Df(e){return e instanceof Error?e.message:String(e)}function Of(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 kf(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Af(e){return e instanceof Error&&e.message.toLowerCase().includes(`session not found`)}var jf={order:0,overflowWatermark:0};function Mf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:jf,optimisticDismissedIds:[],announcements:[]}}function Nf(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&&Gf(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 Pf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Mf(t),needsRefresh:!1,changed:!1};if(e===void 0||!Gf(e,t))return{value:qf(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:qf(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(!Jf(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 Ff(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=Xf(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,...Zf(Yf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function If(e){return e===`error`?`Error`:e===`warning`?`Warning`:`Info`}function Lf(e){return`${If(e.severity)} notification received.`}function Rf(e){return e.retainedCount+e.discardedCount}function zf(e){return`Notifications (${String(Rf(e))})`}function Bf(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`Dismiss ${If(e.severity).toLowerCase()} notification`;let n=Array.from(t);return`Dismiss notification: ${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Vf(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 Hf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Uf(e){return`${String(e)} older ${e===1?`notification`:`notifications`} not shown.`}function Wf(e){if(!e.truncated)return;let t=Dt/1024;return`Message truncated at ${String(t)} KiB.`}function Gf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Kf(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function qf(e){return{...Mf(e),status:`stale`}}function Jf(e,t){return e.length===t.retainedCount&&Yf(e)===t.highestSeverity}function Yf(e){let t;for(let n of e)t=Kf(t,n.severity);return t}function Xf(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 Zf(e){return e===void 0?{}:{highestSeverity:e}}var Qf=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:Mf(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=Pf(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=Ff(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=$f(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: ${tp(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=Ff(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=$f(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: ${tp(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||ep(i,t,r)?Nf(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Pf(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&&Gf(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||!Gf(r,e))return;if(!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=ep(r,e,t)?Nf(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Gf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Gf(t,e))&&this.setState({selectedNotificationInbox:Mf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Gf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Gf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Gf(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 $f(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function ep(e,t,n){return!Gf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function tp(e){return e instanceof Error?e.message:String(e)}var np=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)}},rp=`pi-web:workspace-selection:v1`,ip=class{constructor(e=Kd()){this.workspaceIdsByProject=new qd(rp,Jd,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function ap(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 op=50,sp=class{constructor(e,t,n,r,i=new np,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 mc(a.topologyRefreshDebounceMs??op)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Fs()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(Vs(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,...Fs()});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=ap(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Vs(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:Vs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Fs()});try{let r=Oc(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(Vs(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=cp(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||lp(e,n)))return{selectedWorkspace:n}}};function cp(e){return e.find(e=>e.isMain)??e[0]}function lp(e,t){return up(e,t)}function up(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)=>up(e,t[n]));if(!dp(e)||!dp(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&up(e[n],t[n]))}function dp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fp=`pi-web:machine-navigation:v1`,pp=class{constructor(e=Kd()){this.snapshotsByMachine=new qd(fp,vp,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?_p(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,_p(e))}forget(e){this.snapshotsByMachine.delete(e)}};function mp(e){return{machineId:e,surface:{}}}function hp(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 gp(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 _p(e){return{...e,surface:{...e.surface}}}function vp(e){if(!wp(e))return;let t=Cp(e,`machineId`);if(t===void 0)return;let n=xp(Cp(e,`tool`)),r=bp(Cp(e,`view`));return{machineId:t,projectId:Cp(e,`projectId`),workspaceId:Cp(e,`workspaceId`),sessionId:Cp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:yp(e.surface)}}function yp(e){return wp(e)?{selectedFilePath:Cp(e,`selectedFilePath`),selectedTerminalId:Cp(e,`selectedTerminalId`)}:{}}function bp(e){return e===`navigation`||e===`chat`?e:xp(e)}function xp(e){return Sp(e)?e:void 0}function Sp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Cp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function wp(e){return typeof e==`object`&&!!e}var Tp=`pi-web:terminal-selection:v1`,Ep=class{constructor(e=Kd()){this.terminalIdsByCwd=new qd(Tp,Jd,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 Dp(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 Op(e){return e.find(e=>!e.exited)??e[0]}var kp=1200,Ap=[`mod`,`alt`,`shift`],jp=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Ip(e);if(r===void 0)return!1;let i=Mp(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(),!Lp(r))return!1}else if(!Lp(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>em(t.tokens,e));return n===void 0?t.some(t=>tm(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},kp)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function Mp(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Rp(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(Hp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(Up),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Wp(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:Vp(t),i=n?[...s.get(e)??[]].sort(Hp).map(Vp):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Np(e){return qp(e,{requireFirstChordActivator:!0})}function Pp(e){let t=qp(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Fp(e){return Pp(e).map(e=>e.split(`+`).map($p).join(`+`)).join(` `)}function Ip(e){if(e.isComposing)return;let t=Zp(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 Lp(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Rp(e,t,n){let r=zp(e,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Pp(i),o=a[0];if(!(o===void 0||!Lp(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:Bp(a),order:n}}function zp(e,t){if(t!==void 0){for(let n of[e.id,...e.shortcutAliases??[]])if(Object.hasOwn(t,n))return t[n]}}function Bp(e){return e.join(`\0`)}function Vp(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Hp(e,t){return Gp(e.source)-Gp(t.source)||Kp(e.action.id,t.action.id)||Kp(e.action.title,t.action.title)||e.order-t.order}function Up(e,t){return e.tokens.length-t.tokens.length||Hp(e,t)}function Wp(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&tm(e.tokens,t.tokens))}function Gp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Kp(e,t){return e<t?-1:+(e>t)}function qp(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=Jp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Lp(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 Jp(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=Yp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`Shortcut has duplicate ${$p(t)} modifiers.`};n.add(t);continue}let i=Xp(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:[...Ap.filter(e=>n.has(e)),r].join(`+`)}}function Yp(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 Xp(e){let t=Qp(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 Zp(e){return e===` `?`space`:Xp(e.toLowerCase())}function Qp(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 $p(e){return e===`mod`?nm()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?nm()?`⌥`:`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 em(e,t){return e.length===t.length&&tm(e,t)}function tm(e,t){return t.every((t,n)=>e[n]===t)}function nm(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}function rm(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 im=[`ask-user-card`,`extension-dialog-card`];function am(e){return e.some(e=>im.includes(sm(e)))}function om(e){let t=[],n=e instanceof Node?e:null;for(;n!==null;)t.push(n),n=n.parentNode??(n instanceof ShadowRoot?n.host:null);return t}function sm(e){return e instanceof Element?e.tagName.toLowerCase():``}function cm(e){return e.hasSelectedSession&&e.documentVisible}function lm(e,t){return t?.phase===`error`?`error`:e===void 0?t?.phase===`active`?`working`:void 0:um(e)?`asking`:e.isStreaming||e.isBashRunning||e.isCompacting||e.pendingMessageCount>0||t?.phase===`active`?`working`:`idle`}function um(e){return e===void 0?!1:e.pendingAsk!==void 0||(e.pendingDialogs?.length??0)>0}var dm={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function fm(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=bm(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=bm(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function pm(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function mm(e){if(e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=fm(e.draft);return!t.ok||pm(t.request)!==pm(e.previewRequest)?!1:hm(e.preview)}function hm(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function gm(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 _m(e,t){let n=new Set(gm(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 vm(e,t){return t(ym(e))}function ym(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 bm(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 xm=new Set,Sm=Tt+1,Cm={unreadCatalog:e=>Do.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>Do.acknowledgeUnread(e,t,n,r)},wm=class{constructor(e={}){this.machines=new Map,this.api=e.api??Cm,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 xm;let r=new Set;for(let e of t)n.summariesByIdentity.has(Am(e))&&r.add(e.id);return r.size===0?xm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(Am(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=Tm(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(Am(t));if(i===void 0)return Promise.resolve();let a=jm(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=Dm(t),a=`fresh`,o=!1;for(let e of n.events){let t=Tm(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>=Sm?(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=!km(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 Tm(e,t,n){if(e===void 0){let e=Om(n.catalogId);return n.catalogRevision===1?Em(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=Om(n.catalogId);return n.catalogRevision===1?Em(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?Em(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function Em(e,t,n){let r=new Map(e.summariesByIdentity),i=Am(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 Dm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[Am(e),{...e}]))}}function Om(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function km(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 Am(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function jm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}function Mm(){return{selectedSessionKey:void 0,warningSetSignature:Nm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function Nm(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 Pm(e,t,n){let r=Nm(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 Fm(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 Im(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 Lm(e){return e.collapsed?Im(e):Fm(e)}var Rm=`themes:classic`,zm={themeId:`themes:pi-web-dark`,auto:!0},Bm=`pi-web-app-theme`,Vm=`--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(`.`),Hm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Um(){try{let e=window.localStorage.getItem(Bm);return e===null?void 0:Ym(e)}catch{return}}function Wm(e){try{window.localStorage.setItem(Bm,JSON.stringify(e))}catch{}}function Gm(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of Vm){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function Km(e){let t=qm(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=Jm(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 qm(e,t=Rm){return e.find(e=>e.id===t)??e[0]}function Jm(e,t){return e.find(e=>e.light===t||e.dark===t)}function Ym(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return Xm(e)?e:void 0}catch{return}}function Xm(e){if(!Zm(e))return!1;let t=e.themeId,n=e.auto;return Qm(t)&&typeof n==`boolean`}function Zm(e){return typeof e==`object`&&!!e}function Qm(e){return typeof e==`string`&&Hm.test(e)}var $m=`workspace.delete`,eh=`pi.operation`,th=`target.workspaceId`;function nh(e){return e?.removal!==void 0&&!e.isMain}function rh(e){return e.removal?.confirmation}function ih(e){return{...e===void 0?{}:{projectId:e},metadata:{[eh]:$m}}}function ah(e){let t={};for(let n of e){let e=ch(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 oh(e){return Object.entries(e).filter(([,e])=>lh(e)).map(([e])=>e)}function sh(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&lh(n)}function ch(e){return e.metadata[th]}function lh(e){return e.status===`queued`||e.status===`running`}function uh(){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:dh,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.terminal`,title:`Go to Terminal`,shortcut:`mod+3`,group:`Navigation`,enabled:dh,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`Refresh Files`,shortcut:`mod+shift+f`,group:`Workspace`,enabled:dh,run:e=>e.refreshFiles()},{id:`workspace.delete`,title:`Remove Workspace`,description:`Run the owning provider's workspace removal operation`,group:`Workspace`,enabled:fh,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`Start Session`,shortcut:`mod+enter`,group:`Session`,enabled:dh,run:e=>e.startSession()},{id:`model.select`,title:`Select Model`,description:`Choose the model for the selected session`,group:`Session`,enabled:ph,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`Select Thinking Level`,description:`Choose the thinking level for the selected session`,group:`Session`,enabled:ph,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`Archive Session`,description:`Archive the selected session`,group:`Session`,enabled:mh,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:gh,run:e=>e.reloadSession()},{id:`session.delete`,title:`Delete New Session`,description:`Delete the selected transient new session`,group:`Session`,enabled:hh,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`Stop Active Work`,shortcut:`mod+.`,group:`Session`,enabled:e=>e.state.selectedSession!==void 0&&Ls(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function dh(e){return e.state.selectedWorkspace!==void 0}function fh(e){let t=e.state.selectedWorkspace;return nh(t)&&!sh(e.state,t)}function ph(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function mh(e){return Wd(e.state.selectedSession,e.state.status)}function hh(e){return Gd(e.state.selectedSession,e.state.status)}function gh(e){return Wd(e.state.selectedSession,e.state.status)?!Ls(e.state.status,e.state.activity):!1}function _h(e){return typeof e==`string`?vh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function vh(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>
|
|
@@ -442,6 +442,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
|
|
|
442
442
|
.drawer-tab { flex: 0 0 auto; display: inline-flex; align-items: center; gap: var(--pi-space-3); box-sizing: border-box; min-height: 28px; padding: var(--pi-space-2) var(--pi-space-5); border: 1px solid transparent; border-radius: var(--pi-radius-pill); background: transparent; color: var(--pi-muted); font: inherit; font-size: var(--pi-text-2xs); font-weight: 600; letter-spacing: .03em; text-transform: uppercase; white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; }
|
|
443
443
|
.drawer-tab:hover { color: var(--pi-text-bright); }
|
|
444
444
|
.drawer-tab:focus-visible { outline: var(--pi-focus-ring-width) solid var(--pi-accent); outline-offset: 1px; }
|
|
445
|
+
.drawer-tab, .activity-filter, .activity-history-toggle { transition: background-color var(--pi-motion-fast) var(--pi-ease), border-color var(--pi-motion-fast) var(--pi-ease), color var(--pi-motion-fast) var(--pi-ease); }
|
|
445
446
|
.drawer-tab.selected { border-color: var(--pi-border); background: var(--pi-surface); color: var(--pi-text-bright); }
|
|
446
447
|
.drawer-summary { flex: 0 1 auto; min-width: 0; overflow: hidden; color: var(--pi-muted); font-size: var(--pi-text-2xs); text-overflow: ellipsis; white-space: nowrap; }
|
|
447
448
|
.drawer-header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: var(--pi-space-1); }
|
|
@@ -470,6 +471,11 @@ 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
|
|
|
470
471
|
instead of letting a thumb bounce off it. */
|
|
471
472
|
.subagent-row:disabled { cursor: default; opacity: .72; }
|
|
472
473
|
.subagent-row:disabled:hover { background: var(--pi-surface); }
|
|
474
|
+
/* Status changes under the reader's eyes - a row goes running to done while
|
|
475
|
+
the drawer is open - so the colours that carry that meaning move rather
|
|
476
|
+
than jump. Paint only: animating the row's size would shift every row
|
|
477
|
+
below it. The reduced-motion block above collapses these to nothing. */
|
|
478
|
+
.subagent-row { transition: background-color var(--pi-motion-base) var(--pi-ease), border-color var(--pi-motion-base) var(--pi-ease); }
|
|
473
479
|
.subagent-row.status-working, .subagent-row.status-running { border-color: var(--pi-accent-border); border-inline-start-color: var(--pi-accent); background: color-mix(in srgb, var(--pi-accent) 14%, var(--pi-surface)); }
|
|
474
480
|
.subagent-row.status-idle, .subagent-row.status-done { border-inline-start-color: var(--pi-success); background: color-mix(in srgb, var(--pi-success) 7%, var(--pi-surface)); }
|
|
475
481
|
.subagent-row.status-error, .subagent-row.status-failed { border-inline-start-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 8%, var(--pi-surface)); }
|
|
@@ -592,6 +598,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
|
|
|
592
598
|
/* The one dock state that is a control, so it opts back into pointer events
|
|
593
599
|
and carries an affordance. */
|
|
594
600
|
.activity-dock.background { right: auto; max-width: min(70%, 300px); border-color: var(--pi-purple-border); color: var(--pi-purple); padding: var(--pi-space-2) var(--pi-space-5); font: inherit; font-size: var(--pi-text-xs); pointer-events: auto; cursor: pointer; -webkit-tap-highlight-color: transparent; }
|
|
601
|
+
.activity-dock { transition: color var(--pi-motion-base) var(--pi-ease), background-color var(--pi-motion-base) var(--pi-ease), border-color var(--pi-motion-base) var(--pi-ease); }
|
|
595
602
|
.activity-dock.background:hover, .activity-dock.background:focus-visible { border-color: var(--pi-purple); background: var(--pi-purple-surface); }
|
|
596
603
|
@media (pointer: coarse) { .activity-dock.background { min-height: 44px; padding-block: var(--pi-space-4); } }
|
|
597
604
|
.activity-dock.background:focus-visible { outline: var(--pi-focus-ring-width) solid var(--pi-accent); outline-offset: 2px; }
|
|
@@ -1079,7 +1086,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1079
1086
|
.viewer-header { align-items: flex-start; flex-direction: column; }
|
|
1080
1087
|
.viewer-actions { width: 100%; flex-wrap: wrap; }
|
|
1081
1088
|
}
|
|
1082
|
-
`]}};H([b({attribute:!1})],dv.prototype,`machineId`,void 0),H([b({attribute:!1})],dv.prototype,`projectId`,void 0),H([b({attribute:!1})],dv.prototype,`workspaceId`,void 0),H([b({attribute:!1})],dv.prototype,`selectedPath`,void 0),H([b({attribute:!1})],dv.prototype,`file`,void 0),H([b({attribute:!1})],dv.prototype,`loadError`,void 0),H([b({attribute:!1})],dv.prototype,`previewUrlBuilder`,void 0),H([b({attribute:!1})],dv.prototype,`modeStore`,void 0),dv=H([y(`workspace-file-viewer`)],dv);function fv(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 pv(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function mv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function hv(e){return e===`html`?``:void 0}function gv(e){return e===`image`||e===`html`||e===`pdf`}function _v(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${bh(e.size)}${e.truncated?` · truncated`:``}`}function vv(){uv(()=>import(`./CodeViewer-
|
|
1089
|
+
`]}};H([b({attribute:!1})],dv.prototype,`machineId`,void 0),H([b({attribute:!1})],dv.prototype,`projectId`,void 0),H([b({attribute:!1})],dv.prototype,`workspaceId`,void 0),H([b({attribute:!1})],dv.prototype,`selectedPath`,void 0),H([b({attribute:!1})],dv.prototype,`file`,void 0),H([b({attribute:!1})],dv.prototype,`loadError`,void 0),H([b({attribute:!1})],dv.prototype,`previewUrlBuilder`,void 0),H([b({attribute:!1})],dv.prototype,`modeStore`,void 0),dv=H([y(`workspace-file-viewer`)],dv);function fv(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 pv(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function mv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function hv(e){return e===`html`?``:void 0}function gv(e){return e===`image`||e===`html`||e===`pdf`}function _v(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${bh(e.size)}${e.truncated?` · truncated`:``}`}function vv(){uv(()=>import(`./CodeViewer-Bbc754po.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var yv=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=Tv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{Ev(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{Ev(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{Ev(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!Ev(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=Tv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&Cv(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&&wv(t)!==wv(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`
|
|
1083
1090
|
<section
|
|
1084
1091
|
class=${this.dragActive?`files-panel dragging`:`files-panel`}
|
|
1085
1092
|
@dragenter=${this.handleDragEnter}
|
|
@@ -1249,7 +1256,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1249
1256
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1250
1257
|
.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; }
|
|
1251
1258
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1252
|
-
`]}};H([b({attribute:!1})],yv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],yv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],yv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],yv.prototype,`uploadDialog`,void 0),H([x()],yv.prototype,`pendingUpload`,void 0),H([x()],yv.prototype,`destinationFolder`,void 0),H([x()],yv.prototype,`overwrite`,void 0),H([x()],yv.prototype,`createDirs`,void 0),H([x()],yv.prototype,`formError`,void 0),H([x()],yv.prototype,`dragActive`,void 0),yv=H([y(`workspace-files-panel`)],yv);function bv(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 xv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{vs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Sv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Cv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function wv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Tv(e){return e==null?[]:Array.from(e)}function Ev(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Dv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Ov(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function kv(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 Av(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Pv(e.percent)}}function jv(e){return e.status===`uploading`?e.percent:1}function Mv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Pv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Nv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${bh(e.loaded)} / ${bh(e.total)}`:`Wrote ${e.response.path}`:e.error}function Pv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Fv(){return[{id:`workspace.files`,title:`Files`,icon:vh(`files`),order:10,routeAliases:[`files`],render:Iv},{id:`workspace.terminal`,title:`Terminal`,icon:vh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Lv}]}function Iv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Lv(e){return Rv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Rv(){uv(()=>import(`./TerminalPanel-CCTQ5gix.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var zv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:uh(),workspacePanels:Fv()}})},Bv={"--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`},Vv={"--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`},Hv={"--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`},Uv={"--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`},Wv={"--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`},Gv={"--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`},Kv={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:Vv},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:Hv},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Bv},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:Uv},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:Wv},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:Gv}],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 qv(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await Xv(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=Jv(e.module,n),a=ty(await(t.moduleLoader??Yv)(r),r);i.push({id:t.machineId===void 0?e.id:zs(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 Jv(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function Yv(e){return uv(()=>import(e),[],import.meta.url)}async function Xv(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await Qv(t));return Zv(await t.json())}}function Zv(e){if(!ry(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!ry(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!Yt(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Xt(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...$v(e.backendRevision),machineSpecific:ey(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 Qv(e){let t;try{let n=await e.json();if(ry(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 $v(e){if(e===void 0)return{};try{return{backendRevision:Jo(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function ey(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ty(e,t){if(!ry(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(ry(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!ny(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ny(e){return ry(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function ry(e){return typeof e==`object`&&!!e}var iy=/^[a-z][a-z0-9.-]*$/u,ay=/^[a-z][a-z0-9.-]*$/u,oy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,sy=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,cy=new WeakMap,ly=new WeakMap,uy=new WeakMap,dy=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&&yy(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=Sy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=fy(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=vy(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?.(py(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(py(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(py(t,u)):void 0},render:e=>t.render(py(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=vy(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?.(my(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(my(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=>!by(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(by)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!sy.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!iy.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!ay.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return Jo(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}: ${xy(t)}`);return t}};function fy(e,t){return cy.get(e)?.(t)??e}function py(e,t){return ly.get(e)?.(t)??e}function my(e,t){return uy.get(e)?.(t)??e}function hy(e,t){return cy.set(e,t),e}function gy(e,t){return ly.set(e,t),e}function _y(e,t){return uy.set(e,t),e}function vy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function yy(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function by(e){return oy.test(e)}function xy(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 Sy(e){return e.state.selectedMachine?.id??`local`}function Cy(e,t,n,r=rs){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 wy(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 Ty=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function Ey(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ty.map(e=>window.matchMedia(e))}function Dy(e,t=Oy()){return e.some(e=>e.matches)||ky(t)}function Oy(){return typeof navigator>`u`?void 0:navigator}function ky(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Ay=class{constructor(e=jy()){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 jy(){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)`,Ny=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=Dy(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Py(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??Ey(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Ay,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Dy(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(e={}){return Fy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function Py(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(My)}function Fy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Iy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new mc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Ly(),this.documentTarget=t.documentTarget??Ry(),this.isDocumentVisible=t.isDocumentVisible??zy,this.scheduleFrame=t.scheduleFrame??By}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 Ly(){return typeof window>`u`?void 0:window}function Ry(){return typeof document>`u`?void 0:document}function zy(){return typeof document>`u`||document.visibilityState===`visible`}function By(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 Vy=[`machines`,`projects`,`workspaces`,`sessions`];function Hy(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function Uy(e,t){if(e!==`none`)return e??Hy(t)}function Wy(e,t){return Uy(t.expanded,t.state)!==e}function Gy(e,t,n){return Uy(e,n.state)===t?`none`:t}function Ky(e){return e.workspaceCount===1?`sessions`:`workspaces`}function qy(e){return Vy[Vy.indexOf(e)+1]}var Jy=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return Uy(this.expanded,this.getState())}isCollapsed(e){return Wy(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(Gy(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?Ky({workspaceCount:t?.workspaceCount}):qy(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())}},Yy=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`,Zy(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...Xy(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function Xy(e,t){return!e&&t}function Zy(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Qy=`pi-web:panel-sizes:v1`,$y={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},eb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??mb(),this.panelSizes=ob(this.storage)}hostConnected(){}constraints(e){return tb(e)}panelWidth(e,t){return ab(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=ab(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=ub(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=db(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(){sb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${pb(ab(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${pb(ab(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function tb(e){return $y[e]}function nb(e,t,n){return e===`navigation`?n-t:t-n}function rb(e,t,n,r,i=tb(e)){return ab(e,t+nb(e,n,r),i)}function ib(e,t,n,r={}){let i=r.constraints??tb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=fb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return ab(e,t+a,i)}function ab(e,t,n=tb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ob(e=mb()){try{let t=e?.getItem(Qy);return t==null||t===``?{}:cb(JSON.parse(t))}catch{return{}}}function sb(e,t=mb()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Qy);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=ab(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=ab(`workspace`,e.workspacePanelWidth)),t.setItem(Qy,JSON.stringify(n))}catch{}}function cb(e){if(!hb(e)||e.version!==1)return{};let t={},n=lb(e.navigationPanelWidth),r=lb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=ab(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=ab(`workspace`,r)),t}function lb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ub(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function db(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function fb(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 pb(e){return`${String(Math.round(e))}px`}function mb(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function hb(e){return typeof e==`object`&&!!e}function gb(){let e=new URLSearchParams(window.location.search);return{machineId:bb(e.get(`machine`)),projectId:bb(e.get(`project`)),workspaceId:bb(e.get(`workspace`)),sessionId:bb(e.get(`session`)),tool:bb(e.get(`tool`)),view:bb(e.get(`view`))}}function _b(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:vb(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:vb(e.view,t)}}function vb(e,t){return t(e)??(xb(e)?e:void 0)}function yb(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 bb(e){return e===null||e===``?void 0:e}function xb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Sb(){return wb(new URLSearchParams(window.location.search).get(`settings`))}function Cb(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 wb(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 Tb(e,t){return t===void 0?e:e.map(e=>Db(e,t))}function Eb(e,t){let n=new Set(Mp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Tb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Ob(e):e)}function Db(e,t){let n=zp(e,t);return n===void 0?e:n===null?Ob(e):{...e,shortcut:n}}function Ob(e){let t={...e};return delete t.shortcut,t}function kb(e,t){let n=t.api??Oo,r=t.pollIntervalMs??1e3,i=t.setTimeout??Mb(),a=t.clearTimeout??Nb();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:Ab(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ab(e,t,n,r,i){return jb(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&&jb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function jb(e){return e.status===`succeeded`||e.status===`failed`}function Mb(){return(e,t)=>globalThis.setTimeout(e,t)}function Nb(){return e=>{globalThis.clearTimeout(e)}}var Pb=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}},Fb=class{constructor(e){this.open=e,this.longPress=new Pb({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)}},Ib=0,Lb=120;function Rb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Bb():zb(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-Ib,f=n.top-c-Ib;return[...d<Lb&&f>d?[`bottom: ${Vb(a-n.top+Ib)};`,`max-height: ${Vb(Math.max(0,f))};`]:[`top: ${Vb(n.bottom+Ib)};`,`max-height: ${Vb(Math.max(0,d))};`],`right: ${Vb(Math.max(0,i-u))};`,`max-width: ${Vb(Math.max(0,u-o))};`].join(` `)}function zb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Bb()}function Bb(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Vb(e){return`${String(Math.round(e))}px`}function Hb(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 Ub(e){if(e!==void 0)return e[Pt.working]===!0?`session`:e[Pt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==Pt.unread)?`session`:void 0}function Wb(e){return e?.[Pt.unread]===!0}var Gb={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function Kb(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`:Gb[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 qb(e,t=`Active`,n){let r=Hb(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var Jb=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Yb(e){return e.composedPath().some(e=>Xb(e,Jb))}function Xb(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 Zb(e,t){return Yb(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?$b(e,()=>{ex(e.currentTarget,-1)}):e.key===`ArrowDown`?$b(e,()=>{ex(e.currentTarget,1)}):e.key===`Home`?$b(e,()=>{tx(e.currentTarget,0)}):e.key===`End`?$b(e,()=>{tx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?$b(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?$b(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&$b(e,t.cancel)}function Qb(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 $b(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function ex(e,t){let n=rx(e),r=ax(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||nx(n,i+t)}function tx(e,t){let n=rx(e);n.length!==0&&nx(n,t<0?n.length-1:t)}function nx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function rx(e){let t=ax(e)?.getRootNode();return t===void 0||!ix(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function ix(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function ax(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new Fb((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,Qb(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1259
|
+
`]}};H([b({attribute:!1})],yv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],yv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],yv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],yv.prototype,`uploadDialog`,void 0),H([x()],yv.prototype,`pendingUpload`,void 0),H([x()],yv.prototype,`destinationFolder`,void 0),H([x()],yv.prototype,`overwrite`,void 0),H([x()],yv.prototype,`createDirs`,void 0),H([x()],yv.prototype,`formError`,void 0),H([x()],yv.prototype,`dragActive`,void 0),yv=H([y(`workspace-files-panel`)],yv);function bv(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 xv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{vs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Sv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Cv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function wv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Tv(e){return e==null?[]:Array.from(e)}function Ev(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Dv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Ov(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function kv(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 Av(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Pv(e.percent)}}function jv(e){return e.status===`uploading`?e.percent:1}function Mv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Pv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Nv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${bh(e.loaded)} / ${bh(e.total)}`:`Wrote ${e.response.path}`:e.error}function Pv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Fv(){return[{id:`workspace.files`,title:`Files`,icon:vh(`files`),order:10,routeAliases:[`files`],render:Iv},{id:`workspace.terminal`,title:`Terminal`,icon:vh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Lv}]}function Iv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Lv(e){return Rv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Rv(){uv(()=>import(`./TerminalPanel-C03ZVP61.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var zv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:uh(),workspacePanels:Fv()}})},Bv={"--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`},Vv={"--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`},Hv={"--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`},Uv={"--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`},Wv={"--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`},Gv={"--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`},Kv={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:Vv},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:Hv},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Bv},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:Uv},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:Wv},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:Gv}],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 qv(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await Xv(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=Jv(e.module,n),a=ty(await(t.moduleLoader??Yv)(r),r);i.push({id:t.machineId===void 0?e.id:zs(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 Jv(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function Yv(e){return uv(()=>import(e),[],import.meta.url)}async function Xv(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await Qv(t));return Zv(await t.json())}}function Zv(e){if(!ry(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!ry(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!Yt(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Xt(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...$v(e.backendRevision),machineSpecific:ey(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 Qv(e){let t;try{let n=await e.json();if(ry(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 $v(e){if(e===void 0)return{};try{return{backendRevision:Jo(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function ey(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ty(e,t){if(!ry(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(ry(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!ny(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ny(e){return ry(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function ry(e){return typeof e==`object`&&!!e}var iy=/^[a-z][a-z0-9.-]*$/u,ay=/^[a-z][a-z0-9.-]*$/u,oy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,sy=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,cy=new WeakMap,ly=new WeakMap,uy=new WeakMap,dy=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&&yy(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=Sy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=fy(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=vy(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?.(py(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(py(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(py(t,u)):void 0},render:e=>t.render(py(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=vy(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?.(my(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(my(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=>!by(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(by)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!sy.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!iy.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!ay.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return Jo(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}: ${xy(t)}`);return t}};function fy(e,t){return cy.get(e)?.(t)??e}function py(e,t){return ly.get(e)?.(t)??e}function my(e,t){return uy.get(e)?.(t)??e}function hy(e,t){return cy.set(e,t),e}function gy(e,t){return ly.set(e,t),e}function _y(e,t){return uy.set(e,t),e}function vy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function yy(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function by(e){return oy.test(e)}function xy(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 Sy(e){return e.state.selectedMachine?.id??`local`}function Cy(e,t,n,r=rs){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 wy(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 Ty=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function Ey(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ty.map(e=>window.matchMedia(e))}function Dy(e,t=Oy()){return e.some(e=>e.matches)||ky(t)}function Oy(){return typeof navigator>`u`?void 0:navigator}function ky(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Ay=class{constructor(e=jy()){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 jy(){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)`,Ny=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=Dy(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Py(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??Ey(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Ay,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Dy(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(e={}){return Fy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function Py(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(My)}function Fy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Iy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new mc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Ly(),this.documentTarget=t.documentTarget??Ry(),this.isDocumentVisible=t.isDocumentVisible??zy,this.scheduleFrame=t.scheduleFrame??By}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 Ly(){return typeof window>`u`?void 0:window}function Ry(){return typeof document>`u`?void 0:document}function zy(){return typeof document>`u`||document.visibilityState===`visible`}function By(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 Vy=[`machines`,`projects`,`workspaces`,`sessions`];function Hy(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function Uy(e,t){if(e!==`none`)return e??Hy(t)}function Wy(e,t){return Uy(t.expanded,t.state)!==e}function Gy(e,t,n){return Uy(e,n.state)===t?`none`:t}function Ky(e){return e.workspaceCount===1?`sessions`:`workspaces`}function qy(e){return Vy[Vy.indexOf(e)+1]}var Jy=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return Uy(this.expanded,this.getState())}isCollapsed(e){return Wy(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(Gy(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?Ky({workspaceCount:t?.workspaceCount}):qy(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())}},Yy=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`,Zy(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...Xy(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function Xy(e,t){return!e&&t}function Zy(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Qy=`pi-web:panel-sizes:v1`,$y={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},eb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??mb(),this.panelSizes=ob(this.storage)}hostConnected(){}constraints(e){return tb(e)}panelWidth(e,t){return ab(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=ab(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=ub(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=db(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(){sb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${pb(ab(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${pb(ab(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function tb(e){return $y[e]}function nb(e,t,n){return e===`navigation`?n-t:t-n}function rb(e,t,n,r,i=tb(e)){return ab(e,t+nb(e,n,r),i)}function ib(e,t,n,r={}){let i=r.constraints??tb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=fb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return ab(e,t+a,i)}function ab(e,t,n=tb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ob(e=mb()){try{let t=e?.getItem(Qy);return t==null||t===``?{}:cb(JSON.parse(t))}catch{return{}}}function sb(e,t=mb()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Qy);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=ab(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=ab(`workspace`,e.workspacePanelWidth)),t.setItem(Qy,JSON.stringify(n))}catch{}}function cb(e){if(!hb(e)||e.version!==1)return{};let t={},n=lb(e.navigationPanelWidth),r=lb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=ab(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=ab(`workspace`,r)),t}function lb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ub(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function db(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function fb(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 pb(e){return`${String(Math.round(e))}px`}function mb(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function hb(e){return typeof e==`object`&&!!e}function gb(){let e=new URLSearchParams(window.location.search);return{machineId:bb(e.get(`machine`)),projectId:bb(e.get(`project`)),workspaceId:bb(e.get(`workspace`)),sessionId:bb(e.get(`session`)),tool:bb(e.get(`tool`)),view:bb(e.get(`view`))}}function _b(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:vb(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:vb(e.view,t)}}function vb(e,t){return t(e)??(xb(e)?e:void 0)}function yb(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 bb(e){return e===null||e===``?void 0:e}function xb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Sb(){return wb(new URLSearchParams(window.location.search).get(`settings`))}function Cb(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 wb(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 Tb(e,t){return t===void 0?e:e.map(e=>Db(e,t))}function Eb(e,t){let n=new Set(Mp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Tb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Ob(e):e)}function Db(e,t){let n=zp(e,t);return n===void 0?e:n===null?Ob(e):{...e,shortcut:n}}function Ob(e){let t={...e};return delete t.shortcut,t}function kb(e,t){let n=t.api??Oo,r=t.pollIntervalMs??1e3,i=t.setTimeout??Mb(),a=t.clearTimeout??Nb();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:Ab(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ab(e,t,n,r,i){return jb(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&&jb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function jb(e){return e.status===`succeeded`||e.status===`failed`}function Mb(){return(e,t)=>globalThis.setTimeout(e,t)}function Nb(){return e=>{globalThis.clearTimeout(e)}}var Pb=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}},Fb=class{constructor(e){this.open=e,this.longPress=new Pb({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)}},Ib=0,Lb=120;function Rb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Bb():zb(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-Ib,f=n.top-c-Ib;return[...d<Lb&&f>d?[`bottom: ${Vb(a-n.top+Ib)};`,`max-height: ${Vb(Math.max(0,f))};`]:[`top: ${Vb(n.bottom+Ib)};`,`max-height: ${Vb(Math.max(0,d))};`],`right: ${Vb(Math.max(0,i-u))};`,`max-width: ${Vb(Math.max(0,u-o))};`].join(` `)}function zb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Bb()}function Bb(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Vb(e){return`${String(Math.round(e))}px`}function Hb(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 Ub(e){if(e!==void 0)return e[Pt.working]===!0?`session`:e[Pt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==Pt.unread)?`session`:void 0}function Wb(e){return e?.[Pt.unread]===!0}var Gb={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function Kb(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`:Gb[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 qb(e,t=`Active`,n){let r=Hb(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var Jb=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Yb(e){return e.composedPath().some(e=>Xb(e,Jb))}function Xb(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 Zb(e,t){return Yb(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?$b(e,()=>{ex(e.currentTarget,-1)}):e.key===`ArrowDown`?$b(e,()=>{ex(e.currentTarget,1)}):e.key===`Home`?$b(e,()=>{tx(e.currentTarget,0)}):e.key===`End`?$b(e,()=>{tx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?$b(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?$b(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&$b(e,t.cancel)}function Qb(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 $b(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function ex(e,t){let n=rx(e),r=ax(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||nx(n,i+t)}function tx(e,t){let n=rx(e);n.length!==0&&nx(n,t<0?n.length-1:t)}function nx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function rx(e){let t=ax(e)?.getRootNode();return t===void 0||!ix(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function ix(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function ax(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new Fb((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,Qb(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1253
1260
|
<section>
|
|
1254
1261
|
<h2>${this.renderHeading()}${this.renderAdd()}</h2>
|
|
1255
1262
|
${this.collapsed?null:g`
|
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-DtVZ1Hqm.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