@hyperdreamer/pi-webui 1.10.1 → 1.10.2
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-C7lZj4kb.js → CodeViewer-BdULrLxb.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-BZtpu-dj.js → UnifiedDiffViewer-DDlEJGJ4.js} +1 -1
- package/dist/client/assets/{index-DlHF43Ql.js → index-Bq-PmNe2.js} +6 -6
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as e,J as t,P as n,S as r,Y as i,l as a,q as o,y as s}from"./vendor-editor-core-vUi74DnD.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-DoaXUodB.js";import{a as g,i as _,n as v,o as y,r as b,s as x,t as S}from"./index-
|
|
1
|
+
import{$ as e,J as t,P as n,S as r,Y as i,l as a,q as o,y as s}from"./vendor-editor-core-vUi74DnD.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-DoaXUodB.js";import{a as g,i as _,n as v,o as y,r as b,s as x,t as S}from"./index-Bq-PmNe2.js";import{t as C}from"./vendor-editor-legacy-CYBnW6ZU.js";var w=class extends g{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 y`<div class="host"></div>`}recreateEditor(){this.editorHost&&(this.view?.destroy(),this.view=new o({parent:this.editorHost,state:e.create({doc:this.content,extensions:[i(),t.of(a),n(r,{fallback:!0}),e.readOnly.of(!0),o.editable.of(!1),o.lineWrapping,T,...D(this.language),...O(this.language)]})}))}static{this.styles=x`
|
|
2
2
|
:host { display: block; min-height: 0; height: 100%; }
|
|
3
3
|
.host { height: 100%; min-height: 0; overflow: auto; }
|
|
4
4
|
`}};S([b()],w.prototype,`content`,void 0),S([b()],w.prototype,`language`,void 0),S([v(`.host`)],w.prototype,`editorHost`,void 0),w=S([_(`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{a as e,i as t,o as n,r,s as i,t as a}from"./index-
|
|
1
|
+
import{a as e,i as t,o as n,r,s as i,t as a}from"./index-Bq-PmNe2.js";var o=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},s=new class extends o{};function c(e,t,n){return s.diff(e,t,n)}function l(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function u(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function d(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function f(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function p(e,t){return d(e,t,``)}function m(e,t){return f(e,t,``)}function h(e,t){return t.slice(0,g(e,t))}function g(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function _(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function v(e,t){if(t)return b(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function y(e,t){if(t)return b(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function b(e,t){if(!t)return[y(e),v(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=_(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var x=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,S=RegExp(`[${x}]+|\\s+|[^${x}]`,`ug`);new class extends o{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=_(e,r)}else n=e.match(S)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&C(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&C(n,i,r,null,t.intlSegmenter),e}};function C(e,t,n,r,i){if(t&&n){let[a,o]=b(t.value,i),[s,c]=b(n.value,i);if(e){let r=l(a,s);e.value=f(e.value,s,r),t.value=p(t.value,r),n.value=p(n.value,r)}if(r){let e=u(o,c);r.value=d(r.value,c,e),t.value=m(t.value,e),n.value=m(n.value,e)}}else if(n){if(e){let e=y(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=y(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=y(r.value,i),[a,o]=b(t.value,i),s=l(n,a);t.value=p(t.value,s);let c=u(p(n,s),o);t.value=m(t.value,c),r.value=d(r.value,n,c),e.value=f(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=y(r.value,i),n=h(v(t.value,i),e);t.value=m(t.value,n)}else if(e){let n=h(v(e.value,i),y(t.value,i));t.value=p(t.value,n)}}new class extends o{tokenize(e){let t=RegExp(`(\\r?\\n)|[${x}]+|[^\\S\\n\\r]+|[^${x}]`,`ug`);return e.match(t)||[]}},new class extends o{constructor(){super(...arguments),this.tokenize=w}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
2
2
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
3
3
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
4
4
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BdULrLxb.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";import{n as re,t as ie}from"./vendor-terminal-D8k4UKM2.js";var ae=Object.defineProperty,oe=(e,t)=>{let n={};for(var r in e)ae(n,r,{get:e[r],enumerable:!0});return t||ae(n,Symbol.toStringTag,{value:`Module`}),n};(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 se=globalThis,ce=se.ShadowRoot&&(se.ShadyCSS===void 0||se.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,le=Symbol(),ue=new WeakMap,de=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==le)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(ce&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=ue.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ue.set(t,e))}return e}toString(){return this.cssText}},fe=e=>new de(typeof e==`string`?e:e+``,void 0,le),h=(e,...t)=>new de(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,le),pe=(e,t)=>{if(ce)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=se.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},me=ce?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return fe(t)})(e):e,{is:he,defineProperty:ge,getOwnPropertyDescriptor:_e,getOwnPropertyNames:ve,getOwnPropertySymbols:ye,getPrototypeOf:be}=Object,xe=globalThis,Se=xe.trustedTypes,Ce=Se?Se.emptyScript:``,we=xe.reactiveElementPolyfillSupport,Te=(e,t)=>e,Ee={toAttribute(e,t){switch(t){case Boolean:e=e?Ce: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}},De=(e,t)=>!he(e,t),Oe={attribute:!0,type:String,converter:Ee,reflect:!1,useDefault:!1,hasChanged:De};Symbol.metadata??=Symbol(`metadata`),xe.litPropertyMetadata??=new WeakMap;var ke=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=Oe){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&&ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=_e(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)??Oe}static _$Ei(){if(this.hasOwnProperty(Te(`elementProperties`)))return;let e=be(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Te(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Te(`properties`))){let e=this.properties,t=[...ve(e),...ye(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(me(e))}else e!==void 0&&t.push(me(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 pe(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?Ee: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?Ee: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??De)(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){}};ke.elementStyles=[],ke.shadowRootOptions={mode:`open`},ke[Te(`elementProperties`)]=new Map,ke[Te(`finalized`)]=new Map,we?.({ReactiveElement:ke}),(xe.reactiveElementVersions??=[]).push(`2.1.2`);var Ae=globalThis,je=e=>e,Me=Ae.trustedTypes,Ne=Me?Me.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,Fe=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie=`?`+Fe,Le=`<${Ie}>`,Re=document,ze=()=>Re.createComment(``),Be=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ve=Array.isArray,He=e=>Ve(e)||typeof e?.[Symbol.iterator]==`function`,Ue=`[
|
|
3
3
|
\f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ge=/-->/g,Ke=/>/g,qe=RegExp(`>|${Ue}(?:([^\\s"'>=/]+)(${Ue}*=${Ue}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Je=/'/g,Ye=/"/g,Xe=/^(?:script|style|textarea|title)$/i,Ze=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Ze(1),_=Ze(2),Qe=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),$e=new WeakMap,et=Re.createTreeWalker(Re,129);function tt(e,t){if(!Ve(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var nt=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=We;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===We?c[1]===`!--`?o=Ge:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=qe):(Xe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=qe):o=Ke:o===qe?c[0]===`>`?(o=i??We,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?qe:c[3]===`"`?Ye:Je):o===Ye||o===Je?o=qe:o===Ge||o===Ke?o=We:(o=qe,i=void 0);let d=o===qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===We?n+Le:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+Fe+d):n+Fe+(l===-2?t:d)}return[tt(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},rt=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]=nt(t,n);if(this.el=e.createElement(l,r),et.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=et.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(Fe),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ct:r[1]===`?`?lt:r[1]===`@`?ut:st}),i.removeAttribute(e)}else e.startsWith(Fe)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Xe.test(i.tagName)){let e=i.textContent.split(Fe),t=e.length-1;if(t>0){i.textContent=Me?Me.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],ze()),et.nextNode(),c.push({type:2,index:++a});i.append(e[t],ze())}}}else if(i.nodeType===8)if(i.data===Ie)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Fe,e+1))!==-1;)c.push({type:7,index:a}),e+=Fe.length-1}a++}}static createElement(e,t){let n=Re.createElement(`template`);return n.innerHTML=e,n}};function it(e,t,n=e,r){if(t===Qe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Be(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=it(e,i._$AS(e,t.values),i,r)),t}var at=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??Re).importNode(t,!0);et.currentNode=r;let i=et.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ot(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new dt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=et.nextNode(),a++)}return et.currentNode=Re,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++}},ot=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,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=it(this,e,t),Be(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Qe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?He(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!==v&&Be(this._$AH)?this._$AA.nextSibling.data=e:this.T(Re.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=rt.createElement(tt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new at(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=$e.get(e.strings);return t===void 0&&$e.set(e.strings,t=new rt(e)),t}k(t){Ve(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(ze()),this.O(ze()),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=je(e).nextSibling;je(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},st=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,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=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=it(this,e,t,0),a=!Be(e)||e!==this._$AH&&e!==Qe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=it(this,r[n+o],t,o),s===Qe&&(s=this._$AH[o]),a||=!Be(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ct=class extends st{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},lt=class extends st{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ut=class extends st{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=it(this,e,t,0)??v)===Qe)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||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)}},dt=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){it(this,e)}},ft={M:Pe,P:Fe,A:Ie,C:1,L:nt,R:at,D:He,V:it,I:ot,H:st,N:lt,U:ut,B:ct,F:dt},pt=Ae.litHtmlPolyfillSupport;pt?.(rt,ot),(Ae.litHtmlVersions??=[]).push(`3.3.3`);var mt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ot(t.insertBefore(ze(),e),e,void 0,n??{})}return i._$AI(e),i},ht=globalThis,y=class extends ke{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=mt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qe}};y._$litElement$=!0,y.finalized=!0,ht.litElementHydrateSupport?.({LitElement:y});var gt=ht.litElementPolyfillSupport;gt?.({LitElement:y}),(ht.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},_t={attribute:!0,type:String,converter:Ee,reflect:!1,hasChanged:De},vt=(e=_t,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 x(e){return(t,n)=>typeof n==`object`?vt(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 S(e){return x({...e,state:!0,attribute:!1})}var yt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(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 yt(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 yt(n,r,{get(){return a(this)}})}}function bt(e,t=St()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(Ct(e),n).toString()}function xt(e,t=St()){let n=new URL(bt(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 St(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function Ct(e){return e.startsWith(`/`)?`.${e}`:e}async function w(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(bt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(wt(e)??i.statusText)}return t(await i.json())}function wt(e){if(Tt(e))return typeof e.error==`string`?e.error:void 0}function Tt(e){return typeof e==`object`&&!!e}var T={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`},Et=1e3,Dt=32*1024,Ot=8*1024,kt=1e4;function At(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function jt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&At(e)}var Mt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Nt=/^sha256:[0-9a-f]{64}$/u,Pt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Ft=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function It(e){if(!Vt(e)||Object.keys(e).some(e=>!Mt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Nt.test(n))&&!(typeof r!=`string`||!Lt(r))&&!(typeof i!=`string`||!Rt(i))&&Bt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!Ft.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Lt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Rt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Pt.test(e)}function Rt(e){if(e===``||e!==e.trim()||zt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Bt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ht=Object.values(T),Ut=new Set(Ht);T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig;function Wt(e){return typeof e==`string`&&Ut.has(e)}function Gt(e,t){return e?.capabilities?.includes(t)===!0}function Kt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Wt)}function qt(e){return typeof e==`object`&&!!e}function E(e){if(!qt(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Jt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Yt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Xt(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:Jt(t.messages),start:k(t,`start`),total:k(t,`total`)}}function Zt(e){let t=E(e);return j(Qt)(t.machines)}function Qt(e){let t=E(e),n=tn(t,`kind`),r=O(t,`baseUrl`),i=nn(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function $t(e){let t=E(e),n=nn(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Bi(t.web)},...t.sessiond===void 0?{}:{sessiond:Bi(t.sessiond)},...r===void 0?{}:{error:r}}}function en(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...N(`packageName`,O(t,`packageName`)),...N(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:Ri(t.components)},...t.capabilities===void 0?{}:{capabilities:Ki(t.capabilities)},...n===void 0?{}:{error:n}}}function tn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function nn(e,t){let n=O(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function rn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function an(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...N(`effectiveConfig`,on(t.effectiveConfig))}}function on(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,di(e.uploads))}}}function sn(e){let t=E(e),n=O(t,`name`),r=Pi(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`archivedAt`),o=Pi(t.pinned,`pinned`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o}}}function cn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function ln(e){if(e!==void 0)return{id:D(E(e),`id`)}}function un(e){let t=E(e),n=ln(t.dismiss);return{severity:cn(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function dn(e){return e===void 0?{}:{warnings:j(un)(e)}}function fn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,Pi(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(qn)(t.queuedMessages),...N(`messageCount`,M(t,`messageCount`)),tokens:Jn(t.tokens),cost:k(t,`cost`),...Rr(t.generation),...Xn(t.model),...zr(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...dn(t.warnings)}}function pn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function mn(e){let t=O(E(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function hn(e){let t=E(e),n=Pn(t,`catalogRevision`),r=jn(t.sessions,_n,Et,`sessions`);if(vn(r),yn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:bn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function gn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=bn(t,`sessionId`,512),r=bn(t,`cwd`,Dt),i=xn(t,`catalogRevision`),a=t.unread===null?null:_n(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:bn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function _n(e){let t=E(e),n=bn(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:bn(t,`sessionId`,512),cwd:bn(t,`cwd`,Dt),completionOrder:xn(t,`completionOrder`),completedAt:n}}function vn(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 yn(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 bn(e,t,n){let r=Nn(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function xn(e,t){let n=Pn(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Sn(e){let t=E(e),n=wn(t.summary),r=jn(t.notifications,Tn,100,`notifications`);if(Fn(r),In(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Rn(r))throw Error(`Notification snapshot severity mismatch`);let i=En(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:Nn(t,`daemonInstanceId`),catalogRevision:Pn(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Cn(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=wn(t.summary),r=En(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Dn(t.delta);if(i.kind===`cleared`&&!Ln(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:Nn(t,`daemonInstanceId`),catalogRevision:Pn(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function wn(e){let t=E(e),n=Pn(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Pn(t,`discardedCount`),i=kn(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:Nn(t,`sessionId`),cwd:Nn(t,`cwd`),inboxRevision:Pn(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Tn(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Pn(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:Nn(t,`id`),message:n,truncated:A(t,`truncated`),severity:On(t.severity),receivedAt:r,order:i}}function En(e){let t=E(e);return{order:Pn(t,`order`),overflowWatermark:Pn(t,`overflowWatermark`)}}function Dn(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:Tn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=jn(t.notificationIds,Mn,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:An(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function On(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function kn(e){return e===void 0?void 0:On(e)}function An(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 jn(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 Mn(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function Nn(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Pn(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 Fn(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 In(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 Ln(e){return e.retainedCount===0&&e.discardedCount===0}function Rn(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function zn(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:Yt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Wn(t.thresholds),projects:j(Gn)(t.projects),totals:Kn(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Bn(e){let t=E(e);return{...zn(t),archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`)}}function Vn(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),failures:j(Un)(t.failures),generatedAt:D(t,`generatedAt`)}}function Hn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`),failures:j(Un)(t.failures),generatedAt:D(t,`generatedAt`)}}function Un(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Wn(e){let t=E(e);return{...N(`archiveIdleDays`,M(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,M(t,`deleteArchivedDays`))}}function Gn(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Kn(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function qn(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function Jn(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function Yn(e){let t=E(e);return{...N(`provider`,O(t,`provider`)),...N(`id`,O(t,`id`)),...N(`name`,O(t,`name`)),...N(`contextWindow`,M(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function Xn(e){return e===void 0?{}:{model:Yn(e)}}function Zn(e){let t=E(e);return{models:j(Yn)(t.models)}}function Qn(e){let t=E(e);return{...t.model===void 0?{}:{model:Yn(t.model)},thinkingLevel:D(t,`thinkingLevel`),models:j(Yn)(t.models),thinkingLevels:Yt(t.thinkingLevels,`thinkingLevels`)}}function $n(e){let t=nr(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=nr(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=er(t);return{...t,providers:i}}function er(e){let t=nr(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=O(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=O(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=rr(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=ir(o,`models configuration provider headers`));let s=rr(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=rr(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(tr)}return n}function tr(e){let t=nr(e,`models configuration model`),n={id:D(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=D(t,`id`);let r=O(t,`name`);r!==void 0&&(n.name=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=_a(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=rr(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=ar(o));let s=t.input;if(s!==void 0){if(!Array.isArray(s)||!s.every(e=>typeof e==`string`))throw Error(`Expected models configuration model input array of strings`);n.input=[...s]}let c=M(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=M(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=rr(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=or(u));let d=rr(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function nr(e,t){if(!qt(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function rr(e,t){if(e!==void 0)return nr(e,t)}function ir(e,t){let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)throw Error(`Expected ${t} values to be strings`);n[r]=i}return n}function ar(e){let t={};for(let[n,r]of Object.entries(e)){if(r!==null&&typeof r!=`string`)throw Error(`Expected models configuration thinking level map values to be strings or null`);t[n]=r}return t}function or(e){let t={};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`]){let r=e[n];if(r!==void 0){if(typeof r!=`number`)throw Error(`Expected models configuration model cost ${n} to be a number`);t[n]=r}}return t}function sr(e){if(E(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function cr(e){let t=E(e);return{models:j(lr)(t.models)}}function lr(e){let t=E(e),n=D(t,`id`),r=O(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function ur(e){let t=E(e),n=A(t,`ok`),r=O(t,`error`),i=t.latencyMs===void 0?void 0:k(t,`latencyMs`),a=t.status===void 0?void 0:k(t,`status`),o=O(t,`responseText`);return{ok:n,...r===void 0?{}:{error:r},...i===void 0?{}:{latencyMs:i},...a===void 0?{}:{status:a},...o===void 0?{}:{responseText:o}}}function dr(e){let t=E(e);return{skills:j(fr)(t.skills)}}function fr(e){let t=E(e),n=E(t.sourceInfo),r=O(n,`source`),i=O(n,`scope`);return{name:D(t,`name`),description:D(t,`description`),filePath:D(t,`filePath`),baseDir:D(t,`baseDir`),disableModelInvocation:A(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:pr(t.install)}}}function pr(e){let t=E(e),n=O(t,`sourceType`),r=O(t,`skillsShUrl`),i=O(t,`skillPath`),a=O(t,`ref`),o=O(t,`versionHash`);return{package:D(t,`package`),scope:mr(t.scope),source:D(t,`source`),...n===void 0?{}:{sourceType:n},...r===void 0?{}:{skillsShUrl:r},...i===void 0?{}:{skillPath:i},...a===void 0?{}:{ref:a},...o===void 0?{}:{versionHash:o},canCheckForUpdates:A(t,`canCheckForUpdates`)}}function mr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function hr(e){if(E(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function gr(e){let t=E(e);return{results:j(_r)(t.results)}}function _r(e){let t=E(e);return{package:D(t,`package`),installs:D(t,`installs`),url:D(t,`url`)}}function vr(e){let t=E(e);return{updates:j(yr)(t.updates)}}function yr(e){let t=E(e),n=O(t,`currentVersion`),r=O(t,`latestVersion`),i=O(t,`message`);return{package:D(t,`package`),scope:mr(t.scope),state:br(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function br(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function xr(e){let t=E(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=O(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:fr(t.skill)},...n===void 0?{}:{output:n}}}function Sr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Cr(e){let t=E(e);return{levels:j(Sr)(t.levels)}}function wr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Tr(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 Er(e){let t=E(e),n=t.source===void 0?void 0:Tr(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function Dr(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:wr(t.authType),status:Er(t.status),...n===void 0?{}:{loginFlow:n}}}function Or(e){let t=E(e);return{providers:j(Dr)(t.providers)}}function kr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Ar(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,O(t,`error`)),...N(`auth`,jr(t.auth)),...N(`prompt`,Nr(t.prompt)),...N(`select`,Fr(t.select)),...N(`info`,Ir(t.info))}}function Ar(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function jr(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,Mr(t.deviceCode))}}function Mr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...N(`intervalSeconds`,M(t,`intervalSeconds`)),...N(`expiresInSeconds`,M(t,`expiresInSeconds`))}}function Nr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Pr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,_a(t,`allowEmpty`))}}function Pr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Fr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(ia)(t.options)}}function Ir(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...N(`links`,t.links===void 0?void 0:j(Lr)(t.links))}})(e)}function Lr(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function Rr(e){if(e===void 0)return{};let t=E(e);return{generation:{outputTokens:k(t,`outputTokens`),...N(`tokensPerSecond`,M(t,`tokensPerSecond`)),...N(`estimated`,_a(t,`estimated`))}}}function zr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:va(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:va(t,`percent`)}}}function Br(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...N(`description`,O(t,`description`))}}function Vr(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function Hr(e){let t=E(e);return{path:D(t,`path`),entries:j(Ur)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Ur(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...N(`size`,M(t,`size`)),...N(`modifiedAt`,O(t,`modifiedAt`))}}function Wr(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...N(`language`,O(t,`language`)),...N(`mediaType`,Jr(t.mediaType)),...N(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function Gr(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Kr(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function qr(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Jr(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Yr(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...N(`branch`,O(t,`branch`)),...N(`latestTag`,O(t,`latestTag`)),...N(`upstream`,O(t,`upstream`)),...N(`ahead`,M(t,`ahead`)),...N(`behind`,M(t,`behind`)),files:j(Xr)(t.files)}}function Xr(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:Zr(t.index),workingTree:Zr(t.workingTree)}}function Zr(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function Qr(e){let t=E(e);return{...N(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function $r(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...N(`exitCode`,M(t,`exitCode`)),...N(`commandRunId`,O(t,`commandRunId`))}}function ei(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:ti(t.status),...N(`exitCode`,M(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:ni(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 ni(e,t){let n=E(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function ri(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function ii(e){let t=E(e);return{workspaces:j(ri)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function ai(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:oi(t.config),effectiveConfig:oi(t.effectiveConfig),envOverrides:gi(t.envOverrides)}}function oi(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,M(t,`port`)),...N(`allowedHosts`,ci(t.allowedHosts)),...N(`shortcuts`,mi(t.shortcuts)),...N(`plugins`,hi(t.plugins)),...N(`pathAccess`,li(t.pathAccess)),...N(`uploads`,di(t.uploads)),...N(`maxUploadBytes`,M(t,`maxUploadBytes`)),...N(`agent`,si(t.agent)),...N(`spawnSessions`,_a(t,`spawnSessions`)),...N(`subsessions`,_a(t,`subsessions`))}}function si(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function ci(e){if(e!==void 0){if(e===!0)return!0;if(fi(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function li(e){if(e===void 0)return;if(!qt(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,ui(t,`pathAccess.allowedPaths`))}}function ui(e,t){if(e!==void 0){if(pi(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function di(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function fi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function pi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function mi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEBUI shortcut field`);return[e,t]}))}}function hi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!qt(t)||Array.isArray(t))throw Error(`Invalid PI WEBUI plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEBUI plugin enabled field`);let r=t.settings;if(r!==void 0&&(!qt(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function gi(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),agentCommand:_a(t,`agentCommand`)??!1,agentDir:_a(t,`agentDir`)??!1,..._i(t),agentSessionDir:_a(t,`agentSessionDir`)??!1}}function _i(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-webui`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEBUI agentDirSource field`);return{agentDirSource:t}}function vi(e){let t=E(e);return{packages:j(bi)(t.packages)}}function yi(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:xi(t.scope),i=Pi(t.removed,`removed`);return{action:Si(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(bi)(t.packages)}}function bi(e){let t=E(e);return{source:D(t,`source`),scope:xi(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function xi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Si(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ci(e){let t=E(e);return{packages:j(wi)(t.packages),totals:Di(t.totals),diagnostics:j(Ai)(t.diagnostics)}}function wi(e){let t=E(e);return{source:D(t,`source`),scope:Ti(t.scope),filtered:A(t,`filtered`),disabled:A(t,`disabled`),...N(`installedPath`,O(t,`installedPath`)),...N(`packageName`,O(t,`packageName`)),...N(`version`,O(t,`version`)),...N(`configuredVersion`,O(t,`configuredVersion`)),counts:Di(t.counts),resources:j(Oi)(t.resources),status:Ei(t.status)}}function Ti(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Ei(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function Di(e){let t=E(e);return{extensions:k(t,`extensions`),skills:k(t,`skills`),prompts:k(t,`prompts`),themes:k(t,`themes`)}}function Oi(e){let t=E(e);return{kind:ki(t.kind),name:D(t,`name`),path:D(t,`path`),relativePath:D(t,`relativePath`)}}function ki(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Ai(e){let t=E(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`))}}function ji(e){let t=E(e);return{plugins:j(Mi)(t.plugins)}}function Mi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ni(t.scope),machineSpecific:Pi(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ni(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Pi(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Fi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Li(t.components),release:Hi(t.release),commands:Ui(t.commands),messages:j(Wi)(t.messages)}}function Ii(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Ri(t.components),capabilities:Ki(t.capabilities)}}function Li(e){let t=E(e);return{web:Bi(t.web),sessiond:Bi(t.sessiond)}}function Ri(e){let t=E(e);return{web:zi(t.web),sessiond:zi(t.sessiond)}}function zi(e){let t=E(e),n=Gi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:It(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:Ki(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function Bi(e){let t=E(e);return{component:Gi(t.component),label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...N(`installation`,Vi(t.installation)),...N(`error`,O(t,`error`))}}function Vi(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEBUI installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEBUI installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEBUI Docker mode`);return{kind:n,...N(`path`,O(t,`path`)),...N(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Hi(e){let t=E(e);return{packageName:D(t,`packageName`),...N(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...N(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,O(t,`error`))}}function Ui(e){let t=E(e);return{...N(`update`,O(t,`update`)),...N(`restart`,O(t,`restart`)),...N(`restartWeb`,O(t,`restartWeb`)),...N(`restartSessiond`,O(t,`restartSessiond`)),...N(`status`,O(t,`status`))}}function Wi(e){let t=E(e);return{id:D(t,`id`),severity:qi(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function Gi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Ki(e){let t=Kt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function qi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Ji(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(ia)(t.options)};if(n===`tree`)return{type:n,tree:Yi(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...aa(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Yi(e){let t=E(e),n=j(Xi)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ta(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:ra(t.activePathIds,`activePathIds`)}}function Xi(e){let t=E(e);return{id:na(t,`id`),parentId:ta(t,`parentId`),kind:Zi(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function Zi(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 Qi(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){ea(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return ea(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function $i(e){let t=E(e);return A(t,`cancelled`)?(ea(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:sn(t.session)}}function ea(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ta(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 na(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function ra(e,t){let n=Yt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ia(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function aa(e){return e===void 0?{}:{session:sn(e)}}function oa(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function sa(e){let t=E(e);return j(ca)(t.attachments)}function ca(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function la(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function ua(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function da(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function fa(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Yt(t.sessionIds,`sessionIds`),r=M(t,`archivedCount`),i=M(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function pa(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function ma(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function ha(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ga(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function _a(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function M(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function va(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 N(e,t){return t===void 0?{}:{[e]:t}}function ya(e){let t=E(e),n=E(t.memory),r=E(t.network);return{generatedAt:D(t,`generatedAt`),memory:{totalBytes:k(n,`totalBytes`),usedBytes:k(n,`usedBytes`),freeBytes:k(n,`freeBytes`),usagePercent:k(n,`usagePercent`)},network:Sa(r)}}function ba(e){let t=E(e),n=E(t.os),r=E(t.cpu),i=E(t.memory),a=E(t.network),o=t.gpu,s;if(o!=null){let e=E(o),t={name:D(e,`name`)},n=O(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=M(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=M(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=M(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=M(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:D(t,`generatedAt`),os:{platform:D(n,`platform`),release:D(n,`release`),arch:D(n,`arch`),uptimeSeconds:k(n,`uptimeSeconds`)},cpu:{model:D(r,`model`),cores:k(r,`cores`),usagePercent:k(r,`usagePercent`)},memory:{totalBytes:k(i,`totalBytes`),usedBytes:k(i,`usedBytes`),freeBytes:k(i,`freeBytes`),usagePercent:k(i,`usagePercent`)},network:xa(a)};s!==void 0&&(c.gpu=s);let l=O(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=O(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function xa(e){let t={hostname:D(e,`hostname`),localIpv4Addresses:Yt(e.localIpv4Addresses,`localIpv4Addresses`),...Sa(e)},n=O(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=O(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function Sa(e){let t={},n=M(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=M(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function Ca(e){return typeof e==`string`?e:e.id}function wa(e){return typeof e==`string`?void 0:e.cwd}function Ta(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function Ea(e,t,n=`local`){let r=new URLSearchParams,i=wa(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(Ca(e))}/messages${a===``?``:`?${a}`}`}function Da(e,t=`local`){let n=new URLSearchParams,r=wa(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Ca(e))}/export${i===``?``:`?${i}`}`}function Oa(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`),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function ka(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Aa(e){return typeof e==`string`?e:e.id}function ja(e){return typeof e==`string`?void 0:e.cwd}function Ma(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(Aa(e))}`}function F(e,t,n=`local`){return`${Ma(e,n)}/${t}`}function Na(e,t,n=`local`){return`${F(e,t,n)}${Fa(e)}`}function Pa(e,t=`local`){return`${Ma(e,t)}${Fa(e)}`}function Fa(e){let t=ja(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function I(e,t={}){let n=ja(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ia(e){return JSON.stringify({sessions:e.map(La)})}function La(e){let t=Aa(e),n=ja(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ra(e){return e===`local`?`api/pi-webui/status`:`${P(e)}/pi-webui/status`}var za={piWebUiStatus:(e=`local`)=>w(Ra(e),Fi),checkForUpdates:(e=`local`)=>w(`${Ra(e)}?refresh=1`,Fi,{cache:`no-store`}),piWebUiRuntime:()=>w(`api/pi-webui/runtime`,Ii),systemInfo:(e=`local`)=>w(`${P(e)}/pi-webui/system-info`,ba),systemMetrics:(e=`local`)=>w(`${P(e)}/pi-webui/system-metrics`,ya,{cache:`no-store`})},Ba={machines:()=>w(`api/machines`,Zt),addMachine:e=>w(`api/machines`,Qt,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>w(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>w(`api/machines/${encodeURIComponent(e)}/health`,$t),runtime:(e,t=!1)=>w(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,en,t?{cache:`no-store`}:{})};function Va(e){return e===void 0?`api/config`:`${P(e)}/config`}function Ha(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var Ua={config:e=>w(Va(e),ai),saveConfig:(e,t)=>w(Va(t),ai,{method:`PUT`,body:JSON.stringify({config:e})})},Wa={plugins:e=>w(Ha(e),ji)};function Ga(e=`local`){return`${P(e)}/models-config`}var Ka={config:(e=`local`)=>w(Ga(e),$n),save:(e,t=`local`)=>w(Ga(t),sr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>w(`${Ga(t)}/test`,ur,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>w(`${Ga(t)}/discover`,cr,{method:`POST`,body:JSON.stringify(e)})};function qa(e=`local`){return`${P(e)}/skills`}function Ja(e,t=`local`){return`${qa(t)}?${new URLSearchParams({cwd:e}).toString()}`}var Ya={list:(e,t=`local`)=>w(Ja(e,t),dr),toggle:(e,t=`local`)=>w(qa(t),hr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>w(`${qa(t)}/search`,gr,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>w(`${qa(t)}/install`,hr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>w(`${qa(t)}/check`,vr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>w(`${qa(t)}/update`,xr,{method:`POST`,body:JSON.stringify(e)})};function Xa(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Za={packages:e=>w(Xa(``,e),vi),install:(e,t)=>{let n={source:e};return w(Xa(`install`,t),yi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return w(Xa(`remove`,n),yi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return w(Xa(`update`,t),yi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function Qa(e=`local`){return`${P(e)}/package-plugins`}function $a(e,t=`local`){return`${Qa(t)}?${new URLSearchParams({cwd:e}).toString()}`}var eo={list:(e,t=`local`)=>w($a(e,t),Ci),mutate:(e,t=`local`)=>w(Qa(t),Ci,{method:`POST`,body:JSON.stringify(e)})},to={workspaceActivity:(e=`local`)=>w(`${P(e)}/activity`,ii)},no={projects:(e=`local`)=>w(`${P(e)}/projects`,j(rn)),addProject:(e,t,n,r=`local`)=>w(`${P(r)}/projects`,rn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}`,la,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>w(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Vr))},ro={workspaces:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(an)),deleteWorkspace:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ei,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Hr),workspaceFile:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Wr),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 w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Gr,{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 w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Kr,{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`),w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,qr,{method:`POST`})}},io={sessions:(e,t=`local`)=>w(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(sn)),unreadCatalog:(e=`local`)=>w(`${P(e)}/sessions/unread`,hn,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return w(F(e,`unread/acknowledge`,r),hn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>w(Na(e,`notifications`,t),Sn),dismissNotification:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss`,r),Sn,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss-all`,r),Sn,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`)=>w(`${P(t)}/sessions`,sn,{method:`POST`,body:JSON.stringify({cwd:e})}),sessionDefaults:(e,t=`local`)=>w(`${P(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,Qn),updateSessionDefaults:(e,t,n=`local`)=>w(`${P(n)}/session-defaults`,Qn,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup/preview`,zn,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup`,Bn,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>w(`${P(e)}/sessions/cleanup/force`,Bn,{method:`POST`}),archiveMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/archive`,Vn,{method:`POST`,body:Ia(e)}),deleteArchivedMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/delete-archived`,Hn,{method:`POST`,body:Ia(e)}),messages:(e,t,n=`local`)=>w(Ea(e,t,n),Xt),status:(e,t=`local`)=>w(Na(e,`status`,t),fn),systemPrompt:(e,t=`local`)=>w(Na(e,`system-prompt`,t),mn),streamSnapshot:(e,t=`local`)=>w(Na(e,`stream-snapshot`,t),pn),clearQueue:(e,t=`local`)=>w(F(e,`queue/clear`,t),fn,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>w(F(e,`warnings/dismiss`,n),fn,{method:`POST`,body:I(e,{dismissId:t})}),models:(e,t=`local`)=>w(Na(e,`models`,t),Zn),setModel:(e,t,n,r=`local`)=>w(F(e,`model`,r),fn,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>w(F(e,`model/cycle`,n),fn,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>w(Na(e,`thinking-levels`,t),Cr),setThinkingLevel:(e,t,n=`local`)=>w(F(e,`thinking-level`,n),fn,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>w(F(e,`thinking-level/cycle`,t),fn,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>w(Na(e,`commands`,t),j(Br)),prompt:(e,t,n,r=`local`,i)=>w(F(e,`prompt`,r),oa,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>w(F(e,`attachments`,n),sa,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>w(F(e,`shell`,n),oa,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>w(F(e,`commands/run`,n),Ji,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>w(F(e,`commands/respond`,r),Ji,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>w(F(e,`tree/navigate`,n),Qi,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>w(F(e,`messages/edit-from-here`,n),Qi,{method:`POST`,body:I(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>w(F(e,`messages/fork`,n),$i,{method:`POST`,body:I(e,{entryId:t})}),abort:(e,t=`local`)=>w(F(e,`abort`,t),ua,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>w(F(e,`stop`,t),da,{method:`POST`,body:I(e)}),archive:(e,t=`local`)=>w(F(e,`archive`,t),fa,{method:`POST`,body:I(e)}),archiveWithDescendants:(e,t=`local`)=>w(F(e,`archive-tree`,t),fa,{method:`POST`,body:I(e)}),restore:(e,t=`local`)=>w(F(e,`restore`,t),pa,{method:`POST`,body:I(e)}),deleteArchived:(e,t=`local`)=>w(Pa(e,t),ma,{method:`DELETE`}),detachParent:(e,t=`local`)=>w(F(e,`detach-parent`,t),ha,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>w(F(e,`reload`,t),ga,{method:`POST`,body:I(e)}),pin:(e,t=`local`)=>w(F(e,`pin`,t),sn,{method:`POST`,body:I(e)}),unpin:(e,t=`local`)=>w(F(e,`unpin`,t),sn,{method:`POST`,body:I(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 w(`${P(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Or)},saveApiKey:(e,t,n=`local`)=>w(`${P(n)}/auth/api-key`,oa,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>w(`${P(t)}/auth/api-key/interactive`,kr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>w(`${P(t)}/auth/logout`,oa,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>w(`${P(t)}/auth/oauth`,kr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}`,kr),respondOAuthFlow:(e,t,n,r=`local`)=>w(`${P(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,kr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,kr,{method:`POST`})},ao={terminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j($r)),startTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,$r,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,la,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,la,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,$r,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ei,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs${so(e)}`,j(ei)),getCommandRun:(e,t=`local`)=>oo(e,t),cancelCommandRun:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ei,{method:`POST`})};async function oo(e,t){let n=await fetch(bt(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(co(e)??n.statusText)}return ei(await n.json())}}function so(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 co(e){if(!lo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function lo(e){return typeof e==`object`&&!!e}var uo={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?w(`${P(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Vr)):(r.set(`cwd`,e),w(`${P(n.machineId)}/files?${r.toString()}`,j(Vr)))}},fo={gitStatus:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Yr),gitDiff:(e,t,n,r=`local`)=>w(Ta(r,e,t,n),Qr)},L={...za,...Ba,...Ua,...Wa,...Za,...eo,...to,...no,...ro,...io,...ao,...uo,...fo};function po(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(xt(`${go(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function mo(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(xt(`${go(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function ho(e=`local`){return new WebSocket(xt(`${go(e)}/events`))}function go(e){return`api/machines/${encodeURIComponent(e)}`}var _o=`.pi-webui/uploads`,vo=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},yo=class extends Error{constructor(e,t){super(Ao(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function bo(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function xo(e,t){return e?.uploads?.defaultFolder??t}function So(e,t){let n=No(e,`upload destination`,{allowEmpty:!0}),r=No(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Co(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`,Oa(e,t,n.path,Eo(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Do(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(Gr(Fo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Io(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new vo(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function wo(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:So(i,e.name),loaded:0,total:e.size,percent:ko(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Oo(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 vo;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Co(e,t,{path:p.path,file:f},{...To(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(Mo(e,c))throw e;let t=jo(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 yo(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function To(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 Eo(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Do(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ko(e.loaded,n),lengthComputable:e.lengthComputable}}function Oo(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:ko(i,r),done:n}}function ko(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Ao(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function jo(e){return e instanceof Error?e.message:String(e)}function Mo(e,t){return t.requested||e instanceof vo}function No(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Po(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 Po(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Fo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Io(e){let t=Lo(e);return Ro(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Lo(e){try{return Fo(e)}catch{return}}function Ro(e){return typeof e==`object`&&!!e}function zo(){return{sessions:[],projectSessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingSessions:!1,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:``}}function Bo(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Vo(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ho(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Uo(e,t){return`${e}:${t}`}function Wo(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Go=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Ko=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Go,this.api=n.api??to,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,qo(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=Jo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function qo(e){let t={};for(let n of e.workspaces)Ho(n)&&(t[n.cwd]=n);return t}function Jo(e,t){let n={...e};return Ho(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Yo=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??L,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Zo(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Xo(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Xo(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEBUI instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Xo(n.flow):void 0,a=Xo(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.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=Xo(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||Xo(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Xo(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(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(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Xo(e){return e.prompt?.requestId??e.select?.requestId}function Zo(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 Qo(e){return e.replaceAll(`:`,`.`)}function $o(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 es(e,t){let n=$o(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function ts(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));ns(i,r)}function ns(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 rs(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:So(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ls(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:ls(0,n),status:`uploading`,startedAt:e.startedAt}}function is(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 as(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=cs(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function os(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,...cs(r),status:`error`,error:t,completedAt:n}}function ss(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,...cs(r),status:`cancelled`,error:n,completedAt:t}}function cs(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ls(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var us=Qo(`core:workspace.files`),ds=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??L,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??wo,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=R(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,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:hs(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),ts(us,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(fs(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),ts(us,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=rs({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(ss(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:hs(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(is(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(as(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof yo)||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(ps(t)){let e=ss(n,this.now());return this.setUploadBatch(e),e}let r=ms(t),i=os(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function fs(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function ps(e){return e instanceof vo}function ms(e){return e instanceof Error?e.message:String(e)}function hs(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var gs=Qo(`core:workspace.git`),_s=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.statusRequest=0,this.diffRequest=0}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollingScope=void 0,this.statusRequest+=1,this.diffRequest+=1}async refreshGit(e={}){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await L.gitStatus(t.id,n.id,r);if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;this.setState({gitStatus:a,gitStale:!1,...e.reportError===!1?{}:{error:``}});let o=this.getState().selectedDiffPath;o!==void 0&&(a.files.some(e=>e.path===o)?await this.refreshDiff(o,e):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ts(gs,`diff`,void 0,{replace:!0})))}catch(a){if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;e.reportError!==!1&&this.setState({error:String(a)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),ts(gs,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e,t={}){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0)return;let i=R(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([L.gitDiff(n.id,r.id,{path:e},i),L.gitDiff(n.id,r.id,{path:e,staged:!0},i)]);if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;this.setState({selectedDiff:o,selectedStagedDiff:s,...t.reportError===!1?{}:{error:``}})}catch(e){if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;t.reportError!==!1&&this.setState({error:String(e)})}}updatePolling(){let e=this.currentPollingScope();e===this.pollingScope&&this.pollTimer!==void 0||(this.dispose(),e!==void 0&&(this.pollingScope=e,this.refreshGit({reportError:!1}),this.pollTimer=window.setInterval(()=>{this.refreshGit({reportError:!1})},8e3)))}currentPollingScope(){let e=this.getState();if(!(e.selectedProject===void 0||e.selectedWorkspace?.isGitRepo!==!0))return JSON.stringify([R(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return R(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}};function vs(e){let t=[],n=[];for(let r of e)ws(r.index)&&t.push(Cs(r,`staged`,r.index)),Ts(r.workingTree)&&n.push(Cs(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function ys(e){let t=vs(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function bs(e){switch(e){case`modified`:return`M`;case`added`:return`A`;case`deleted`:return`D`;case`renamed`:return`R`;case`copied`:return`C`;case`untracked`:return`?`;case`conflicted`:return`U`;case`ignored`:return`!`;case`unmodified`:return``}}function xs(e){switch(e){case`modified`:return`Modified`;case`added`:return`Added`;case`deleted`:return`Deleted`;case`renamed`:return`Renamed`;case`copied`:return`Copied`;case`untracked`:return`Untracked`;case`conflicted`:return`Conflicted`;case`ignored`:return`Ignored`;case`unmodified`:return`Unmodified`}}function Ss(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Cs(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function ws(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Ts(e){return e!==`unmodified`&&e!==`ignored`}var Es=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 L.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Os(this.getState().machineActivities,r),machineRuntimes:Os(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...zo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await L.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 L.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:Ds(this.getState().machineStatuses,e.id),machineRuntimes:Ds(this.getState().machineRuntimes,e.id),machineActivities:Ds(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await L.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 L.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 L.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=>L.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=>L.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 Ds(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Os(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var ks=`~/workspace`,As=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??L,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n;if(t.length===0){if(n=await this.api.addProject(ks,void 0,!0,e),R(this.getState())!==e)return;t=[n]}let r=new Set(t.map(e=>e.id)),i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>r.has(e)));this.setState({projects:t,workspacesByProjectId:i}),this.onProjectsApplied?.(e),n!==void 0&&await this.workspaces.selectProject(n)}catch(t){R(this.getState())===e&&this.setState({error:String(t)})}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){R(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}};function js(e,t){return t[e.path]}function Ms(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Ns(e,t,n){return Is(Ls(e,t,n))}function Ps(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Fs(e){return Is(Object.values(e??{}))}function Is(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ls(e,t,n){return Object.values(n).filter(n=>Ps(e,t,n.cwd))}var Rs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??ro,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!zs(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!zs(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Ho).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function zs(e,t,n){return e.some(e=>Ps(e,t[e.id]??[],n))}var Bs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??za,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebUiStatus(e);this.isCurrent(e,t)&&this.setState({piWebUiStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebUiStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(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({piWebUiStatus:t}),Vs(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 R(this.getState())===e&&t===this.requestSequence}};function Vs(e){if(e.release.error!==void 0)throw Error(`PI WEBUI update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEBUI update check was skipped because remote version checks are disabled by offline/version-check settings`)}var Hs=`pi-webui:cached-new-sessions:v1`,Us=`browserCachedNew`,Ws=`local`;function Gs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Ks(e,t=Ws,n=Gs()){if(e.messageCount!==0||e.archived===!0)return;let r=Qs(n).filter(n=>n.id!==e.id||n.machineId!==t);$s([qs(e,t),...r],n)}function qs(e,t=Ws){return{...e,browserCachedNew:!0,machineId:t}}function Js(e,t=Ws,n=Gs()){$s(Qs(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Ys(e,t,n=Ws,r=Gs()){let i=new Set(t.map(e=>e.id)),a=Qs(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&$s(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Xs(e){return e!==void 0&&tc(e)&&e.browserCachedNew===!0}function Zs(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:Ws},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Qs(e=Gs()){try{let t=e?.getItem(Hs);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>ec(e)):[]}catch{return[]}}function $s(e,t=Gs()){try{e.length===0?t?.removeItem(Hs):t?.setItem(Hs,JSON.stringify(e))}catch{}}function ec(e){if(!nc(e))return[];let t=rc(e,`id`),n=rc(e,`path`),r=rc(e,`cwd`),i=rc(e,`created`),a=rc(e,`modified`),o=rc(e,`firstMessage`),s=ac(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=ic(e,`name`),l=ic(e,`parentSessionPath`),u=ic(e,`machineId`)??Ws;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 tc(e){return Us in e}function nc(e){return typeof e==`object`&&!!e}function rc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function ic(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function ac(e,t){let n=e[t];return typeof n==`number`?n:void 0}function oc(e){return Tc(e.flatMap(dc)).filter(e=>e.parts.length>0)}function sc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function cc(e,t){let n=_c(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Pc(t,`canFork`);return{...e,...n===void 0?{}:{meta:n},...r===void 0?{}:{entryId:r},...i===void 0?{}:{previousAssistantEntryId:i},...a===void 0?{}:{canFork:a}}}function lc(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,sc(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 dc(e){if(pc(e))return[e];if(z(e,`role`)===`bashExecution`)return[cc(bc(e),e)];let t=xc(z(e,`role`)),n=Sc(Nc(e,`content`),e),r=t===`user`?mc(n):void 0;if(r!==void 0)return r.map(t=>cc(t,e));let i=gc(e);if(t===`tool`)return[cc({role:t,parts:n,...i===void 0?{}:{source:i}},e)];let a=n.filter(e=>e.type!==`empty`),o=t===`assistant`&&a.length>0&&a.every(e=>e.type===`skillRead`)?`skill`:t,s=a.length>0?[cc({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=fc(e);return c===void 0?s:[...s,cc(c,e)]}function fc(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return sc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function pc(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Nc(e,`parts`))}function mc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=hc(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 hc(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 gc(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function _c(e){let t=vc(Nc(e,`timestamp`)),n=yc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function vc(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 yc(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(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 bc(e){let t=z(e,`command`)??``,n=Pc(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Nc(e,`output`);r!=null&&n.push(``,Ic(r));let i=Nc(e,`exitCode`);i!=null&&n.push(``,`exit ${Ic(i)}`),Pc(e,`cancelled`)===!0&&n.push(``,`cancelled`),Pc(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function xc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Sc(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=Nc(e,`arguments`),r=z(e,`id`),i=t===`read`?wc(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ac(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return kc(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Cc(e.text,t):e):kc(e)}function Cc(e,t){let n=z(t,`toolCallId`),r=Nc(t,`content`),i=Nc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Pc(t,`isError`)===!0}}function wc(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Tc(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.entryId===void 0?{}:{entryId:r.entryId},...r.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:r.previousAssistantEntryId},...r.canFork===void 0?{}:{canFork:r.canFork},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&Dc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Ec(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function Dc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Oc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Oc(e){let t=Nc(e,`preview`);if(!Mc(t))return;let n=z(t,`diff`),r=z(t,`error`),i=Fc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function kc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ac(e)}]:[{type:`text`,text:Ic(e)}]}function Ac(e){if(!Mc(e))return Ic(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${jc(t)}`).join(` · `)}function jc(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Mc(e){return typeof e==`object`&&!!e}function Nc(e,t){return Mc(e)?e[t]:void 0}function z(e,t){let n=Nc(e,t);return typeof n==`string`?n:void 0}function Pc(e,t){let n=Nc(e,t);return typeof n==`boolean`?n:void 0}function Fc(e,t){let n=Nc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ic(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Lc=`pi-webui:prompt-draft:`;function Rc(e){return`${Lc}${e}`}function zc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bc(e,t=zc()){try{return t?.getItem(Rc(e))??``}catch{return``}}function Vc(e,t,n=zc()){try{t?n?.setItem(Rc(e),t):n?.removeItem(Rc(e))}catch{}}function Hc(e,t=zc()){try{t?.removeItem(Rc(e))}catch{}}function Uc(e,t,n=zc()){let r=Bc(e,n);r!==``&&(Vc(t,r,n),Hc(e,n))}function Wc(e,t){return sc(`bash`,`${t===!0?`excluded from context
|
|
@@ -1097,7 +1097,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1097
1097
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1098
1098
|
.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; }
|
|
1099
1099
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1100
|
-
`]}};B([x({attribute:!1})],im.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],im.prototype,`uploadInput`,void 0),B([S()],im.prototype,`pendingUpload`,void 0),B([S()],im.prototype,`destinationFolder`,void 0),B([S()],im.prototype,`overwrite`,void 0),B([S()],im.prototype,`createDirs`,void 0),B([S()],im.prototype,`formError`,void 0),B([S()],im.prototype,`dragActive`,void 0),im=B([b(`workspace-files-panel`)],im);function am(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 om(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{So(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function sm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function cm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${xm(t.size)}`}function lm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function um(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function dm(e){return e==null?[]:Array.from(e)}function fm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function pm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function mm(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 hm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return ym(e.percent)}}function gm(e){return e.status===`uploading`?e.percent:1}function _m(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return ym(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function vm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${xm(e.loaded)} / ${xm(e.total)}`:`Wrote ${e.response.path}`:e.error}function ym(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function bm(){rm(()=>import(`./CodeViewer-
|
|
1100
|
+
`]}};B([x({attribute:!1})],im.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],im.prototype,`uploadInput`,void 0),B([S()],im.prototype,`pendingUpload`,void 0),B([S()],im.prototype,`destinationFolder`,void 0),B([S()],im.prototype,`overwrite`,void 0),B([S()],im.prototype,`createDirs`,void 0),B([S()],im.prototype,`formError`,void 0),B([S()],im.prototype,`dragActive`,void 0),im=B([b(`workspace-files-panel`)],im);function am(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 om(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{So(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function sm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function cm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${xm(t.size)}`}function lm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function um(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function dm(e){return e==null?[]:Array.from(e)}function fm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function pm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function mm(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 hm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return ym(e.percent)}}function gm(e){return e.status===`uploading`?e.percent:1}function _m(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return ym(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function vm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${xm(e.loaded)} / ${xm(e.total)}`:`Wrote ${e.response.path}`:e.error}function ym(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function bm(){rm(()=>import(`./CodeViewer-BdULrLxb.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function xm(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Sm(t)} KB`;let n=t/1024;return n<1024?`${Sm(n)} MB`:`${Sm(n/1024)} GB`}function Sm(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Cm=2e3,wm=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await za.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},Cm))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await za.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
|
|
1101
1101
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1102
1102
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1103
1103
|
</section>`;let e=this.systemInfo;return e===void 0?g`<section class="info-panel"><p class="muted">System information unavailable.</p></section>`:g`<section class="info-panel">
|
|
@@ -1351,7 +1351,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1351
1351
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1352
1352
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1353
1353
|
</section>
|
|
1354
|
-
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-
|
|
1354
|
+
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-DDlEJGJ4.js`),[],import.meta.url)}function Rm(){rm(()=>Promise.resolve().then(()=>oO),void 0,import.meta.url)}function zm(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Bm(e){let t=Vm(e);return g`
|
|
1355
1355
|
<p class="summary">
|
|
1356
1356
|
<span class="summary-branch">${t.branch}</span>
|
|
1357
1357
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -2320,7 +2320,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2320
2320
|
.custom-focus, .validation-error { margin-inline-start: 0; }
|
|
2321
2321
|
footer { flex-wrap: wrap; }
|
|
2322
2322
|
}
|
|
2323
|
-
`}};B([x({attribute:!1})],zv.prototype,`tree`,void 0),B([x({attribute:!1})],zv.prototype,`onNavigate`,void 0),B([x({attribute:!1})],zv.prototype,`onAbort`,void 0),B([x({attribute:!1})],zv.prototype,`onCancel`,void 0),B([S()],zv.prototype,`selectedId`,void 0),B([S()],zv.prototype,`foldedIds`,void 0),B([S()],zv.prototype,`step`,void 0),B([S()],zv.prototype,`summaryMode`,void 0),B([S()],zv.prototype,`customInstructions`,void 0),B([S()],zv.prototype,`busy`,void 0),B([S()],zv.prototype,`aborting`,void 0),B([S()],zv.prototype,`error`,void 0),B([S()],zv.prototype,`statusMessage`,void 0),zv=B([b(`session-tree-navigator`)],zv);function Bv(e){return Math.min(Math.max(0,e),Rv)}function Vv(e){return e===`user`||e===`custom-message`}function Hv(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function Uv(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function Wv(e){return e instanceof Error?e.message:String(e)}var Gv=`pi-webui:chat-groups:`,Kv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Jv(e));return t===null||t===``?void 0:Yv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Jv(e),JSON.stringify(t))}catch{}}},qv=class{constructor(e=Kv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Zv(i,this.openGroupKeys)&&Zv(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Jv(e){return`${Gv}${e}`}function Yv(e){if(Array.isArray(e))return{open:Xv(e),closedDefaultOpen:[]};if(Qv(e))return{open:Array.isArray(e.open)?Xv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Xv(e.closedDefaultOpen):[]}}function Xv(e){return e.filter(e=>typeof e==`string`)}function Zv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Qv(e){return typeof e==`object`&&!!e}function $v(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>ry(e,t)),s=e.parts.filter(t=>!ry(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(ty(t)){let e=ny(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function ey(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function ty(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function ny(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function ry(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function iy(e,t=ay()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function ay(){let e=e=>cy(e),t=sy();return t===void 0?{isSecureContext:oy(),fallbackWriteText:e}:{isSecureContext:oy(),writeText:t,fallbackWriteText:e}}function oy(){return typeof window<`u`&&window.isSecureContext}function sy(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function cy(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:ly(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),uy(n,r),dy(t)}}function ly(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function uy(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function dy(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function fy(e,t){let n=my(_y(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function py(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=hy(r,t.markerOffset);return}e.scrollTop=gy(e.scrollHeight,t.distanceFromBottom)}function my(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function hy(e,t){return e-t}function gy(e,t){return Math.max(0,e-t)}function _y(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var vy=600,yy=1;function by(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:xy(e)||Sy(e)}function xy(e){return e.scrollTop<(e.topThreshold??Math.max(vy,e.clientHeight))}function Sy(e){return e.scrollHeight<=e.clientHeight+yy}var Cy=`pi-webui:chat-scroll:`,wy=180,Ty=48,Ey=2,Dy={getItem(e){return typeof localStorage>`u`?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>`u`||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>`u`||localStorage.removeItem(e)}},Oy={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},ky=class{constructor(e=Dy,t=Oy){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=wy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Ey){if(e===``||t===void 0||!My(t))return`skipped`;try{if(Py(t,r))return this.storage.setItem(Ay(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Iy(t,n);if(i===void 0)return`skipped`;let a=Fy(t,i);return this.storage.setItem(Ay(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!My(t))return{status:`skipped`};let i=Ry(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(Ay(e));if(t===null||t===``)return;let n=JSON.parse(t);return jy(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!My(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Ay(e){return`${Cy}${e}`}function jy(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function My(e){return e.clientHeight>0&&e.scrollHeight>0}function Ny(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Py(e,t=Ty){return Ny(e)<t}function Fy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:zy(t)??``,offset:t.getBoundingClientRect().top-n}}function Iy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(zy(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function Ly(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Ry(e,t){return e.find(e=>zy(e)===t)}function zy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function By(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return i<=20?{scrollRatio:0,viewportRatio:1,visible:!1}:{scrollRatio:Vy(r/i),viewportRatio:Vy(n/t),visible:!0}}function Vy(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Hy(e,t){return Vy(e*(1-t))}function Uy(e,t,n,r){return r<=0?0:Vy((e-t+n)/r)}var Wy=22,Gy=2;function Ky(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-Wy),i=e.map((e,t)=>({index:t,desiredTop:Vy(e.topRatio)*n-Wy/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*Wy+(i.length-1)*Gy>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function qy(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Vy(t)}function Jy(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:`0`}function Yy(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Xy(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function Zy(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Qy(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function $y(e){let t=[],n=e.tokens;t.push(`Input: ${Zy(n.input)}`),t.push(`Output: ${Zy(n.output)}`),t.push(`Cache read: ${Zy(n.cacheRead)}`),t.push(`Cache write: ${Zy(n.cacheWrite)}`),t.push(`Total: ${Zy(n.total)}`),e.cost>0&&t.push(`Cost: ${Xy(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${Zy(r.contextWindow)} tokens`)}return t.join(` | `)}function eb(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function tb(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:Zy(e.messageCount)}):(i.push({label:`User`,value:Zy(n.user)}),i.push({label:`Assistant`,value:Zy(n.assistant)}),i.push({label:`Tool calls`,value:Zy(n.toolCalls)}),i.push({label:`Tool results`,value:Zy(n.toolResults)}),i.push({label:`Total`,value:Zy(n.total)}));let a=e.tokens,o=[{label:`Input`,value:Zy(a.input)},{label:`Output`,value:Zy(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:Zy(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:Zy(a.cacheWrite)}),o.push({label:`Total`,value:Zy(a.total)}),e.cost>0&&o.push({label:`Cost`,value:Xy(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${Qy(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var nb=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=Vy((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=Vy((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=Vy(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Hy(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Vy(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
|
|
2323
|
+
`}};B([x({attribute:!1})],zv.prototype,`tree`,void 0),B([x({attribute:!1})],zv.prototype,`onNavigate`,void 0),B([x({attribute:!1})],zv.prototype,`onAbort`,void 0),B([x({attribute:!1})],zv.prototype,`onCancel`,void 0),B([S()],zv.prototype,`selectedId`,void 0),B([S()],zv.prototype,`foldedIds`,void 0),B([S()],zv.prototype,`step`,void 0),B([S()],zv.prototype,`summaryMode`,void 0),B([S()],zv.prototype,`customInstructions`,void 0),B([S()],zv.prototype,`busy`,void 0),B([S()],zv.prototype,`aborting`,void 0),B([S()],zv.prototype,`error`,void 0),B([S()],zv.prototype,`statusMessage`,void 0),zv=B([b(`session-tree-navigator`)],zv);function Bv(e){return Math.min(Math.max(0,e),Rv)}function Vv(e){return e===`user`||e===`custom-message`}function Hv(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function Uv(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function Wv(e){return e instanceof Error?e.message:String(e)}var Gv=`pi-webui:chat-groups:`,Kv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Jv(e));return t===null||t===``?void 0:Yv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Jv(e),JSON.stringify(t))}catch{}}},qv=class{constructor(e=Kv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Zv(i,this.openGroupKeys)&&Zv(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Jv(e){return`${Gv}${e}`}function Yv(e){if(Array.isArray(e))return{open:Xv(e),closedDefaultOpen:[]};if(Qv(e))return{open:Array.isArray(e.open)?Xv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Xv(e.closedDefaultOpen):[]}}function Xv(e){return e.filter(e=>typeof e==`string`)}function Zv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Qv(e){return typeof e==`object`&&!!e}function $v(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>ry(e,t)),s=e.parts.filter(t=>!ry(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(ty(t)){let e=ny(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function ey(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function ty(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function ny(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function ry(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function iy(e,t=ay()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function ay(){let e=e=>cy(e),t=sy();return t===void 0?{isSecureContext:oy(),fallbackWriteText:e}:{isSecureContext:oy(),writeText:t,fallbackWriteText:e}}function oy(){return typeof window<`u`&&window.isSecureContext}function sy(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function cy(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:ly(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),uy(n,r),dy(t)}}function ly(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function uy(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function dy(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function fy(e,t){let n=my(_y(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function py(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=hy(r,t.markerOffset);return}e.scrollTop=gy(e.scrollHeight,t.distanceFromBottom)}function my(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function hy(e,t){return e-t}function gy(e,t){return Math.max(0,e-t)}function _y(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var vy=600,yy=1;function by(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:xy(e)||Sy(e)}function xy(e){return e.scrollTop<(e.topThreshold??Math.max(vy,e.clientHeight))}function Sy(e){return e.scrollHeight<=e.clientHeight+yy}var Cy=`pi-webui:chat-scroll:`,wy=180,Ty=48,Ey=2,Dy={getItem(e){return typeof localStorage>`u`?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>`u`||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>`u`||localStorage.removeItem(e)}},Oy={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},ky=class{constructor(e=Dy,t=Oy){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=wy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Ey){if(e===``||t===void 0||!My(t))return`skipped`;try{if(Py(t,r))return this.storage.setItem(Ay(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Iy(t,n);if(i===void 0)return`skipped`;let a=Fy(t,i);return this.storage.setItem(Ay(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!My(t))return{status:`skipped`};let i=Ry(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(Ay(e));if(t===null||t===``)return;let n=JSON.parse(t);return jy(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!My(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Ay(e){return`${Cy}${e}`}function jy(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function My(e){return e.clientHeight>0&&e.scrollHeight>0}function Ny(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Py(e,t=Ty){return Ny(e)<t}function Fy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:zy(t)??``,offset:t.getBoundingClientRect().top-n}}function Iy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(zy(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function Ly(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Ry(e,t){return e.find(e=>zy(e)===t)}function zy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function By(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return{scrollRatio:i>0?Vy(r/i):0,viewportRatio:Vy(n/t),visible:!0}}function Vy(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Hy(e,t){return Vy(e*(1-t))}function Uy(e,t,n,r){return r<=0?0:Vy((e-t+n)/r)}var Wy=22,Gy=2;function Ky(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-Wy),i=e.map((e,t)=>({index:t,desiredTop:Vy(e.topRatio)*n-Wy/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*Wy+(i.length-1)*Gy>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function qy(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Vy(t)}function Jy(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:`0`}function Yy(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Xy(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function Zy(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Qy(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function $y(e){let t=[],n=e.tokens;t.push(`Input: ${Zy(n.input)}`),t.push(`Output: ${Zy(n.output)}`),t.push(`Cache read: ${Zy(n.cacheRead)}`),t.push(`Cache write: ${Zy(n.cacheWrite)}`),t.push(`Total: ${Zy(n.total)}`),e.cost>0&&t.push(`Cost: ${Xy(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${Zy(r.contextWindow)} tokens`)}return t.join(` | `)}function eb(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function tb(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:Zy(e.messageCount)}):(i.push({label:`User`,value:Zy(n.user)}),i.push({label:`Assistant`,value:Zy(n.assistant)}),i.push({label:`Tool calls`,value:Zy(n.toolCalls)}),i.push({label:`Tool results`,value:Zy(n.toolResults)}),i.push({label:`Total`,value:Zy(n.total)}));let a=e.tokens,o=[{label:`Input`,value:Zy(a.input)},{label:`Output`,value:Zy(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:Zy(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:Zy(a.cacheWrite)}),o.push({label:`Total`,value:Zy(a.total)}),e.cost>0&&o.push({label:`Cost`,value:Xy(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${Qy(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var nb=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=Vy((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=Vy((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=Vy(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Hy(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Vy(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
|
|
2324
2324
|
<div
|
|
2325
2325
|
class="rail"
|
|
2326
2326
|
role="scrollbar"
|
|
@@ -2667,7 +2667,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2667
2667
|
`)}function AS(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return oS.format(t)}function jS(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var G=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.warningCount=0,this.warningsExpanded=!1,this.canClearServerQueue=!1,this.canMessageActions=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new qv,this.scrollController=new ky,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.sessionInfoOpen=!1,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.handleUsageToggle=()=>{this.sessionInfoOpen=!this.sessionInfoOpen},this.handleUsageKeydown=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.sessionInfoOpen=!this.sessionInfoOpen)},this.closeSessionInfoPopover=()=>{this.sessionInfoOpen&&(this.sessionInfoOpen=!1,this.removePopoverOutsideListener(),this.requestUpdate())},this.handlePopoverKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSessionInfoPopover(),this.focusUsageToggle())},this.onPopoverGlobalClick=e=>{this.handlePopoverClickOutside(e)},this.popoverGlobalListenerAttached=!1}focusUsageToggle(){this.renderRoot!==void 0&&this.renderRoot.querySelector(`.usage-toggle`)?.focus()}handlePopoverClickOutside(e){let t=this.renderRoot.querySelector(`.session-info-popover`),n=this.renderRoot.querySelector(`.usage-toggle`);if(t===null||n===null)return;let r=e.target;r instanceof Node&&!t.contains(r)&&!n.contains(r)&&this.closeSessionInfoPopover()}ensurePopoverOutsideListener(){this.popoverGlobalListenerAttached||typeof window>`u`||(this.popoverGlobalListenerAttached=!0,window.addEventListener(`click`,this.onPopoverGlobalClick,!0))}removePopoverOutsideListener(){this.popoverGlobalListenerAttached&&(this.popoverGlobalListenerAttached=!1,!(typeof window>`u`)&&window.removeEventListener(`click`,this.onPopoverGlobalClick,!0))}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize),this._setupResizeObserver()}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}_setupResizeObserver(){if(this._resizeObserver!==void 0)return;let e=this.chat;e&&(this._resizeObserver=new ResizeObserver(()=>{this._requestMinimapMeasure()}),this._resizeObserver.observe(e))}disconnectedCallback(){this.removePopoverOutsideListener(),this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),this._minimapMeasureTimer!==void 0&&(clearTimeout(this._minimapMeasureTimer),this._minimapMeasureTimer=void 0),this._resizeObserver!==void 0&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.sessionInfoOpen=!1,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`messages`)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has(`loadingMore`)&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has(`hasMore`)&&!this.hasMore&&(this.loadMoreRequested=!1),e.has(`sessionId`)&&this.restoreScrollPosition(),!e.has(`sessionId`)&&e.has(`messages`)&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&(this.scheduleConversationRailUpdate(),this._requestMinimapMeasure()),e.has(`messages`)&&!e.has(`sessionId`)&&this._updateMinimapViewport(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog(),this.syncPopoverOutsideListener()}syncPopoverOutsideListener(){this.sessionInfoOpen?this.ensurePopoverOutsideListener():this.removePopoverOutsideListener()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!uS(e)||t===void 0?e!==t:hd(e)!==hd(t)}render(){let e=this.groupedMessages();return g`
|
|
2668
2668
|
${this.renderTopNotices()}
|
|
2669
2669
|
${this.renderNotificationLiveRegions()}
|
|
2670
|
-
<div class="chat-wrap" style=${this._minimapViewport.visible?`--pi-minimap-right:36px`:``}>
|
|
2670
|
+
<div class="chat-wrap" style=${this._minimapViewport.visible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
|
|
2671
2671
|
${this.renderConversationRail()}
|
|
2672
2672
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
|
|
2673
2673
|
${this.renderHistoryBoundary()}
|
|
@@ -5986,7 +5986,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5986
5986
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
5987
5987
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
5988
5988
|
}
|
|
5989
|
-
`}};B([x({attribute:!1})],yk.prototype,`onClose`,void 0),B([x({attribute:!1})],yk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],yk.prototype,`workspace`,void 0),B([x()],yk.prototype,`machineId`,void 0),B([x({attribute:!1})],yk.prototype,`api`,void 0),B([S()],yk.prototype,`status`,void 0),B([S()],yk.prototype,`selectedChange`,void 0),B([S()],yk.prototype,`selectedDiff`,void 0),B([S()],yk.prototype,`loadingStatus`,void 0),B([S()],yk.prototype,`loadingDiff`,void 0),B([S()],yk.prototype,`error`,void 0),B([S()],yk.prototype,`bounds`,void 0),yk=B([b(`git-update-manager-panel`)],yk);function bk(){rm(()=>import(`./UnifiedDiffViewer-BZtpu-dj.js`),[],import.meta.url)}function xk(e,t){let n=vs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function Sk(e){return e===`staged`?`Staged`:`Unstaged`}function Ck(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function wk(e){return e instanceof Error?e.message:String(e)}var Tk=900*1e3,Ek=750,Dk=[1e3,3e3,8e3,15e3,3e4],Ok={capture:!0},kk=`auto:on`,Ak=`auto:off`,jk=`theme:`,Mk=Qo(`core:workspace.files`),Nk=Qo(`core:workspace.git`),Pk=Qo(`core:workspace.terminal`),Fk=320,Ik=2,Lk=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Bo(),this.sessionUnread=new qf({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Dd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new wu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Rs(()=>this.state,e=>{this.setState(e)},{api:ro,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ko(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Yo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Fd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nd),this.projects=new As(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Es(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ds(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new _s(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new af,this.realtime=new eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Bd,this.terminalSelection=new $d,this.appShell=new Oh(this),this.browserResume=new Ah({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Kh(this),this.panelResize=new Xh(this),this.navigationSections=new Uh(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=Rk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=fp()??cp,this.activeThemeId=sp,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=Vg(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=rA(),this.infoTabHidden=oA(),this.railOrder=pk()??[...sk],this.settingsSection=_g(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bo(void 0),this.sessionWarningVisibility=tp(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=Pg(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,mk(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?Mg(t.bounds,n,r):Ng(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=zg(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Bg(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=op(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=Vk(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=rp(this.sessionWarningVisibility,e===void 0?void 0:Wo(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=Bk(e,t);await this.updateComplete,!(!this.unreadConnected||Vk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);qk(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Jg(this.state.selectedProject?.name);this.windowTitleCleanup=Yg(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Bk(e,t);return Vk(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen}connectedCallback(){super.connectedCallback(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,Ok),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},Tk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,Ok),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!Kk(this.state,e))return;let t=this.state;this.state={...this.state,...e},Vk(t)!==Vk(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Hk(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),Uk(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=fg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=Ek){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>Gk(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Ua.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(fg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Xk():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Xk():{selectedFilePath:es(Mk,`file`),selectedDiffPath:es(Nk,`diff`),selectedTerminalId:es(Pk,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){pg(e,{replace:!0}),ts(Mk,`file`,void 0,{replace:!0}),ts(Nk,`diff`,void 0,{replace:!0}),ts(Pk,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Qk(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Dk.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await tA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),pg({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Hd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Hd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){pg(Ud(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ts(Mk,`file`,e.selectedFilePath,{replace:!0}),ts(Nk,`diff`,e.selectedDiffPath,{replace:!0}),ts(Pk,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Vd(e.id);if(await this.restoreRouteFor(Ud(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=Zk(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=wg(e,{api:{runTerminalCommand:(e,n)=>ao.runTerminalCommand(e,n,t),listCommandRuns:e=>ao.listCommandRuns(e,t),getCommandRun:e=>ao.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){ts(Pk,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,vg(e)}closeSettings(){this.settingsSection=void 0,vg(void 0)}navigateSettings(e){this.settingsSection=e,vg(e)}restoreSettingsRoute(){this.settingsSection=_g()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await io.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:Gt(e,T.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new eu;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Wk(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):Yk(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await ao.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=Jk(e),r=Jk(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5989
|
+
`}};B([x({attribute:!1})],yk.prototype,`onClose`,void 0),B([x({attribute:!1})],yk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],yk.prototype,`workspace`,void 0),B([x()],yk.prototype,`machineId`,void 0),B([x({attribute:!1})],yk.prototype,`api`,void 0),B([S()],yk.prototype,`status`,void 0),B([S()],yk.prototype,`selectedChange`,void 0),B([S()],yk.prototype,`selectedDiff`,void 0),B([S()],yk.prototype,`loadingStatus`,void 0),B([S()],yk.prototype,`loadingDiff`,void 0),B([S()],yk.prototype,`error`,void 0),B([S()],yk.prototype,`bounds`,void 0),yk=B([b(`git-update-manager-panel`)],yk);function bk(){rm(()=>import(`./UnifiedDiffViewer-DDlEJGJ4.js`),[],import.meta.url)}function xk(e,t){let n=vs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function Sk(e){return e===`staged`?`Staged`:`Unstaged`}function Ck(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function wk(e){return e instanceof Error?e.message:String(e)}var Tk=900*1e3,Ek=750,Dk=[1e3,3e3,8e3,15e3,3e4],Ok={capture:!0},kk=`auto:on`,Ak=`auto:off`,jk=`theme:`,Mk=Qo(`core:workspace.files`),Nk=Qo(`core:workspace.git`),Pk=Qo(`core:workspace.terminal`),Fk=320,Ik=2,Lk=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Bo(),this.sessionUnread=new qf({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Dd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new wu,{notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Rs(()=>this.state,e=>{this.setState(e)},{api:ro,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ko(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Yo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Fd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nd),this.projects=new As(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Es(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ds(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new _s(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new af,this.realtime=new eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Bd,this.terminalSelection=new $d,this.appShell=new Oh(this),this.browserResume=new Ah({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Kh(this),this.panelResize=new Xh(this),this.navigationSections=new Uh(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=Rk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=fp()??cp,this.activeThemeId=sp,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=Vg(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=rA(),this.infoTabHidden=oA(),this.railOrder=pk()??[...sk],this.settingsSection=_g(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bo(void 0),this.sessionWarningVisibility=tp(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=Pg(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,mk(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?Mg(t.bounds,n,r):Ng(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=zg(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Bg(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=op(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=Vk(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=rp(this.sessionWarningVisibility,e===void 0?void 0:Wo(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=Bk(e,t);await this.updateComplete,!(!this.unreadConnected||Vk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);qk(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Jg(this.state.selectedProject?.name);this.windowTitleCleanup=Yg(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Bk(e,t);return Vk(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen}connectedCallback(){super.connectedCallback(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,Ok),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},Tk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,Ok),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!Kk(this.state,e))return;let t=this.state;this.state={...this.state,...e},Vk(t)!==Vk(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Hk(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),Uk(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=fg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=Ek){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>Gk(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Ua.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(fg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Xk():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Xk():{selectedFilePath:es(Mk,`file`),selectedDiffPath:es(Nk,`diff`),selectedTerminalId:es(Pk,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){pg(e,{replace:!0}),ts(Mk,`file`,void 0,{replace:!0}),ts(Nk,`diff`,void 0,{replace:!0}),ts(Pk,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Qk(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Dk.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await tA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),pg({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Hd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Hd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){pg(Ud(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ts(Mk,`file`,e.selectedFilePath,{replace:!0}),ts(Nk,`diff`,e.selectedDiffPath,{replace:!0}),ts(Pk,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Vd(e.id);if(await this.restoreRouteFor(Ud(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=Zk(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=wg(e,{api:{runTerminalCommand:(e,n)=>ao.runTerminalCommand(e,n,t),listCommandRuns:e=>ao.listCommandRuns(e,t),getCommandRun:e=>ao.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)){this.setState({error:`Machine not found for terminal command run`});return}this.openTerminal(n)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){ts(Pk,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,vg(e)}closeSettings(){this.settingsSection=void 0,vg(void 0)}navigateSettings(e){this.settingsSection=e,vg(e)}restoreSettingsRoute(){this.settingsSection=_g()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await io.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:Gt(e,T.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new eu;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Wk(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):Yk(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await ao.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=Jk(e),r=Jk(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5990
5990
|
<workspace-panel
|
|
5991
5991
|
id="workspace-panel"
|
|
5992
5992
|
.workspace=${e}
|
package/dist/client/index.html
CHANGED
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--pi-bg); color: var(--pi-text); }
|
|
54
54
|
body { min-height: 100dvh; }
|
|
55
55
|
</style>
|
|
56
|
-
<script type="module" crossorigin src="./assets/index-
|
|
56
|
+
<script type="module" crossorigin src="./assets/index-Bq-PmNe2.js"></script>
|
|
57
57
|
<link rel="modulepreload" crossorigin href="./assets/vendor-editor-core-vUi74DnD.js">
|
|
58
58
|
<link rel="modulepreload" crossorigin href="./assets/vendor-editor-languages-DoaXUodB.js">
|
|
59
59
|
<link rel="modulepreload" crossorigin href="./assets/vendor-terminal-D8k4UKM2.js">
|
package/package.json
CHANGED