@hyperdreamer/pi-webui 1.11.0 → 1.11.1
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/README.md +9 -0
- package/dist/client/assets/{CodeViewer-Jy1WSFR_.js → CodeViewer-C0XQ5fEe.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-iic0AurS.js → UnifiedDiffViewer-BGXZn_Bc.js} +1 -1
- package/dist/client/assets/{index-6NlIF1nJ.js → index-CkfjnumG.js} +8 -8
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -59,6 +59,15 @@ Then open:
|
|
|
59
59
|
http://localhost:8809
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
+
## Important: configure your model settings first
|
|
63
|
+
|
|
64
|
+
Before starting serious work, open **Settings → Model tiers** and **Settings → Utility models** for the machine where your sessions run. Treat both as core setup, not optional fine-tuning:
|
|
65
|
+
|
|
66
|
+
- **Model tiers** control the model and thinking level used for session work. Configure the six-rung `economy` through `frontier` ladder so Tiered sessions can route to the models you intend to use.
|
|
67
|
+
- **Utility models** are separate from session routing. They handle automatic titles, branch summaries, and context compaction, helping long-running work stay usable.
|
|
68
|
+
|
|
69
|
+
See the [configuration reference](docs/config.md) for complete details and examples.
|
|
70
|
+
|
|
62
71
|
## Core model
|
|
63
72
|
|
|
64
73
|
PI WEBUI organizes work like this:
|
|
@@ -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-CkfjnumG.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-CkfjnumG.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-C0XQ5fEe.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)}})}}var w={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`,modelTierSettings:`settings.modelTiers`,utilityModelSettings:`settings.utilityModels`,sessionsModelPolicy:`sessions.modelPolicy`,sessionsModelPolicyDefaults:`sessions.modelPolicyDefaults`,sessionsModelPolicyStarterSelection:`sessions.modelPolicyStarterSelection`,sessionsReorder:`sessions.reorder`},bt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],xt=[`lightweight`,`context`],St=1e3,Ct=1e3,wt=32*1024,Tt=8*1024,Et=1e4;function Dt(e,t=kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(At(e),n).toString()}function Ot(e,t=kt()){let n=new URL(Dt(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 kt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function At(e){return e.startsWith(`/`)?`.${e}`:e}async function T(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(Dt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(jt(e)??i.statusText)}return t(await i.json())}function jt(e){if(Mt(e))return typeof e.error==`string`?e.error:void 0}function Mt(e){return typeof e==`object`&&!!e}function Nt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Pt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Nt(e)}var Ft=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),It=/^sha256:[0-9a-f]{64}$/u,Lt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Rt=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function zt(e){if(!Wt(e)||Object.keys(e).some(e=>!Ft.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`||!It.test(n))&&!(typeof r!=`string`||!Bt(r))&&!(typeof i!=`string`||!Vt(i))&&Ut(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!Rt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Bt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Vt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Lt.test(e)}function Vt(e){if(e===``||e!==e.trim()||Ht(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Ht(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Ut(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Gt=Object.values(w),Kt=new Set(Gt);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder;function qt(e){return typeof e==`string`&&Kt.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function Jt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(qt)}var Yt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Xt(e){return Yt.some(t=>t===e)}function Zt(e){return e===void 0||e===``?`off`:e}function Qt(e,t){let n=t.length>=2?t:Yt,r=n.length-1,i=Zt(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function $t(e){return typeof e==`object`&&!!e}function D(e){if(!$t(e))throw Error(`Expected object response`);return e}function O(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function k(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function A(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function en(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function tn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function nn(e){if(!$t(e)||typeof e.kind!=`string`)throw Error(`Invalid memory snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid memory snapshot response`);return{kind:`data`,globalEntries:rn(e.globalEntries),projectEntries:rn(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function rn(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!$t(e)||typeof e.id!=`string`||typeof e.content!=`string`)throw Error(`Invalid memory snapshot response`);return{id:e.id,content:e.content,...typeof e.category==`string`?{category:e.category}:{},...typeof e.created==`string`?{created:e.created}:{},...typeof e.last==`string`?{last:e.last}:{},...typeof e.failureReason==`string`?{failureReason:e.failureReason}:{}}})}function an(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:en(t.messages),start:A(t,`start`),total:A(t,`total`)}}function on(e){let t=D(e);return M(sn)(t.machines)}function sn(e){let t=D(e),n=un(t,`kind`),r=k(t,`baseUrl`),i=dn(t,`status`),a=k(t,`statusMessage`);return{id:O(t,`id`),name:O(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:O(t,`createdAt`),updatedAt:O(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function cn(e){let t=D(e),n=dn(t,`status`),r=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Na(t.web)},...t.sessiond===void 0?{}:{sessiond:Na(t.sessiond)},...r===void 0?{}:{error:r}}}function ln(e){let t=D(e),n=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...P(`packageName`,k(t,`packageName`)),...P(`generatedAt`,k(t,`generatedAt`)),...t.components===void 0?{}:{components:ja(t.components)},...t.capabilities===void 0?{}:{capabilities:za(t.capabilities)},...n===void 0?{}:{error:n}}}function un(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function dn(e,t){let n=k(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 fn(e){let t=D(e);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),createdAt:O(t,`createdAt`)}}function pn(e){let t=D(e),n=k(t,`branch`);return{id:O(t,`id`),projectId:O(t,`projectId`),path:O(t,`path`),label:O(t,`label`),...n===void 0?{}:{branch:n},isMain:j(t,`isMain`),isGitRepo:j(t,`isGitRepo`),isGitWorktree:j(t,`isGitWorktree`),...P(`effectiveConfig`,mn(t.effectiveConfig))}}function mn(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,ia(e.uploads))}}}function hn(e){let t=D(e),n=k(t,`name`),r=Da(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=Da(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:rr(t,`manualOrder`);return{id:O(t,`id`),path:O(t,`path`),cwd:O(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:O(t,`created`),modified:O(t,`modified`),messageCount:A(t,`messageCount`),firstMessage:O(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o},...s===void 0?{}:{creationSource:s},...c===void 0?{}:{manualOrder:c}}}function gn(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:rr(t,`manualOrder`)}}function _n(e){let t=D(e);return{orderedSessions:M(gn)(t.orderedSessions)}}function vn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function yn(e){if(e!==void 0)return{id:O(D(e),`id`)}}function bn(e){let t=D(e),n=yn(t.dismiss);return{severity:vn(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function xn(e){return e===void 0?{}:{warnings:M(bn)(e)}}function Sn(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,Da(t.persisted,`persisted`)),isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:A(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(gr)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:_r(t.tokens),cost:A(t,`cost`),...ci(t.generation),...yr(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:On(t.modelPolicy)),...li(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...xn(t.warnings)}}function Cn(e){let t=Nn(e,`session model policy response`);if(Fn(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=Sn(t.session);if(!Object.hasOwn(t,`policy`)){let e=n.modelPolicy?.blockedReason;if(e===void 0||e.trim()===``)throw Error(`Expected non-blank string field: blockedReason`);return{contractVersion:1,session:n}}return{contractVersion:1,policy:wn(t.policy),session:n}}function wn(e){let t=Nn(e,`session model policy`);Fn(t,[`mode`,`exact`,`tier`],`session model policy`);let n=jn(t.mode),r=Mn(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:kn(t.exact),...P(`tier`,r)}}function Tn(e){let t=Nn(e,`starter model policy preference`);Fn(t,[`mode`,`tier`],`starter model policy preference`);let n=jn(t.mode),r=Mn(t,`starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered starter model policy preference requires a tier`);return{mode:n,...P(`tier`,r)}}function En(e){let t=Nn(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?Dn(t):Tn(t)}function Dn(e){let t=Nn(e,`confirmed starter model policy preference`);Fn(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=jn(t.mode),r=Mn(t,`confirmed starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered confirmed starter model policy preference requires a tier`);return{mode:n,exact:kn(t.exact),...P(`tier`,r)}}function On(e){let t=Nn(e,`session model policy status`);Fn(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=jn(t.mode),r=Mn(t,`session model policy status`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy status requires a tier`);return{mode:n,...P(`tier`,r),resolved:kn(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function kn(e){let t=Nn(e,`exact selection`);return Fn(t,[`model`,`thinkingLevel`],`exact selection`),{model:An(t.model),thinkingLevel:Ya(t,`thinkingLevel`)}}function An(e){let t=Nn(e,`model reference`);return Fn(t,[`provider`,`id`],`model reference`),{provider:Ya(t,`provider`),id:Ya(t,`id`)}}function jn(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function Mn(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!Yi(n))throw Error(`Invalid ${t} tier`);return n}function Nn(e,t){if(!Pn(e))throw Error(`Expected ${t} object`);return e}function Pn(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function Fn(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function In(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Ln(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function Rn(e){let t=D(e),n=rr(t,`catalogRevision`),r=er(t.sessions,Bn,Ct,`sessions`);if(Vn(r),Hn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Un(t,`catalogId`,512),catalogRevision:n,sessions:r}}function zn(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Un(t,`sessionId`,512),r=Un(t,`cwd`,wt),i=Wn(t,`catalogRevision`),a=t.unread===null?null:Bn(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:Un(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Bn(e){let t=D(e),n=Un(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:Un(t,`sessionId`,512),cwd:Un(t,`cwd`,wt),completionOrder:Wn(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 Hn(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 Un(e,t,n){let r=nr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Wn(e,t){let n=rr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Gn(e){let t=D(e),n=qn(t.summary),r=er(t.notifications,Jn,100,`notifications`);if(ir(r),ar(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==sr(r))throw Error(`Notification snapshot severity mismatch`);let i=Yn(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:nr(t,`daemonInstanceId`),catalogRevision:rr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Kn(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=qn(t.summary),r=Yn(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Xn(t.delta);if(i.kind===`cleared`&&!or(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:nr(t,`daemonInstanceId`),catalogRevision:rr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function qn(e){let t=D(e),n=rr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=rr(t,`discardedCount`),i=Qn(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:nr(t,`sessionId`),cwd:nr(t,`cwd`),inboxRevision:rr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Jn(e){let t=D(e),n=O(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=O(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=rr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:nr(t,`id`),message:n,truncated:j(t,`truncated`),severity:Zn(t.severity),receivedAt:r,order:i}}function Yn(e){let t=D(e);return{order:rr(t,`order`),overflowWatermark:rr(t,`overflowWatermark`)}}function Xn(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:Jn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=er(t.notificationIds,tr,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:$n(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Zn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Qn(e){return e===void 0?void 0:Zn(e)}function $n(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 er(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 tr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function nr(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function rr(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 ir(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 ar(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 or(e){return e.retainedCount===0&&e.discardedCount===0}function sr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function cr(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:tn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:pr(t.thresholds),projects:M(mr)(t.projects),totals:hr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function lr(e){let t=D(e);return{...cr(t),archivedSessionIds:tn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:tn(t.deletedSessionIds,`deletedSessionIds`)}}function ur(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:tn(t.archivedSessionIds,`archivedSessionIds`),failures:M(fr)(t.failures),generatedAt:O(t,`generatedAt`)}}function dr(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:tn(t.deletedSessionIds,`deletedSessionIds`),failures:M(fr)(t.failures),generatedAt:O(t,`generatedAt`)}}function fr(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function pr(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function mr(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function hr(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function gr(e){let t=D(e),n=O(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:O(t,`text`)}}function _r(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),total:A(t,`total`)}}function vr(e){let t=D(e);return{...P(`provider`,k(t,`provider`)),...P(`id`,k(t,`id`)),...P(`name`,k(t,`name`)),...P(`contextWindow`,N(t,`contextWindow`)),...P(`reasoning`,t.reasoning)}}function yr(e){return e===void 0?{}:{model:vr(e)}}function br(e){let t=D(e);return{models:M(vr)(t.models)}}function xr(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:Tn(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{...t.model===void 0?{}:{model:vr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(vr)(t.models),thinkingLevels:tn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Sr(e){let t=Nn(e,`version-two session defaults response`);if(Fn(t,[`starterModelPolicyContractVersion`,`model`,`thinkingLevel`,`models`,`thinkingLevels`,`starterModelPolicyPreference`,`starterModelPolicyPreferenceError`],`version-two session defaults response`),t.starterModelPolicyContractVersion!==2)throw Error(`Invalid starter model policy contract version`);let n=t.starterModelPolicyPreference===void 0?void 0:En(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{starterModelPolicyContractVersion:2,...t.model===void 0?{}:{model:vr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(vr)(t.models),thinkingLevels:tn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Cr(e){let t=Er(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=Er(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=wr(t);return{...t,providers:i}}function wr(e){let t=Er(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=k(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=k(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=Dr(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=Or(o,`models configuration provider headers`));let s=Dr(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=Dr(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=Er(e,`models configuration model`),n={id:O(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=O(t,`id`);let r=k(t,`name`);r!==void 0&&(n.name=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=uo(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=Dr(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=kr(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=N(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=N(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=Dr(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=Ar(u));let d=Dr(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function Er(e,t){if(!$t(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function Dr(e,t){if(e!==void 0)return Er(e,t)}function Or(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 kr(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 Ar(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 jr(e){if(D(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function Mr(e){let t=D(e);return{models:M(Nr)(t.models)}}function Nr(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function Pr(e){let t=D(e),n=j(t,`ok`),r=k(t,`error`),i=t.latencyMs===void 0?void 0:A(t,`latencyMs`),a=t.status===void 0?void 0:A(t,`status`),o=k(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 Fr(e){let t=D(e);return{skills:M(Ir)(t.skills)}}function Ir(e){let t=D(e),n=D(t.sourceInfo),r=k(n,`source`),i=k(n,`scope`);return{name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),baseDir:O(t,`baseDir`),disableModelInvocation:j(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:Lr(t.install)}}}function Lr(e){let t=D(e),n=k(t,`sourceType`),r=k(t,`skillsShUrl`),i=k(t,`skillPath`),a=k(t,`ref`),o=k(t,`versionHash`);return{package:O(t,`package`),scope:Rr(t.scope),source:O(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:j(t,`canCheckForUpdates`)}}function Rr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function zr(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Br(e){let t=D(e);return{results:M(Vr)(t.results)}}function Vr(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Hr(e){let t=D(e);return{updates:M(Ur)(t.updates)}}function Ur(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:Rr(t.scope),state:Wr(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Wr(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function Gr(e){let t=D(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=k(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:Ir(t.skill)},...n===void 0?{}:{output:n}}}function Kr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function qr(e){let t=D(e);return{levels:M(Kr)(t.levels)}}function Jr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Yr(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 Xr(e){let t=D(e),n=t.source===void 0?void 0:Yr(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function Zr(e){let t=D(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:O(t,`id`),name:O(t,`name`),authType:Jr(t.authType),status:Xr(t.status),...n===void 0?{}:{loginFlow:n}}}function Qr(e){let t=D(e);return{providers:M(Zr)(t.providers)}}function $r(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:ei(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...P(`error`,k(t,`error`)),...P(`auth`,ti(t.auth)),...P(`prompt`,ri(t.prompt)),...P(`select`,ai(t.select)),...P(`info`,oi(t.info))}}function ei(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ti(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,ni(t.deviceCode))}}function ni(e){if(e===void 0)return;let t=D(e);return{userCode:O(t,`userCode`),...P(`intervalSeconds`,N(t,`intervalSeconds`)),...P(`expiresInSeconds`,N(t,`expiresInSeconds`))}}function ri(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:ii(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,uo(t,`allowEmpty`))}}function ii(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function ai(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(Za)(t.options)}}function oi(e){if(e!==void 0)return M(e=>{let t=D(e);return{message:O(t,`message`),...P(`links`,t.links===void 0?void 0:M(si)(t.links))}})(e)}function si(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function ci(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,uo(t,`estimated`))}}}function li(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:fo(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:fo(t,`percent`)}}}function ui(e){let t=D(e),n=O(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:O(t,`name`),source:n,...P(`description`,k(t,`description`))}}function di(e){let t=D(e),n=O(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:O(t,`path`),kind:n}}function fi(e){let t=D(e);return{path:O(t,`path`),entries:M(pi)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function pi(e){let t=D(e),n=O(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:O(t,`name`),path:O(t,`path`),type:n,...P(`size`,N(t,`size`)),...P(`modifiedAt`,k(t,`modifiedAt`))}}function mi(e){let t=D(e),n=O(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:O(t,`path`),...P(`language`,k(t,`language`)),...P(`mediaType`,vi(t.mediaType)),...P(`mimeType`,k(t,`mimeType`)),encoding:n,size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),content:O(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function hi(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function gi(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function _i(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function vi(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function yi(e){let t=D(e);return{isGitRepo:j(t,`isGitRepo`),hash:O(t,`hash`),...P(`branch`,k(t,`branch`)),...P(`latestTag`,k(t,`latestTag`)),...P(`upstream`,k(t,`upstream`)),...P(`ahead`,N(t,`ahead`)),...P(`behind`,N(t,`behind`)),files:M(bi)(t.files)}}function bi(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:xi(t.index),workingTree:xi(t.workingTree)}}function xi(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 Si(e){let t=D(e);return{...P(`path`,k(t,`path`)),staged:j(t,`staged`),hash:O(t,`hash`),diff:O(t,`diff`),truncated:j(t,`truncated`)}}function Ci(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),name:O(t,`name`),createdAt:O(t,`createdAt`),exited:j(t,`exited`),...P(`exitCode`,N(t,`exitCode`)),...P(`commandRunId`,k(t,`commandRunId`))}}function wi(e){let t=D(e);return{id:O(t,`id`),origin:O(t,`origin`),projectId:O(t,`projectId`),workspaceId:O(t,`workspaceId`),terminalId:O(t,`terminalId`),title:O(t,`title`),command:O(t,`command`),status:Ti(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:Ei(t.metadata,`metadata`)}}function Ti(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Ei(e,t){let n=D(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function Di(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function Oi(e){let t=D(e);return{workspaces:M(Di)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function ki(e){let t=Zi(e,`utility model settings response`),n=Object.keys(t).find(e=>!Mi(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return Ai(t);if(t.contractVersion===2)return ji(t);throw Error(`Invalid utility model settings contract version`)}function Ai(e){let t=k(e,`configError`);return{contractVersion:1,settings:Ni(e.settings),models:M(Ii)(e.models),slots:Ri(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function ji(e){let t=k(e,`configError`);return{contractVersion:2,settings:Pi(e.settings),models:M(Li)(e.models),slots:Ri(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Mi(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function Ni(e){let t=Zi(e,`settings`),n=Object.keys(t).find(e=>!Bi(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Gi(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Gi(t.context,`settings.context`))}}function Pi(e){let t=Zi(e,`settings`),n=Object.keys(t).find(e=>!Bi(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Fi(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Fi(t.context,`settings.context`))}}function Fi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid utility model binding field: ${t}.${r}`);let i=nr(n,`provider`),a=nr(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Xt(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function Ii(e){let t=Zi(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);return{model:Gi(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Li(e){let t=Zi(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`&&e!==`thinkingLevels`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);let r=tn(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Xt(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:Gi(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function Ri(e){let t=Vi(e,`slots`);return{lightweight:zi(t.lightweight,`slots.lightweight`),context:zi(t.context,`slots.context`)}}function zi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid utility model validation field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Bi(e){return xt.some(t=>t===e)}function Vi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>!Bi(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=xt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Hi(e){let t=D(e);if(t.contractVersion!==1)throw Error(`Invalid model-tier settings contract version`);let n=t.ladder===void 0?void 0:Ui(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Ki)(t.models),rows:qi(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function Ui(e){let t=Xi(e,`ladder`);return{economy:Wi(t.economy,`ladder.economy`),fast:Wi(t.fast,`ladder.fast`),standard:Wi(t.standard,`ladder.standard`),advanced:Wi(t.advanced,`ladder.advanced`),capable:Wi(t.capable,`ladder.capable`),frontier:Wi(t.frontier,`ladder.frontier`)}}function Wi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>e!==`model`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid model-tier entry field: ${t}.${r}`);return{model:Gi(n.model,`${t}.model`),thinkingLevel:nr(n,`thinkingLevel`)}}function Gi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`);if(r!==void 0)throw Error(`Invalid model reference field: ${t}.${r}`);return{provider:nr(n,`provider`),id:nr(n,`id`)}}function Ki(e){let t=Zi(e,`models`);return{model:Gi(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:tn(t.thinkingLevels,`models.thinkingLevels`)}}function qi(e){let t=Xi(e,`rows`);return{economy:Ji(t.economy,`rows.economy`),fast:Ji(t.fast,`rows.fast`),standard:Ji(t.standard,`rows.standard`),advanced:Ji(t.advanced,`rows.advanced`),capable:Ji(t.capable,`rows.capable`),frontier:Ji(t.frontier,`rows.frontier`)}}function Ji(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid model-tier row field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Yi(e){return bt.some(t=>t===e)}function Xi(e,t){let n=Zi(e,t),r=Object.keys(n).find(e=>!Yi(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=bt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function Zi(e,t){if(!$t(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function Qi(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:$i(t.config),effectiveConfig:$i(t.effectiveConfig),envOverrides:la(t.envOverrides)}}function $i(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,ta(t.allowedHosts)),...P(`shortcuts`,sa(t.shortcuts)),...P(`plugins`,ca(t.plugins)),...P(`pathAccess`,na(t.pathAccess)),...P(`uploads`,ia(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,ea(t.agent)),...P(`spawnSessions`,uo(t,`spawnSessions`)),...P(`subsessions`,uo(t,`subsessions`))}}function ea(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function ta(e){if(e!==void 0){if(e===!0)return!0;if(aa(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function na(e){if(e===void 0)return;if(!$t(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,ra(t,`pathAccess.allowedPaths`))}}function ra(e,t){if(e!==void 0){if(oa(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function ia(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function aa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function oa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function sa(e){if(e!==void 0){if(!$t(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 ca(e){if(e!==void 0){if(!$t(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!$t(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&&(!$t(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function la(e){let t=D(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),agentCommand:uo(t,`agentCommand`)??!1,agentDir:uo(t,`agentDir`)??!1,...ua(t),agentSessionDir:uo(t,`agentSessionDir`)??!1}}function ua(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 da(e){let t=D(e);return{packages:M(pa)(t.packages)}}function fa(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:ma(t.scope),i=Da(t.removed,`removed`);return{action:ha(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(pa)(t.packages)}}function pa(e){let t=D(e);return{source:O(t,`source`),scope:ma(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function ma(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function ha(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function ga(e){let t=D(e);return{packages:M(_a)(t.packages),totals:ba(t.totals),diagnostics:M(Ca)(t.diagnostics)}}function _a(e){let t=D(e);return{source:O(t,`source`),scope:va(t.scope),filtered:j(t,`filtered`),disabled:j(t,`disabled`),...P(`installedPath`,k(t,`installedPath`)),...P(`packageName`,k(t,`packageName`)),...P(`version`,k(t,`version`)),...P(`configuredVersion`,k(t,`configuredVersion`)),counts:ba(t.counts),resources:M(xa)(t.resources),status:ya(t.status)}}function va(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function ya(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function ba(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function xa(e){let t=D(e);return{kind:Sa(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function Sa(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Ca(e){let t=D(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`))}}function wa(e){let t=D(e);return{plugins:M(Ta)(t.plugins)}}function Ta(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:Ea(t.scope),machineSpecific:Da(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function Ea(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Da(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Oa(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Aa(t.components),release:Fa(t.release),commands:Ia(t.commands),messages:M(La)(t.messages)}}function ka(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:ja(t.components),capabilities:za(t.capabilities)}}function Aa(e){let t=D(e);return{web:Na(t.web),sessiond:Na(t.sessiond)}}function ja(e){let t=D(e);return{web:Ma(t.web),sessiond:Ma(t.sessiond)}}function Ma(e){let t=D(e),n=Ra(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:zt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),available:j(t,`available`),capabilities:za(t.capabilities),...P(`activeAgentProfile`,i),...P(`error`,k(t,`error`))}}function Na(e){let t=D(e);return{component:Ra(t.component),label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),...P(`installedVersion`,k(t,`installedVersion`)),stale:j(t,`stale`),available:j(t,`available`),...P(`installation`,Pa(t.installation)),...P(`error`,k(t,`error`))}}function Pa(e){if(e===void 0)return;let t=D(e),n=O(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,...P(`path`,k(t,`path`)),...P(`source`,k(t,`source`)),...r===void 0?{}:{scope:r},...P(`npmRoot`,k(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Fa(e){let t=D(e);return{packageName:O(t,`packageName`),...P(`latestVersion`,k(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...P(`checkedAt`,k(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...P(`error`,k(t,`error`))}}function Ia(e){let t=D(e);return{...P(`update`,k(t,`update`)),...P(`restart`,k(t,`restart`)),...P(`restartWeb`,k(t,`restartWeb`)),...P(`restartSessiond`,k(t,`restartSessiond`)),...P(`status`,k(t,`status`))}}function La(e){let t=D(e);return{id:O(t,`id`),severity:Ba(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function Ra(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function za(e){let t=Jt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function Ba(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Va(e){let t=D(e),n=O(t,`type`);if(n===`unsupported`)return{type:n,message:O(t,`message`)};if(n===`select`)return{type:n,requestId:O(t,`requestId`),title:O(t,`title`),options:M(Za)(t.options)};if(n===`tree`)return{type:n,tree:Ha(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...Qa(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Ha(e){let t=D(e),n=M(Ua)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Ja(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Xa(t.activePathIds,`activePathIds`)}}function Ua(e){let t=D(e);return{id:Ya(t,`id`),parentId:Ja(t,`parentId`),kind:Wa(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function Wa(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Ga(e){let t=D(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){qa(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 qa(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function Ka(e){let t=D(e);return j(t,`cancelled`)?(qa(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:hn(t.session)}}function qa(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Ja(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 Ya(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Xa(e,t){let n=tn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Za(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function Qa(e){return e===void 0?{}:{session:hn(e)}}function $a(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function eo(e){let t=D(e);return M(to)(t.attachments)}function to(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function no(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function ro(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function io(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ao(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:tn(t.sessionIds,`sessionIds`),r=N(t,`archivedCount`),i=N(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function oo(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function so(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function co(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function lo(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function uo(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function N(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function fo(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 P(e,t){return t===void 0?{}:{[e]:t}}function po(e){let t=D(e),n=D(t.memory),r=D(t.network);return{generatedAt:O(t,`generatedAt`),memory:{totalBytes:A(n,`totalBytes`),usedBytes:A(n,`usedBytes`),freeBytes:A(n,`freeBytes`),usagePercent:A(n,`usagePercent`)},network:go(r)}}function mo(e){let t=D(e),n=D(t.os),r=D(t.cpu),i=D(t.memory),a=D(t.network),o=t.gpu,s;if(o!=null){let e=D(o),t={name:O(e,`name`)},n=k(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=N(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=N(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=N(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=N(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:O(t,`generatedAt`),os:{platform:O(n,`platform`),release:O(n,`release`),arch:O(n,`arch`),uptimeSeconds:A(n,`uptimeSeconds`)},cpu:{model:O(r,`model`),cores:A(r,`cores`),usagePercent:A(r,`usagePercent`)},memory:{totalBytes:A(i,`totalBytes`),usedBytes:A(i,`usedBytes`),freeBytes:A(i,`freeBytes`),usagePercent:A(i,`usagePercent`)},network:ho(a)};s!==void 0&&(c.gpu=s);let l=k(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=k(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function ho(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:tn(e.localIpv4Addresses,`localIpv4Addresses`),...go(e)},n=k(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=k(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function go(e){let t={},n=N(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=N(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function _o(e){return typeof e==`string`?e:e.id}function vo(e){return typeof e==`string`?void 0:e.cwd}function yo(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 bo(e,t,n=`local`){let r=new URLSearchParams,i=vo(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(_o(e))}/messages${a===``?``:`?${a}`}`}function xo(e,t=`local`){let n=new URLSearchParams,r=vo(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(_o(e))}/export${i===``?``:`?${i}`}`}function So(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`),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function Co(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function wo(e){return typeof e==`string`?e:e.id}function To(e){return typeof e==`string`?void 0:e.cwd}function Eo(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(wo(e))}`}function I(e,t,n=`local`){return`${Eo(e,n)}/${t}`}function Do(e,t,n=`local`){return`${I(e,t,n)}${ko(e)}`}function Oo(e,t=`local`){return`${Eo(e,t)}${ko(e)}`}function ko(e){let t=To(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=To(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ao(e){return JSON.stringify({sessions:e.map(jo)})}function jo(e){let t=wo(e),n=To(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Mo(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var No={piWebUiStatus:(e=`local`)=>T(Mo(e),Oa),checkForUpdates:(e=`local`)=>T(`${Mo(e)}?refresh=1`,Oa,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,ka),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,mo),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,po,{cache:`no-store`})},Po={machines:()=>T(`api/machines`,on),addMachine:e=>T(`api/machines`,sn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>T(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>T(`api/machines/${encodeURIComponent(e)}/health`,cn),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,ln,t?{cache:`no-store`}:{})};function Fo(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var Io={snapshot:(e,t=`local`)=>T(Fo(e,t),nn,{cache:`no-store`})};function Lo(e){return e===void 0?`api/config`:`${F(e)}/config`}function Ro(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var zo={config:e=>T(Lo(e),Qi),saveConfig:(e,t)=>T(Lo(t),Qi,{method:`PUT`,body:JSON.stringify({config:e})})},Bo={plugins:e=>T(Ro(e),wa)};function Vo(e=`local`){return`${F(e)}/models-config`}var Ho={config:(e=`local`)=>T(Vo(e),Cr),save:(e,t=`local`)=>T(Vo(t),jr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>T(`${Vo(t)}/test`,Pr,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${Vo(t)}/discover`,Mr,{method:`POST`,body:JSON.stringify(e)})};function Uo(e=`local`){return`${F(e)}/model-tiers`}var Wo={settings:(e=`local`)=>T(Uo(e),Hi),save:(e,t=`local`)=>T(Uo(t),Hi,{method:`PUT`,body:JSON.stringify({ladder:e})})};function Go(e=`local`){return`${F(e)}/utility-models`}function Ko(e,t){if(t===2)return e;let n={};for(let t of xt){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let r=e[t];r===null?n[t]=null:r!==void 0&&(n[t]={provider:r.provider,id:r.id})}return n}var qo={settings:(e=`local`)=>T(Go(e),ki),save:(e,t,n=`local`)=>T(Go(n),ki,{method:`PUT`,body:JSON.stringify({settings:Ko(e,t)})})};function Jo(e=`local`){return`${F(e)}/skills`}function Yo(e,t=`local`){return`${Jo(t)}?${new URLSearchParams({cwd:e}).toString()}`}var Xo={list:(e,t=`local`)=>T(Yo(e,t),Fr),toggle:(e,t=`local`)=>T(Jo(t),zr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${Jo(t)}/search`,Br,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${Jo(t)}/install`,zr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${Jo(t)}/check`,Hr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${Jo(t)}/update`,Gr,{method:`POST`,body:JSON.stringify(e)})};function Zo(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Qo={packages:e=>T(Zo(``,e),da),install:(e,t)=>{let n={source:e};return T(Zo(`install`,t),fa,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T(Zo(`remove`,n),fa,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T(Zo(`update`,t),fa,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function $o(e=`local`){return`${F(e)}/package-plugins`}function es(e,t=`local`){return`${$o(t)}?${new URLSearchParams({cwd:e}).toString()}`}var ts={list:(e,t=`local`)=>T(es(e,t),ga),mutate:(e,t=`local`)=>T($o(t),ga,{method:`POST`,body:JSON.stringify(e)})},ns={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,Oi)},rs={projects:(e=`local`)=>T(`${F(e)}/projects`,M(fn)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,fn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,no,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(di))},is={workspaces:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(pn)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,wi,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,fi),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,mi),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 T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,hi,{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 T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,gi,{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`),T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,_i,{method:`POST`})}},as={sessions:(e,t=`local`)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(hn)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),_n,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,Rn,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return T(I(e,`unread/acknowledge`,r),Rn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(Do(e,`notifications`,t),Gn),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),Gn,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),Gn,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,hn,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,hn,{method:`POST`,body:JSON.stringify({cwd:e,creationSource:`session-list-plus`,initialModelPolicy:t})}),sessionDefaults:(e,t=`local`)=>T(`${F(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,xr),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,Sr)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,xr,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,cr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,lr,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,lr,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,ur,{method:`POST`,body:Ao(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,dr,{method:`POST`,body:Ao(e)}),messages:(e,t,n=`local`)=>T(bo(e,t,n),an),status:(e,t=`local`)=>T(Do(e,`status`,t),Sn),systemPrompt:(e,t=`local`)=>T(Do(e,`system-prompt`,t),Ln),streamSnapshot:(e,t=`local`)=>T(Do(e,`stream-snapshot`,t),In),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),Sn,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),Sn,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(Do(e,`model-policy`,t),Cn),rememberCurrentModelPolicy:(e,t=`local`)=>T(Do(e,`model-policy/remember`,t),Dn,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),Cn,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(Do(e,`models`,t),br),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),Sn,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),Sn,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(Do(e,`thinking-levels`,t),qr),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),Sn,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),Sn,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(Do(e,`commands`,t),M(ui)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),$a,{method:`POST`,body:L(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>T(I(e,`attachments`,n),eo,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),$a,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),Va,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),Va,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),Ga,{method:`POST`,body:L(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>T(I(e,`messages/edit-from-here`,n),Ga,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),Ka,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),ro,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),io,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),ao,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),ao,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),oo,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Oo(e,t),so,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),co,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),lo,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),hn,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),hn,{method:`POST`,body:L(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 T(`${F(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Qr)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,$a,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,$r,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,$a,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,$r,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,$r),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,$r,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,$r,{method:`POST`})},os={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(Ci)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ci,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,no,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,no,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,Ci,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,wi,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs${cs(e)}`,M(wi)),getCommandRun:(e,t=`local`)=>ss(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,wi,{method:`POST`})};async function ss(e,t){let n=await fetch(Dt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(ls(e)??n.statusText)}return wi(await n.json())}}function cs(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 ls(e){if(!us(e))return;let t=e.error;return typeof t==`string`?t:void 0}function us(e){return typeof e==`object`&&!!e}var ds={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?T(`${F(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,M(di)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(di)))}},fs={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,yi),gitDiff:(e,t,n,r=`local`)=>T(yo(r,e,t,n),Si)},R={...No,...Po,...Io,...Wo,utilityModels:qo,...zo,...Bo,...Qo,...ts,...ns,...rs,...is,...as,...os,...ds,...fs};function ps(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(Ot(`${gs(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function ms(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(Ot(`${gs(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function hs(e=`local`){return new WebSocket(Ot(`${gs(e)}/events`))}function gs(e){return`api/machines/${encodeURIComponent(e)}`}var _s=`.pi-webui/uploads`,vs=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},ys=class extends Error{constructor(e,t){super(As(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function bs(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function xs(e,t){return e?.uploads?.defaultFolder??t}function Ss(e,t){let n=Ns(e,`upload destination`,{allowEmpty:!0}),r=Ns(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Cs(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`,So(e,t,n.path,Es(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Ds(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(hi(Fs(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Is(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new vs(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function ws(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Ss(i,e.name),loaded:0,total:e.size,percent:ks(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Os(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 vs;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Cs(e,t,{path:p.path,file:f},{...Ts(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(Ms(e,c))throw e;let t=js(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 ys(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Ts(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 Es(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Ds(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ks(e.loaded,n),lengthComputable:e.lengthComputable}}function Os(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:ks(i,r),done:n}}function ks(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function As(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function js(e){return e instanceof Error?e.message:String(e)}function Ms(e,t){return t.requested||e instanceof vs}function Ns(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Ps(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 Ps(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Fs(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Is(e){let t=Ls(e);return Rs(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Ls(e){try{return Fs(e)}catch{return}}function Rs(e){return typeof e==`object`&&!!e}function zs(e){return e.closesActionPalette===!0}function Bs(e){return{mode:e.mode,exact:yc(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Vs(e){let t=Hs(e);if(t.mode!==`tiered`||t.tier!==void 0)return t;let n=e.catalog?.rows;return n===void 0||!Object.hasOwn(n,`standard`)||!n.standard.valid?t:{...t,tier:`standard`}}function Hs(e){if(e.policy!==void 0)return Bs(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:yc(t)}}function Us(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!vc(t)||!vc(n))&&vc(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function Ws(e){let t=Us(e)??lc(),n=e.starterModelPolicyPreference;return oc(e)?sc(n)?{mode:n.mode,exact:yc(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:yc(t),tier:`standard`}:ac(n,t,n.mode):ac(n,t,`exact`)}function Gs(e,t){let n=Us(t);return n===void 0||e.mode===`tiered`||qs(e.exact,n)?e:{...e,exact:yc(n)}}function Ks(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function qs(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function Js(e,t){return{...e,mode:`tiered`,tier:t}}function Ys(e){return{...e,mode:`exact`}}function Xs(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function Zs(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function Qs(e,t){if(e.mode===`exact`)return nc(e.exact,t.models)?{mode:`exact`,exact:yc(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!hc(t)||!gc(t,n)))return{mode:`tiered`,tier:n}}function $s(e,t){return t!==void 0&&Qs(e,t)!==void 0}function ec(e,t,n){let r=uc(e);if(cc(t)||e.mode!==`tiered`||fc(e.exact)||!pc(e.tier)||!hc(n)||!gc(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!fc(i)?r:{...r,exact:yc(i)}}function tc(e,t){let n=e.mode===`exact`?rc(e.exact,t):ic(e,t);if(n.kind===`blocked`)return n;let r=dc(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:yc(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:yc(n.resolved)}:{kind:`blocked`,reason:r}}function nc(e,t){return dc(e)===void 0&&t.find(t=>_c(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function rc(e,t){let n=dc(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>_c(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:yc(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function ic(e,t){let n=e.tier;if(!pc(n))return{kind:`blocked`,reason:mc(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:mc(r,t)};let i=t.ladder?.[n];return i===void 0||!fc(i)?{kind:`blocked`,reason:mc(r,t)}:{kind:`ready`,resolved:yc(i)}}function ac(e,t,n){return{mode:e?.mode??n,exact:yc(t),...e?.tier===void 0?{}:{tier:e.tier}}}function oc(e){return`starterModelPolicyContractVersion`in e}function sc(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function cc(e){return oc(e)&&sc(e.starterModelPolicyPreference)}function lc(){return{model:{provider:``,id:``},thinkingLevel:``}}function uc(e){return{mode:e.mode,exact:yc(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function dc(e){return fc(e)?void 0:`Choose a provider, model, and thinking level before starting`}function fc(e){return vc(e.model.provider)&&vc(e.model.id)&&vc(e.thinkingLevel)}function pc(e){return e!==void 0&&bt.includes(e)}function mc(e,t){return e?.reason!==void 0&&vc(e.reason)?e.reason:t.configError!==void 0&&vc(t.configError)?t.configError:`Selected model tier is unavailable`}function hc(e){let t=e.ladder;return t!==void 0&&bt.every(e=>Object.hasOwn(t,e))}function gc(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function _c(e,t){return e.provider===t.provider&&e.id===t.id}function vc(e){return e.trim()!==``}function yc(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function bc(e){return{kind:`policy-blocked`,scope:e}}function xc(e,t,n){return{kind:e,message:t,scope:n}}function Sc(e,t,n){if(e===void 0||!wc(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function Cc(e,t,n){return wc(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function wc(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var Tc={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},Ec=Yt;function Dc(e){return`${e.provider}/${e.id}`}function Oc(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${Dc(e.model)} · ${t}`}var kc={off:`No reasoning`,minimal:`Very brief reasoning (~1k tokens)`,low:`Light reasoning (~2k tokens)`,medium:`Moderate reasoning (~8k tokens)`,high:`Deep reasoning (~16k tokens)`,xhigh:`Maximum reasoning (~32k tokens)`};function Ac(e){let t=new Set(e.supported),n=new Set,r=[];for(let t of[...e.supported,...e.all])n.has(t)||(n.add(t),r.push(t));let i=e=>{let t=Ec.findIndex(t=>t===e);return t===-1?Ec.length:t};return r.map((e,t)=>({level:e,index:t})).sort((e,t)=>{let n=i(e.level)-i(t.level);return n===0?e.index-t.index:n}).map(({level:n})=>({level:n,supported:t.has(n),selected:n===e.selected,...kc[n]===void 0?{}:{description:kc[n]}}))}function jc(){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,memory:{kind:`loading`},selectedTerminalId:void 0,error:``}}function Mc(){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:[],modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0,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,memory:{kind:`loading`},activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Nc(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Pc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Fc(e,t){return`${e}:${t}`}function Ic(e,t){return`${e}:${t}`}function z(e){return e.selectedMachine?.id??`local`}var Lc=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}},Rc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Lc,this.api=n.api??ns,this.onActivityApplied=n.onActivityApplied}refresh(e=z(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,zc(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=z(this.getState())){let n=this.getState(),r=z(n)===t,i=Bc(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},...z(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function zc(e){let t={};for(let n of e.workspaces)Pc(n)&&(t[n.cwd]=n);return t}function Bc(e,t){let n={...e};return Pc(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Vc=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??R,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Uc(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:z(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,z(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:z(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,z(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||Hc(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Hc(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:z(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=z(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`?Hc(n.flow):void 0,a=Hc(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=Hc(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||Hc(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Hc(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=z(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(z(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Hc(e){return e.prompt?.requestId??e.select?.requestId}function Uc(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 Wc(e){return e.replaceAll(`:`,`.`)}function Gc(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 Kc(e,t){let n=Gc(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function qc(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));Jc(i,r)}function Jc(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 Yc(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Ss(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:tl(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:tl(0,n),status:`uploading`,startedAt:e.startedAt}}function Xc(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 Zc(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=el(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function Qc(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,...el(r),status:`error`,error:t,completedAt:n}}function $c(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,...el(r),status:`cancelled`,error:n,completedAt:t}}function el(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function tl(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var nl=Wc(`core:workspace.files`),rl=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??R,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??ws,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=z(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:sl(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,z(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`}),qc(nl,`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,z(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(il(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),qc(nl,`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=z(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=Yc({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($c(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:sl(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(Xc(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(Zc(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 ys)||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(al(t)){let e=$c(n,this.now());return this.setUploadBatch(e),e}let r=ol(t),i=Qc(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&&z(t)===e.machineId}};function il(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function al(e){return e instanceof vs}function ol(e){return e instanceof Error?e.message:String(e)}function sl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var cl=Wc(`core:workspace.git`),ll=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=z(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await R.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}),qc(cl,`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`}),qc(cl,`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=z(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([R.gitDiff(n.id,r.id,{path:e},i),R.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([z(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return z(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}},ul=3e4,dl={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},fl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Io.snapshot,this.timer=n.timer??dl,this.pollIntervalMs=n.pollIntervalMs??ul}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({memory:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=pl(n);this.setState({memory:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().memory;if(t.kind===`data`){this.setState({memory:{...t,refreshError:e}});return}this.setState({memory:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=z(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function pl(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function ml(e){let t=[],n=[];for(let r of e)bl(r.index)&&t.push(yl(r,`staged`,r.index)),xl(r.workingTree)&&n.push(yl(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function hl(e){let t=ml(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function gl(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 _l(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 vl(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function yl(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function bl(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function xl(e){return e!==`unmodified`&&e!==`ignored`}var Sl=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 R.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:wl(this.getState().machineActivities,r),machineRuntimes:wl(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,...jc()}),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 R.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 R.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:Cl(this.getState().machineStatuses,e.id),machineRuntimes:Cl(this.getState().machineRuntimes,e.id),machineActivities:Cl(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 R.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 R.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 R.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=>R.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=>R.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 Cl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function wl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Tl=`~/workspace`,El=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??R,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=z(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(z(this.getState())!==e)return;let n;if(t.length===0){if(n=await this.api.addProject(Tl,void 0,!0,e),z(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))),a=this.getState().selectedProject,o=a!==void 0&&t.some(e=>e.id===a.id&&e.path!==a.path);this.setState({projects:t,workspacesByProjectId:i}),o&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),n!==void 0&&await this.workspaces.selectProject(n)}catch(t){z(this.getState())===e&&this.setState({error:String(t)})}finally{z(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=z(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(z(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){z(this.getState())===n&&this.setState({error:String(e)})}}async closeProject(e){let t=z(this.getState());try{if(await this.api.closeProject(e,t),z(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){z(this.getState())===t&&this.setState({error:String(e)})}}},Dl=5e3,Ol=`reconcile selected project catalog`,kl={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Al=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??is.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??kl,this.pollIntervalMs=t.pollIntervalMs??Dl,this.onBackgroundError=t.onBackgroundError,this.captureTopologyRequest=t.captureTopologyRequest}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}let n=this.retargetScope(t);this.inFlight===void 0&&(!n&&this.pollTimer!==void 0||this.scheduleNext(t,this.generation))}refresh(){if(!this.observing)return Promise.resolve();let e=this.currentScope();if(e===void 0)return this.invalidateScope(),Promise.resolve();this.retargetScope(e),this.clearPollTimer();let t=this.generation,n=this.inFlight;return n===void 0?this.startRequest(e,t):n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t)}dispose(){this.observing=!1,this.invalidateScope()}retargetScope(e){return this.scope?.key===e.key?(this.scope=e,!1):(this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=e,this.generation+=1,!0)}startRequest(e,t){let n=this.inFlight;if(n!==void 0)return n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t);let r=++this.nextRequestId,i,a=new Promise(e=>{i=e});if(i===void 0)throw Error(`Project catalog request promise was not initialized`);return this.inFlight={generation:t,requestId:r,scopeKey:e.key,promise:a},this.load(e,t,r).then(i,i),a}async load(e,t,n){try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:e.project.id,projectPath:e.project.path}),r=await this.listWorkspaces(e.project.id,e.machineId);if(!this.isCurrent(e,t))return;await this.applySnapshot({machineId:e.machineId,project:e.project,workspaces:r,...n===void 0?{}:{topologyRequest:n}})}catch(n){this.isCurrent(e,t)&&this.reportBackgroundError(n)}finally{this.finishRequest(n)}}finishRequest(e){if(this.inFlight?.requestId!==e)return;this.inFlight=void 0;let t=this.queuedImmediateRefresh;if(t!==void 0){if(this.queuedImmediateRefresh=void 0,this.isCurrent(t.scope,t.generation)){this.startRequest(t.scope,t.generation).then(()=>{t.resolve()},()=>{t.resolve()});return}t.resolve()}let n=this.scope;n!==void 0&&this.isCurrent(n,this.generation)&&this.scheduleNext(n,this.generation)}queueImmediateRefresh(e,t){let n=this.queuedImmediateRefresh;if(n?.generation===t&&n.scope.key===e.key)return n.promise;this.clearQueuedImmediateRefresh();let r,i=new Promise(e=>{r=e});if(r===void 0)throw Error(`Queued project catalog refresh promise was not initialized`);return this.queuedImmediateRefresh={generation:t,scope:e,promise:i,resolve:r},i}scheduleNext(e,t){this.isCurrent(e,t)&&(this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.isCurrent(e,t)||this.inFlight!==void 0)&&this.startRequest(e,t)},this.pollIntervalMs))}stopObserving(){this.observing=!1,this.invalidateScope()}invalidateScope(){this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}clearQueuedImmediateRefresh(){let e=this.queuedImmediateRefresh;this.queuedImmediateRefresh=void 0,e?.resolve()}currentScope(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=z(e);return{key:JSON.stringify([n,t.id,t.path]),machineId:n,project:t}}isCurrent(e,t){return!this.observing||t!==this.generation||this.scope?.key!==e.key?!1:this.currentScope()?.key===e.key}reportBackgroundError(e){if(this.onBackgroundError!==void 0)try{this.onBackgroundError(Ol,e)}catch{}}};function jl(e,t){return t[e.path]}function Ml(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Nl(e,t,n){return Il(Ll(e,t,n))}function Pl(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Fl(e){return Il(Object.values(e??{}))}function Il(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ll(e,t,n){return Object.values(n).filter(n=>Pl(e,t,n.cwd))}var Rl=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??is,this.onProjectTopology=n.onProjectTopology,this.captureTopologyRequest=n.captureTopologyRequest,this.onError=n.onError}handleActivityApplied(e){return z(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return z(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(z(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!zl(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=this.captureTopologyRequest?.({machineId:e.machineId,projectId:t.id,projectPath:t.path}),r=await this.api.workspaces(t.id,e.machineId);await this.applyProjectWorkspaces(e,t,r,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&&!zl(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(z(this.getState()))}async applyProjectWorkspaces(e,t,n,r){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let i=this.getState();if(i.projects.find(e=>e.id===t.id)?.path===t.path&&!(r===void 0&&i.workspacesByProjectId[t.id]!==t.startingWorkspaces)){if(this.onProjectTopology!==void 0){await this.onProjectTopology({machineId:e.machineId,projectId:t.id,projectPath:t.path,workspaces:n,...r===void 0?{}:{topologyRequest:r}});return}this.setState({workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:n}})}}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&z(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Pc).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 zl(e,t,n){return e.some(e=>Pl(e,t[e.id]??[],n))}var Bl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??No,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=z(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=z(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}),Vl(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 z(this.getState())===e&&t===this.requestSequence}};function Vl(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 Hl=`pi-webui:cached-new-sessions:v1`,Ul=`browserCachedNew`,Wl=`local`;function Gl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Kl(e,t=Wl,n=Gl()){if(e.messageCount!==0||e.archived===!0)return;let r=Ql(n).filter(n=>n.id!==e.id||n.machineId!==t);$l([ql(e,t),...r],n)}function ql(e,t=Wl){return{...e,browserCachedNew:!0,machineId:t}}function Jl(e,t=Wl,n=Gl()){$l(Ql(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Yl(e,t,n=Wl,r=Gl()){let i=new Set(t.map(e=>e.id)),a=Ql(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&$l(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Xl(e){return e!==void 0&&tu(e)&&e.browserCachedNew===!0}function Zl(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:Wl},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function Ql(e=Gl()){try{let t=e?.getItem(Hl);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>eu(e)):[]}catch{return[]}}function $l(e,t=Gl()){try{e.length===0?t?.removeItem(Hl):t?.setItem(Hl,JSON.stringify(e))}catch{}}function eu(e){if(!nu(e))return[];let t=ru(e,`id`),n=ru(e,`path`),r=ru(e,`cwd`),i=ru(e,`created`),a=ru(e,`modified`),o=ru(e,`firstMessage`),s=au(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=iu(e,`name`),l=iu(e,`parentSessionPath`),u=iu(e,`machineId`)??Wl,d=e.creationSource===`session-list-plus`?e.creationSource:void 0;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},...d===void 0?{}:{creationSource:d},machineId:u,browserCachedNew:!0}]}function tu(e){return Ul in e}function nu(e){return typeof e==`object`&&!!e}function ru(e,t){let n=e[t];return typeof n==`string`?n:void 0}function iu(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function au(e,t){let n=e[t];return typeof n==`number`?n:void 0}function ou(e){return Tu(e.flatMap(du)).filter(e=>e.parts.length>0)}function su(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function cu(e,t){let n=_u(t),r=B(t,`entryId`),i=B(t,`previousAssistantEntryId`),a=Pu(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 lu(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,su(t,n)]}function uu(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 du(e){if(pu(e))return[e];if(B(e,`role`)===`bashExecution`)return[cu(bu(e),e)];let t=xu(B(e,`role`)),n=Su(Nu(e,`content`),e),r=t===`user`?mu(n):void 0;if(r!==void 0)return r.map(t=>cu(t,e));let i=gu(e);if(t===`tool`)return[cu({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?[cu({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=fu(e);return c===void 0?s:[...s,cu(c,e)]}function fu(e){if(B(e,`role`)!==`assistant`||B(e,`stopReason`)!==`error`)return;let t=B(e,`errorMessage`)?.trim();return su(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function pu(e){let t=B(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Nu(e,`parts`))}function mu(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=hu(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 hu(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 gu(e){let t=B(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function _u(e){let t=vu(Nu(e,`timestamp`)),n=yu(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function vu(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 yu(e){if(B(e,`role`)!==`assistant`)return;let t=B(e,`provider`),n=B(e,`model`),r=B(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 bu(e){let t=B(e,`command`)??``,n=Pu(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Nu(e,`output`);r!=null&&n.push(``,Iu(r));let i=Nu(e,`exitCode`);i!=null&&n.push(``,`exit ${Iu(i)}`),Pu(e,`cancelled`)===!0&&n.push(``,`cancelled`),Pu(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=B(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function xu(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Su(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=B(e,`type`),n=B(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=B(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=B(e,`name`)??`tool`,n=Nu(e,`arguments`),r=B(e,`id`),i=t===`read`?wu(B(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Au(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=B(e,`data`),n=B(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return ku(e)}).map(e=>e.type===`text`&&B(t,`role`)===`toolResult`?Cu(e.text,t):e):ku(e)}function Cu(e,t){let n=B(t,`toolCallId`),r=Nu(t,`content`),i=Nu(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:B(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Pu(t,`isError`)===!0}}function wu(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 Tu(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=Eu(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&&Du(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Eu(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 Du(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Ou(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 Ou(e){let t=Nu(e,`preview`);if(!Mu(t))return;let n=B(t,`diff`),r=B(t,`error`),i=Fu(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 ku(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Au(e)}]:[{type:`text`,text:Iu(e)}]}function Au(e){if(!Mu(e))return Iu(e);let t=B(e,`command`);if(t!==void 0)return t;let n=B(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}: ${ju(t)}`).join(` · `)}function ju(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 Mu(e){return typeof e==`object`&&!!e}function Nu(e,t){return Mu(e)?e[t]:void 0}function B(e,t){let n=Nu(e,t);return typeof n==`string`?n:void 0}function Pu(e,t){let n=Nu(e,t);return typeof n==`boolean`?n:void 0}function Fu(e,t){let n=Nu(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Iu(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Lu=`pi-webui:prompt-draft:`;function Ru(e){return`${Lu}${e}`}function zu(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bu(e,t=zu()){try{return t?.getItem(Ru(e))??``}catch{return``}}function Vu(e,t,n=zu()){try{t?n?.setItem(Ru(e),t):n?.removeItem(Ru(e))}catch{}}function Hu(e,t=zu()){try{t?.removeItem(Ru(e))}catch{}}function Uu(e,t,n=zu()){let r=Bu(e,n);r!==``&&(Vu(t,r,n),Hu(e,n))}function Wu(e,t){return su(`bash`,`${t===!0?`excluded from context
|
|
@@ -1121,7 +1121,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1121
1121
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1122
1122
|
.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; }
|
|
1123
1123
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1124
|
-
`]}};V([x({attribute:!1})],Jg.prototype,`context`,void 0),V([C(`#workspace-upload-input`)],Jg.prototype,`uploadInput`,void 0),V([S()],Jg.prototype,`pendingUpload`,void 0),V([S()],Jg.prototype,`destinationFolder`,void 0),V([S()],Jg.prototype,`overwrite`,void 0),V([S()],Jg.prototype,`createDirs`,void 0),V([S()],Jg.prototype,`formError`,void 0),V([S()],Jg.prototype,`dragActive`,void 0),Jg=V([b(`workspace-files-panel`)],Jg);function Yg(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 Xg(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ss(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Zg(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Qg(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} · ${d_(t.size)}`}function $g(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function e_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function t_(e){return e==null?[]:Array.from(e)}function n_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function r_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function i_(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 a_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return l_(e.percent)}}function o_(e){return e.status===`uploading`?e.percent:1}function s_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return l_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function c_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${d_(e.loaded)} / ${d_(e.total)}`:`Wrote ${e.response.path}`:e.error}function l_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function u_(){qg(()=>import(`./CodeViewer-
|
|
1124
|
+
`]}};V([x({attribute:!1})],Jg.prototype,`context`,void 0),V([C(`#workspace-upload-input`)],Jg.prototype,`uploadInput`,void 0),V([S()],Jg.prototype,`pendingUpload`,void 0),V([S()],Jg.prototype,`destinationFolder`,void 0),V([S()],Jg.prototype,`overwrite`,void 0),V([S()],Jg.prototype,`createDirs`,void 0),V([S()],Jg.prototype,`formError`,void 0),V([S()],Jg.prototype,`dragActive`,void 0),Jg=V([b(`workspace-files-panel`)],Jg);function Yg(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 Xg(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ss(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Zg(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Qg(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} · ${d_(t.size)}`}function $g(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function e_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function t_(e){return e==null?[]:Array.from(e)}function n_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function r_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function i_(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 a_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return l_(e.percent)}}function o_(e){return e.status===`uploading`?e.percent:1}function s_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return l_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function c_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${d_(e.loaded)} / ${d_(e.total)}`:`Wrote ${e.response.path}`:e.error}function l_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function u_(){qg(()=>import(`./CodeViewer-C0XQ5fEe.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function d_(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`${f_(t)} KB`;let n=t/1024;return n<1024?`${f_(n)} MB`:`${f_(n/1024)} GB`}function f_(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var p_=2e3,m_=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 No.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)},p_))}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 No.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">
|
|
1125
1125
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1126
1126
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1127
1127
|
</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">
|
|
@@ -1375,7 +1375,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1375
1375
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1376
1376
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1377
1377
|
</section>
|
|
1378
|
-
`}function D_(){qg(()=>import(`./UnifiedDiffViewer-
|
|
1378
|
+
`}function D_(){qg(()=>import(`./UnifiedDiffViewer-BGXZn_Bc.js`),[],import.meta.url)}function O_(){qg(()=>Promise.resolve().then(()=>DM),void 0,import.meta.url)}function k_(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function A_(e){let t=j_(e);return g`
|
|
1379
1379
|
<p class="summary">
|
|
1380
1380
|
<span class="summary-branch">${t.branch}</span>
|
|
1381
1381
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -5611,7 +5611,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5611
5611
|
<strong>${t}</strong>
|
|
5612
5612
|
<small>${n}</small>
|
|
5613
5613
|
</button>
|
|
5614
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await fj({loadConfig:()=>zo.config(),loadPlugins:()=>Bo.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await zo.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await zo.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([zo.config(e.id),Bo.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${Ej(jj(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${Ej(jj(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await pj(e,e=>Qo.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(Cj(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await Wo.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(Cj(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await qo.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(Cj(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=Oj(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await zo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=kj(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${Ej(jj(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await zo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${jj(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(Cj(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await zo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=hj(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(Cj(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!wj(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await zo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Pk(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(Cj(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await Wo.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(Cj(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await qo.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Qo.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Qo.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>Qo.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(Kk(i))throw this.packageError=i.message??`Pi package management is not available on ${Uk(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=Jk(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=aA(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${Uk(n)}: ${oA(jj(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Bo.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${jj(e)}`}}async refreshPluginsForTarget(e){try{let t=await Bo.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${Ej(jj(t),e)}`}}settingsTarget(){return _j(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return vj(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return yj(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return bj(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return xj(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=vj(t,e),r=this.selectedMachineSettingsSupport(t);return Sj(n)!==Sj(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=xj(t,e),r=this.utilityModelSettingsSupport(t);return Sj(n)!==Sj(r)}packageManagementSupport(e=this.packageTarget()){return Wk(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=Wk(t,e),r=this.packageManagementSupport(t);return Gk(n)===Gk(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
5614
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await fj({loadConfig:()=>zo.config(),loadPlugins:()=>Bo.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await zo.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await zo.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(Cj(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([zo.config(e.id),Bo.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${Ej(jj(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${Ej(jj(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await pj(e,e=>Qo.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(Cj(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await Wo.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(Cj(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await qo.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${Ej(jj(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(Cj(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=Oj(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await zo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=kj(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${Ej(jj(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await zo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${jj(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(Cj(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await zo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=hj(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(Cj(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!wj(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await zo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=Pk(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(Cj(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await Wo.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.onModelTiersSaved?.(t.id,n),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(Cj(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await qo.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${Ej(jj(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Qo.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Qo.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>Qo.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(Kk(i))throw this.packageError=i.message??`Pi package management is not available on ${Uk(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=Jk(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=aA(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${Uk(n)}: ${oA(jj(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Bo.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${jj(e)}`}}async refreshPluginsForTarget(e){try{let t=await Bo.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${Ej(jj(t),e)}`}}settingsTarget(){return _j(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return vj(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return yj(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return bj(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return xj(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=vj(t,e),r=this.selectedMachineSettingsSupport(t);return Sj(n)!==Sj(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=xj(t,e),r=this.utilityModelSettingsSupport(t);return Sj(n)!==Sj(r)}packageManagementSupport(e=this.packageTarget()){return Wk(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=Wk(t,e),r=this.packageManagementSupport(t);return Gk(n)===Gk(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
5615
5615
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5616
5616
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
5617
5617
|
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -5638,7 +5638,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5638
5638
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
5639
5639
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
5640
5640
|
}
|
|
5641
|
-
`}};V([x({attribute:!1})],X.prototype,`section`,void 0),V([x({attribute:!1})],X.prototype,`actions`,void 0),V([x({attribute:!1})],X.prototype,`machine`,void 0),V([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),V([x({attribute:!1})],X.prototype,`onNavigate`,void 0),V([x({attribute:!1})],X.prototype,`onClose`,void 0),V([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),V([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),V([S()],X.prototype,`configResponse`,void 0),V([S()],X.prototype,`accessConfigResponse`,void 0),V([S()],X.prototype,`sessiondConfigResponse`,void 0),V([S()],X.prototype,`pluginsResponse`,void 0),V([S()],X.prototype,`selectedPluginConfigResponse`,void 0),V([S()],X.prototype,`selectedPluginsResponse`,void 0),V([S()],X.prototype,`packagesResponse`,void 0),V([S()],X.prototype,`modelTiersConfigResponse`,void 0),V([S()],X.prototype,`utilityModelsConfigResponse`,void 0),V([S()],X.prototype,`loading`,void 0),V([S()],X.prototype,`accessLoading`,void 0),V([S()],X.prototype,`sessiondLoading`,void 0),V([S()],X.prototype,`pluginLoading`,void 0),V([S()],X.prototype,`packageLoading`,void 0),V([S()],X.prototype,`modelTiersLoading`,void 0),V([S()],X.prototype,`utilityModelsLoading`,void 0),V([S()],X.prototype,`saving`,void 0),V([S()],X.prototype,`packageOperation`,void 0),V([S()],X.prototype,`error`,void 0),V([S()],X.prototype,`accessError`,void 0),V([S()],X.prototype,`sessiondError`,void 0),V([S()],X.prototype,`pluginError`,void 0),V([S()],X.prototype,`packageError`,void 0),V([S()],X.prototype,`modelTiersError`,void 0),V([S()],X.prototype,`utilityModelsError`,void 0),V([S()],X.prototype,`savedMessage`,void 0),V([S()],X.prototype,`packageMessage`,void 0),X=V([b(`settings-dialog`)],X);function jj(e){return e instanceof Error?e.message:String(e)}var Mj=class extends y{constructor(...e){super(...e),this.sessionsApi=as,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&Pj(e.get(`session`))!==Pj(this.session),n=e.has(`machine`)&&Nj(e.get(`machine`))!==Nj(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
5641
|
+
`}};V([x({attribute:!1})],X.prototype,`section`,void 0),V([x({attribute:!1})],X.prototype,`actions`,void 0),V([x({attribute:!1})],X.prototype,`machine`,void 0),V([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),V([x({attribute:!1})],X.prototype,`onNavigate`,void 0),V([x({attribute:!1})],X.prototype,`onClose`,void 0),V([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),V([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),V([x({attribute:!1})],X.prototype,`onModelTiersSaved`,void 0),V([S()],X.prototype,`configResponse`,void 0),V([S()],X.prototype,`accessConfigResponse`,void 0),V([S()],X.prototype,`sessiondConfigResponse`,void 0),V([S()],X.prototype,`pluginsResponse`,void 0),V([S()],X.prototype,`selectedPluginConfigResponse`,void 0),V([S()],X.prototype,`selectedPluginsResponse`,void 0),V([S()],X.prototype,`packagesResponse`,void 0),V([S()],X.prototype,`modelTiersConfigResponse`,void 0),V([S()],X.prototype,`utilityModelsConfigResponse`,void 0),V([S()],X.prototype,`loading`,void 0),V([S()],X.prototype,`accessLoading`,void 0),V([S()],X.prototype,`sessiondLoading`,void 0),V([S()],X.prototype,`pluginLoading`,void 0),V([S()],X.prototype,`packageLoading`,void 0),V([S()],X.prototype,`modelTiersLoading`,void 0),V([S()],X.prototype,`utilityModelsLoading`,void 0),V([S()],X.prototype,`saving`,void 0),V([S()],X.prototype,`packageOperation`,void 0),V([S()],X.prototype,`error`,void 0),V([S()],X.prototype,`accessError`,void 0),V([S()],X.prototype,`sessiondError`,void 0),V([S()],X.prototype,`pluginError`,void 0),V([S()],X.prototype,`packageError`,void 0),V([S()],X.prototype,`modelTiersError`,void 0),V([S()],X.prototype,`utilityModelsError`,void 0),V([S()],X.prototype,`savedMessage`,void 0),V([S()],X.prototype,`packageMessage`,void 0),X=V([b(`settings-dialog`)],X);function jj(e){return e instanceof Error?e.message:String(e)}var Mj=class extends y{constructor(...e){super(...e),this.sessionsApi=as,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&Pj(e.get(`session`))!==Pj(this.session),n=e.has(`machine`)&&Nj(e.get(`machine`))!==Nj(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
5642
5642
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
5643
5643
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
5644
5644
|
<header>
|
|
@@ -6784,7 +6784,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6784
6784
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
6785
6785
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
6786
6786
|
}
|
|
6787
|
-
`}};V([x({attribute:!1})],HN.prototype,`onClose`,void 0),V([x({attribute:!1})],HN.prototype,`onStatusChange`,void 0),V([x({attribute:!1})],HN.prototype,`workspace`,void 0),V([x()],HN.prototype,`machineId`,void 0),V([x({attribute:!1})],HN.prototype,`api`,void 0),V([S()],HN.prototype,`status`,void 0),V([S()],HN.prototype,`selectedChange`,void 0),V([S()],HN.prototype,`selectedDiff`,void 0),V([S()],HN.prototype,`loadingStatus`,void 0),V([S()],HN.prototype,`loadingDiff`,void 0),V([S()],HN.prototype,`error`,void 0),V([S()],HN.prototype,`bounds`,void 0),HN=V([b(`git-update-manager-panel`)],HN);function UN(){qg(()=>import(`./UnifiedDiffViewer-iic0AurS.js`),[],import.meta.url)}function WN(e,t){let n=ml(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function GN(e){return e===`staged`?`Staged`:`Unstaged`}function KN(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function qN(e){return e instanceof Error?e.message:String(e)}var JN=900*1e3,YN=750,XN=[1e3,3e3,8e3,15e3,3e4],ZN={capture:!0},QN=`auto:on`,$N=`auto:off`,eP=`theme:`,tP=Wc(`core:workspace.files`),nP=Wc(`core:workspace.git`),rP=Wc(`core:workspace.terminal`),iP=`workspace-memory`,aP=`workspace.memory`,oP=`workspace-memory:workspace.memory`,sP=320,cP=2,lP=`(min-width: 1181px)`,uP=75,dP=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Mc(),this.sessionUnread=new Ph({onChange:e=>{z(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(z(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Qp(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new $f(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new zf,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(z(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new om(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new im,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Al(()=>this.state,{workspaces:is.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Rl(()=>this.state,e=>{this.setState(e)},{api:is,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Rc(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Vc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new El(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Sl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bl(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new rl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new ll(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new fl(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Im,this.realtime=new nf,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new vm,this.terminalSelection=new jm,this.appShell=new Cv(this),this.browserResume=new Ev({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Hv(this),this.panelResize=new Kv(this),this.navigationSections=new zv(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=fP(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=ng()??Qh,this.activeThemeId=Zh,this.isRefreshingApp=!1,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new ch({save:async(e,t)=>{let n=await as.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new ph({remember:(e,t)=>as.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,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=Ly(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=Gy(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=PN()??[...ON],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=py(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bs(void 0),this.sessionWarningVisibility=Hh(),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=Ay(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(bc(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=z(this.state),o=this.starterModelPolicy,s=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&s===void 0||((s===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,o)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,s,()=>void 0)).catch(e=>{i!==void 0&&this.publishStarterNotice(xc(`start-failed`,`Could not start the session. ${LP(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?Ys(t):t.tier===void 0?{...t,mode:`tiered`}:Js(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(z(this.state));return}if(e===`exact`){let e=Ys(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:Us(n);r!==void 0&&qs(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Js(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(z(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||Qs(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Js(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}Qs(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft(Ys(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Js(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Js(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,FN(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`?Oy(t.bounds,n,r):ky(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=Fy(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Iy(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=z(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&z(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=qh(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(),this.syncStarterNotice()}updated(){this.committedChatIdentity=hP(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Wh(this.sessionWarningVisibility,e===void 0?void 0:Ic(z(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=z(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=mP(e,t);await this.updateComplete,!(!this.unreadConnected||hP(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(z(this.state),this.state.sessions);jP(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Zy(this.state.selectedProject?.name);this.windowTitleCleanup=Qy(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=mP(e,t);return hP(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.compactRailOpen||this.activeActivityRailId!==void 0||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.synchronizeProjectCatalogPolling(),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,ZN),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},JN),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,ZN),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.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(!AP(this.state,e))return;let t=this.state,n=gP(t),r=vP(t),i=_P(t);this.state={...this.state,...e},i!==_P(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==gP(this.state)&&this.resetActiveModelPolicyDraft(),hP(t)!==hP(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),EP(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),this.handleStarterModelPolicyCapabilityChange(t,this.state),DP(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=vP(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=cy();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(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=YN){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=z(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?[z(this.state)]:this.state.machines.filter(e=>kP(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 zo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bs(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(cy(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=z(this.state),a=e.projectId===void 0||e.projectId===``?PP():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),z(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?PP():{selectedFilePath:Kc(tP,`file`),selectedDiffPath:Kc(nP,`diff`),selectedTerminalId:Kc(rP,`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){ly(e,{replace:!0}),qc(tP,`file`,void 0,{replace:!0}),qc(nP,`diff`,void 0,{replace:!0}),qc(rP,`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=IP(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>=XN.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 BP(),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(),ly({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(bm(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(bm(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ly(xm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){qc(tP,`file`,e.selectedFilePath,{replace:!0}),qc(nP,`diff`,e.selectedDiffPath,{replace:!0}),qc(rP,`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)??ym(e.id);if(await this.restoreRouteFor(xm(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=z(this.state)){let n=FP(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=by(e,{api:{runTerminalCommand:(e,n)=>os.runTerminalCommand(e,n,t),listCommandRuns:e=>os.listCommandRuns(e,t),getCommandRun:e=>os.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((z(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`),z(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){qc(rP,`terminal`,e,t)}terminalWorkspaceKey(e){return`${z(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,my(e)}closeSettings(){this.settingsSection=void 0,my(void 0)}navigateSettings(e){this.settingsSection=e,my(e)}restoreSettingsRoute(){this.settingsSection=py()}handleWorkspaceChange(e,t){let n=TP(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&this.synchronizeMemoryPollingForSelectedWorkspace();return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=z(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&z(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await as.sessionDefaultsV2(e.path,n):await as.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!SP(o)?this.starterModelPolicy=Ws(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Gs(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(xc(`defaults-failed`,`Could not load this workspace's model defaults. ${LP(t)}`,{machineId:n,workspaceId:e.id})))}}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`:E(e,w.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(z(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=z(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),this.projectCatalog.refresh()},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 nf;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=z(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>OP(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):NP(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=z(this.state);try{let n=await os.terminals(e.projectId,e.id,t);if(z(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=MP(e),r=MP(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
6787
|
+
`}};V([x({attribute:!1})],HN.prototype,`onClose`,void 0),V([x({attribute:!1})],HN.prototype,`onStatusChange`,void 0),V([x({attribute:!1})],HN.prototype,`workspace`,void 0),V([x()],HN.prototype,`machineId`,void 0),V([x({attribute:!1})],HN.prototype,`api`,void 0),V([S()],HN.prototype,`status`,void 0),V([S()],HN.prototype,`selectedChange`,void 0),V([S()],HN.prototype,`selectedDiff`,void 0),V([S()],HN.prototype,`loadingStatus`,void 0),V([S()],HN.prototype,`loadingDiff`,void 0),V([S()],HN.prototype,`error`,void 0),V([S()],HN.prototype,`bounds`,void 0),HN=V([b(`git-update-manager-panel`)],HN);function UN(){qg(()=>import(`./UnifiedDiffViewer-BGXZn_Bc.js`),[],import.meta.url)}function WN(e,t){let n=ml(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function GN(e){return e===`staged`?`Staged`:`Unstaged`}function KN(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function qN(e){return e instanceof Error?e.message:String(e)}var JN=900*1e3,YN=750,XN=[1e3,3e3,8e3,15e3,3e4],ZN={capture:!0},QN=`auto:on`,$N=`auto:off`,eP=`theme:`,tP=Wc(`core:workspace.files`),nP=Wc(`core:workspace.git`),rP=Wc(`core:workspace.terminal`),iP=`workspace-memory`,aP=`workspace.memory`,oP=`workspace-memory:workspace.memory`,sP=320,cP=2,lP=`(min-width: 1181px)`,uP=75,dP=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Mc(),this.sessionUnread=new Ph({onChange:e=>{z(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(z(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new Qp(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new $f(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new zf,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(z(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new om(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new im,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Al(()=>this.state,{workspaces:is.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Rl(()=>this.state,e=>{this.setState(e)},{api:is,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Rc(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Vc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new El(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Sl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bl(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new rl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new ll(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new fl(()=>this.state,e=>{this.setState(e)}),this.keyboard=new Im,this.realtime=new nf,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new vm,this.terminalSelection=new jm,this.appShell=new Cv(this),this.browserResume=new Ev({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Hv(this),this.panelResize=new Kv(this),this.navigationSections=new zv(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=fP(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=ng()??Qh,this.activeThemeId=Zh,this.isRefreshingApp=!1,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new ch({save:async(e,t)=>{let n=await as.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new ph({remember:(e,t)=>as.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,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=Ly(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=Gy(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=PN()??[...ON],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=py(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bs(void 0),this.sessionWarningVisibility=Hh(),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=Ay(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(bc(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=z(this.state),o=this.starterModelPolicy,s=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&s===void 0||((s===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,o)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,s,()=>void 0)).catch(e=>{i!==void 0&&this.publishStarterNotice(xc(`start-failed`,`Could not start the session. ${LP(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?Ys(t):t.tier===void 0?{...t,mode:`tiered`}:Js(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(z(this.state));return}if(e===`exact`){let e=Ys(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:Us(n);r!==void 0&&qs(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Js(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(z(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||Qs(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Js(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}Qs(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft(Ys(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Js(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Js(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,FN(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`?Oy(t.bounds,n,r):ky(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=Fy(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Iy(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=z(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&z(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=qh(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(),this.syncStarterNotice()}updated(){this.committedChatIdentity=hP(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Wh(this.sessionWarningVisibility,e===void 0?void 0:Ic(z(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=z(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=mP(e,t);await this.updateComplete,!(!this.unreadConnected||hP(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(z(this.state),this.state.sessions);jP(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Zy(this.state.selectedProject?.name);this.windowTitleCleanup=Qy(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=mP(e,t);return hP(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.compactRailOpen||this.activeActivityRailId!==void 0||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.synchronizeProjectCatalogPolling(),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,ZN),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},JN),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,ZN),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.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(!AP(this.state,e))return;let t=this.state,n=gP(t),r=vP(t),i=_P(t);this.state={...this.state,...e},i!==_P(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==gP(this.state)&&this.resetActiveModelPolicyDraft(),hP(t)!==hP(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),EP(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),this.handleStarterModelPolicyCapabilityChange(t,this.state),DP(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=vP(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=cy();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(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=YN){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=z(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?[z(this.state)]:this.state.machines.filter(e=>kP(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 zo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bs(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(cy(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=z(this.state),a=e.projectId===void 0||e.projectId===``?PP():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),z(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?PP():{selectedFilePath:Kc(tP,`file`),selectedDiffPath:Kc(nP,`diff`),selectedTerminalId:Kc(rP,`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){ly(e,{replace:!0}),qc(tP,`file`,void 0,{replace:!0}),qc(nP,`diff`,void 0,{replace:!0}),qc(rP,`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=IP(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>=XN.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 BP(),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(),ly({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(bm(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(bm(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ly(xm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){qc(tP,`file`,e.selectedFilePath,{replace:!0}),qc(nP,`diff`,e.selectedDiffPath,{replace:!0}),qc(rP,`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)??ym(e.id);if(await this.restoreRouteFor(xm(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=z(this.state)){let n=FP(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=by(e,{api:{runTerminalCommand:(e,n)=>os.runTerminalCommand(e,n,t),listCommandRuns:e=>os.listCommandRuns(e,t),getCommandRun:e=>os.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((z(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`),z(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){qc(rP,`terminal`,e,t)}terminalWorkspaceKey(e){return`${z(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,my(e)}closeSettings(){this.settingsSection=void 0,my(void 0)}navigateSettings(e){this.settingsSection=e,my(e)}restoreSettingsRoute(){this.settingsSection=py()}handleWorkspaceChange(e,t){let n=TP(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&this.synchronizeMemoryPollingForSelectedWorkspace();return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=z(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&z(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await as.sessionDefaultsV2(e.path,n):await as.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!SP(o)?this.starterModelPolicy=Ws(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Gs(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(xc(`defaults-failed`,`Could not load this workspace's model defaults. ${LP(t)}`,{machineId:n,workspaceId:e.id})))}}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`:E(e,w.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(z(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=z(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),this.projectCatalog.refresh()},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 nf;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=z(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>OP(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):NP(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=z(this.state);try{let n=await os.terminals(e.projectId,e.id,t);if(z(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=MP(e),r=MP(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
6788
6788
|
<workspace-panel
|
|
6789
6789
|
id="workspace-panel"
|
|
6790
6790
|
.workspace=${e}
|
|
@@ -6831,7 +6831,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6831
6831
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
6832
6832
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
6833
6833
|
></app-panel-edge-control>
|
|
6834
|
-
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-cP-sP);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(lP).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Ef(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=z(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=z(this.state)){return bP(this.state,e)}starterModelPolicySelectionSupported(e=z(this.state)){return xP(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=z(t);if(z(e)!==n||xP(e,n)||!xP(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:z(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Bs(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:z(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Cc(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Ks(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&z(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Wo.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=LP(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=ec(t,e,n);CP(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===z(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(z(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=gP(this.state);if(e===void 0||yP(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(z(this.state))),await Promise.all(n),gP(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=yP(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Vs({policy:o,catalog:i});else if(a.mode===`exact`)s=Vs({liveResolved:a.resolved,catalog:i});else{let e=Vs({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Js(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===gP(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=gP(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!$s(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},uP)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!$s(e,t)||t===void 0)return;let n=Qs(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==gP(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Vs({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Ac({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Dh(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[z(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=z(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await as.cleanupPreview(e,t);if(z(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){z(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${LP(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||bh(t.previewRequest)!==bh(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=z(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await as.cleanup(e,n);if(z(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){z(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${LP(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=z(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await as.forceCleanup(t);if(z(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){z(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${LP(e)}`})}}renderNavigationPanel(){return g`
|
|
6834
|
+
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-cP-sP);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(lP).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Ef(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=z(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=z(this.state)){return bP(this.state,e)}starterModelPolicySelectionSupported(e=z(this.state)){return xP(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=z(t);if(z(e)!==n||xP(e,n)||!xP(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:z(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Bs(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:z(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Cc(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Ks(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&z(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Wo.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=LP(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){z(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),vP(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=ec(t,e,n);CP(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===z(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(z(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=gP(this.state);if(e===void 0||yP(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(z(this.state))),await Promise.all(n),gP(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=yP(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Vs({policy:o,catalog:i});else if(a.mode===`exact`)s=Vs({liveResolved:a.resolved,catalog:i});else{let e=Vs({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Js(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===gP(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=gP(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!$s(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},uP)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!$s(e,t)||t===void 0)return;let n=Qs(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==gP(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Vs({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Ac({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Dh(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[z(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=z(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await as.cleanupPreview(e,t);if(z(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){z(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${LP(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||bh(t.previewRequest)!==bh(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=z(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await as.cleanup(e,n);if(z(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){z(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${LP(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=z(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await as.forceCleanup(t);if(z(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){z(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${LP(e)}`})}}renderNavigationPanel(){return g`
|
|
6835
6835
|
<app-navigation-panel
|
|
6836
6836
|
.machines=${this.state.machines}
|
|
6837
6837
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -7102,6 +7102,6 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7102
7102
|
${r===void 0?null:g`<plugin-activity-dialog .activity=${r.activity} .context=${r.context} .onClose=${()=>{this.closeActivityRailItem(r.activity.id,r.generation)}} .onReportError=${this.reportActivityRailError}></plugin-activity-dialog>`}
|
|
7103
7103
|
${n===void 0?null:g`<git-update-manager-panel .workspace=${n} .machineId=${z(e)} .onStatusChange=${t=>{this.applyGitUpdateManagerStatus(n,z(e),t)}} .onClose=${this.handleCloseGitUpdateManagerPanel}></git-update-manager-panel>`}
|
|
7104
7104
|
${this.terminalModalOpen?this.renderTerminalModal():null}
|
|
7105
|
-
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7105
|
+
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onModelTiersSaved=${(e,t)=>{this.handleModelTiersSaved(e,t)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7106
7106
|
</div>
|
|
7107
7107
|
`}static{this.styles=Fg}};V([S()],$.prototype,`state`,void 0),V([C(`chat-view`)],$.prototype,`chatView`,void 0),V([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),V([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),V([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),V([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),V([S()],$.prototype,`unreadSessionIds`,void 0),V([S()],$.prototype,`activeThemeId`,void 0),V([S()],$.prototype,`isRefreshingApp`,void 0),V([S()],$.prototype,`sessionCleanupDialog`,void 0),V([S()],$.prototype,`historyWindow`,void 0),V([S()],$.prototype,`starterSessionDefaults`,void 0),V([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),V([S()],$.prototype,`starterNotice`,void 0),V([S()],$.prototype,`modelTierCatalog`,void 0),V([S()],$.prototype,`modelTierCatalogLoading`,void 0),V([S()],$.prototype,`modelTierCatalogError`,void 0),V([S()],$.prototype,`starterModelPolicy`,void 0),V([S()],$.prototype,`activeModelPolicyDraft`,void 0),V([S()],$.prototype,`modelsConfigDialogOpen`,void 0),V([S()],$.prototype,`projectBrowserOpen`,void 0),V([S()],$.prototype,`sessionBrowserOpen`,void 0),V([S()],$.prototype,`skillsConfigDialogOpen`,void 0),V([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),V([S()],$.prototype,`systemPromptDialogOpen`,void 0),V([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),V([S()],$.prototype,`terminalModalOpen`,void 0),V([S()],$.prototype,`terminalModalBounds`,void 0),V([S()],$.prototype,`terminalModalMaximized`,void 0),V([S()],$.prototype,`terminalModalFontSize`,void 0),V([S()],$.prototype,`terminalModalOpacity`,void 0),V([S()],$.prototype,`terminalTabHidden`,void 0),V([S()],$.prototype,`infoTabHidden`,void 0),V([S()],$.prototype,`railOrder`,void 0),V([S()],$.prototype,`compactRailOpen`,void 0),V([S()],$.prototype,`activeActivityRailId`,void 0),V([S()],$.prototype,`settingsSection`,void 0),V([S()],$.prototype,`shortcutConfig`,void 0),V([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=V([b(`pi-webui-app`)],$);function fP(){let e=new iv;return e.register({id:`core`,plugin:N_}),e.register({id:`themes`,plugin:R_}),e}function pP(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function mP(e,t){return JSON.stringify([e,t.id,t.cwd])}function hP(e){let t=e.selectedSession;return t===void 0?void 0:mP(z(e),t)}function gP(e){let t=e.selectedSession;return t===void 0?void 0:JSON.stringify([z(e),t.id,t.cwd])}function _P(e){return JSON.stringify([z(e),e.selectedWorkspace?.id,e.selectedWorkspace?.path,e.selectedSession?.id,e.selectedSession?.cwd])}function vP(e){if(yP(e)!==void 0&&bP(e,z(e)))return gP(e)}function yP(e){return e.status?.modelPolicy}function bP(e,t){if(t===`local`)return!0;let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicy)}function xP(e,t){let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicyStarterSelection)}function SP(e){return e!==void 0&&`starterModelPolicyContractVersion`in e}function CP(e,t){return e.mode===t.mode&&e.tier===t.tier&&qs(e.exact,t.exact)}function wP(e){return e.id===oP||e.sourcePluginId===iP&&e.localId===aP}function TP(e,t){return z(e)!==z(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id||e.selectedWorkspace?.path!==t.selectedWorkspace?.path}function EP(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function DP(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function OP(e,t){return kP(e,t)}function kP(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function AP(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function jP(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function MP(e){return Nc(e.status,e.activity)}function NP(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function PP(){return{}}function FP(e,t){return JSON.stringify([e,t])}function IP(e){return XN[Math.min(e,XN.length-1)]??3e4}function LP(e){return e instanceof Error?e.message:String(e)}function RP(e){if(e?.modelPolicy===void 0)return e;let t={...e};return delete t.modelPolicy,t}function zP(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function BP(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function VP(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,V as t};
|
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-CkfjnumG.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