@theruansilva/omp-web 2.0.0 → 2.0.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.
@@ -1,4 +1,4 @@
1
- import{w as r,J as u,$ as h,A as m,X as g,U as f,_ as v}from"./vendor-editor-core-D9EJm1dE.js";import{g as b,r as w,p as y,h as x,c as C,m as j,j as k,a as d}from"./vendor-editor-languages-N6dcxgRO.js";import{i as E,b as _,a as H,n as p,g as O,t as P}from"./index-uWm_YNRB.js";var S=Object.defineProperty,T=Object.getOwnPropertyDescriptor,i=(e,s,n,a)=>{for(var t=a>1?void 0:a?T(s,n):s,c=e.length-1,l;c>=0;c--)(l=e[c])&&(t=(a?l(s,n,t):l(t))||t);return a&&t&&S(s,n,t),t};let o=class extends E{constructor(){super(...arguments),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 _`<div class="host"></div>`}recreateEditor(){this.editorHost&&(this.view?.destroy(),this.view=new r({parent:this.editorHost,state:u.create({doc:this.content,extensions:[h(),m.of(g),f(v,{fallback:!0}),u.readOnly.of(!0),r.editable.of(!1),r.lineWrapping,A,...F(this.language),...L(this.language)]})}))}};o.styles=H`
1
+ import{w as r,J as u,$ as h,A as m,X as g,U as f,_ as v}from"./vendor-editor-core-D9EJm1dE.js";import{g as b,r as w,p as y,h as x,c as C,m as j,j as k,a as d}from"./vendor-editor-languages-N6dcxgRO.js";import{i as E,b as _,a as H,n as p,g as O,t as P}from"./index-Df4Ex27j.js";var S=Object.defineProperty,T=Object.getOwnPropertyDescriptor,i=(e,s,n,a)=>{for(var t=a>1?void 0:a?T(s,n):s,c=e.length-1,l;c>=0;c--)(l=e[c])&&(t=(a?l(s,n,t):l(t))||t);return a&&t&&S(s,n,t),t};let o=class extends E{constructor(){super(...arguments),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 _`<div class="host"></div>`}recreateEditor(){this.editorHost&&(this.view?.destroy(),this.view=new r({parent:this.editorHost,state:u.create({doc:this.content,extensions:[h(),m.of(g),f(v,{fallback:!0}),u.readOnly.of(!0),r.editable.of(!1),r.lineWrapping,A,...F(this.language),...L(this.language)]})}))}};o.styles=H`
2
2
  :host { display: block; min-height: 0; height: 100%; }
3
3
  .host { height: 100%; min-height: 0; overflow: auto; }
4
4
  `;i([p()],o.prototype,"content",2);i([p()],o.prototype,"language",2);i([O(".host")],o.prototype,"editorHost",2);o=i([P("code-viewer")],o);const A=r.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"}}),D=r.theme({".cm-content":{textAlign:"start"},".cm-line":{unicodeBidi:"plaintext"}});function F(e){return e==="markdown"?[r.contentAttributes.of({dir:"auto"}),D]:[]}function L(e){if(e===void 0)return[];switch(e){case"typescript":return[d({typescript:!0})];case"javascript":return[d()];case"json":return[k()];case"markdown":return[j()];case"css":return[C()];case"html":return[x()];case"python":return[y()];case"rust":return[w()];case"go":return[b()];default:return[]}}export{o as CodeViewer};
@@ -1,4 +1,4 @@
1
- import{a as E,n as m,i as K,b as l,t as R,c as h,s as A,d as w,e as _,f as F,g as N,r as c}from"./index-uWm_YNRB.js";import{D as S,o as T}from"./vendor-terminal-DjQ08hXu.js";import"./vendor-editor-core-D9EJm1dE.js";import"./vendor-editor-languages-N6dcxgRO.js";const P="omp-web.terminal.softKeys",z="(pointer: coarse), (max-width: 760px)";function V(e,t){return e??t}function H(e){if(e==="true")return!0;if(e==="false")return!1}function $(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(z):void 0}function M(e){return e?.matches===!0}function B(e=$()){return V(O(),M(e))}function U(){return O()!==void 0}function O(e=D()){if(e!==void 0)try{return H(e.getItem(P))}catch{return}}function j(e,t=D()){if(t!==void 0)try{t.setItem(P,String(e))}catch{}}function D(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}const q=[{id:"escape",label:"Esc",ariaLabel:"Escape",title:"Send Escape"},{id:"tab",label:"Tab",ariaLabel:"Tab",title:"Send Tab"},{id:"ctrl-c",label:"Ctrl+C",ariaLabel:"Control C",title:"Interrupt the foreground process"},{id:"ctrl-d",label:"Ctrl+D",ariaLabel:"Control D",title:"Send EOF / close input"},{id:"ctrl-z",label:"Ctrl+Z",ariaLabel:"Control Z",title:"Suspend the foreground process"},{id:"ctrl-l",label:"Ctrl+L",ariaLabel:"Control L",title:"Clear / redraw the terminal"},{id:"ctrl-r",label:"Ctrl+R",ariaLabel:"Control R",title:"Reverse search history"},{id:"ctrl-u",label:"Ctrl+U",ariaLabel:"Control U",title:"Delete to the start of the line"},{id:"ctrl-w",label:"Ctrl+W",ariaLabel:"Control W",title:"Delete the previous word"},{id:"arrow-left",label:"←",ariaLabel:"Left arrow",title:"Move left"},{id:"arrow-up",label:"↑",ariaLabel:"Up arrow",title:"Move up / previous command"},{id:"arrow-down",label:"↓",ariaLabel:"Down arrow",title:"Move down / next command"},{id:"arrow-right",label:"→",ariaLabel:"Right arrow",title:"Move right"},{id:"home",label:"Home",ariaLabel:"Home",title:"Move to the start"},{id:"end",label:"End",ariaLabel:"End",title:"Move to the end"},{id:"page-up",label:"PgUp",ariaLabel:"Page up",title:"Page up"},{id:"page-down",label:"PgDn",ariaLabel:"Page down",title:"Page down"},{id:"delete",label:"Del",ariaLabel:"Delete",title:"Delete forward"},{id:"backspace",label:"⌫",ariaLabel:"Backspace",title:"Backspace"},{id:"meta-backward-word",label:"M-B",ariaLabel:"Meta B",title:"Move backward one word"},{id:"meta-forward-word",label:"M-F",ariaLabel:"Meta F",title:"Move forward one word"}],d="\x1B",Y="";function W(e,t){switch(e){case"escape":return d;case"tab":return" ";case"ctrl-c":return p("c");case"ctrl-d":return p("d");case"ctrl-z":return p("z");case"ctrl-l":return p("l");case"ctrl-r":return p("r");case"ctrl-u":return p("u");case"ctrl-w":return p("w");case"arrow-left":return b("D",t);case"arrow-up":return b("A",t);case"arrow-down":return b("B",t);case"arrow-right":return b("C",t);case"home":return x("H",t);case"end":return x("F",t);case"page-up":return`${d}[5~`;case"page-down":return`${d}[6~`;case"delete":return`${d}[3~`;case"backspace":return Y;case"meta-backward-word":return`${d}b`;case"meta-forward-word":return`${d}f`}}function p(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function b(e,t){return t?.applicationCursorKeysMode===!0?`${d}O${e}`:`${d}[${e}`}function x(e,t){return t?.applicationCursorKeysMode===!0?`${d}O${e}`:`${d}[${e}`}var X=Object.defineProperty,J=Object.getOwnPropertyDescriptor,y=(e,t,i,r)=>{for(var n=r>1?void 0:r?J(t,i):t,a=e.length-1,u;a>=0;a--)(u=e[a])&&(n=(r?u(t,i,n):u(n))||n);return r&&n&&X(t,i,n),n};const Z=8,G=500;let f=class extends K{constructor(){super(...arguments),this.refocusOnClick=!0,this.onInput=()=>{},this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(W(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType==="mouse"&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){const t=this.pointerStart;t?.pointerId===e.pointerId&&I(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){const i=this.pointerStart;i?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(i.key.id!==t.id||I(i,e))&&this.sendSoftKey(t,{refocus:e.pointerType==="mouse"}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<G){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return l`
1
+ import{a as E,n as m,i as K,b as l,t as R,c as h,s as A,d as w,e as _,f as F,g as N,r as c}from"./index-Df4Ex27j.js";import{D as S,o as T}from"./vendor-terminal-DjQ08hXu.js";import"./vendor-editor-core-D9EJm1dE.js";import"./vendor-editor-languages-N6dcxgRO.js";const P="omp-web.terminal.softKeys",z="(pointer: coarse), (max-width: 760px)";function V(e,t){return e??t}function H(e){if(e==="true")return!0;if(e==="false")return!1}function $(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(z):void 0}function M(e){return e?.matches===!0}function B(e=$()){return V(O(),M(e))}function U(){return O()!==void 0}function O(e=D()){if(e!==void 0)try{return H(e.getItem(P))}catch{return}}function j(e,t=D()){if(t!==void 0)try{t.setItem(P,String(e))}catch{}}function D(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}const q=[{id:"escape",label:"Esc",ariaLabel:"Escape",title:"Send Escape"},{id:"tab",label:"Tab",ariaLabel:"Tab",title:"Send Tab"},{id:"ctrl-c",label:"Ctrl+C",ariaLabel:"Control C",title:"Interrupt the foreground process"},{id:"ctrl-d",label:"Ctrl+D",ariaLabel:"Control D",title:"Send EOF / close input"},{id:"ctrl-z",label:"Ctrl+Z",ariaLabel:"Control Z",title:"Suspend the foreground process"},{id:"ctrl-l",label:"Ctrl+L",ariaLabel:"Control L",title:"Clear / redraw the terminal"},{id:"ctrl-r",label:"Ctrl+R",ariaLabel:"Control R",title:"Reverse search history"},{id:"ctrl-u",label:"Ctrl+U",ariaLabel:"Control U",title:"Delete to the start of the line"},{id:"ctrl-w",label:"Ctrl+W",ariaLabel:"Control W",title:"Delete the previous word"},{id:"arrow-left",label:"←",ariaLabel:"Left arrow",title:"Move left"},{id:"arrow-up",label:"↑",ariaLabel:"Up arrow",title:"Move up / previous command"},{id:"arrow-down",label:"↓",ariaLabel:"Down arrow",title:"Move down / next command"},{id:"arrow-right",label:"→",ariaLabel:"Right arrow",title:"Move right"},{id:"home",label:"Home",ariaLabel:"Home",title:"Move to the start"},{id:"end",label:"End",ariaLabel:"End",title:"Move to the end"},{id:"page-up",label:"PgUp",ariaLabel:"Page up",title:"Page up"},{id:"page-down",label:"PgDn",ariaLabel:"Page down",title:"Page down"},{id:"delete",label:"Del",ariaLabel:"Delete",title:"Delete forward"},{id:"backspace",label:"⌫",ariaLabel:"Backspace",title:"Backspace"},{id:"meta-backward-word",label:"M-B",ariaLabel:"Meta B",title:"Move backward one word"},{id:"meta-forward-word",label:"M-F",ariaLabel:"Meta F",title:"Move forward one word"}],d="\x1B",Y="";function W(e,t){switch(e){case"escape":return d;case"tab":return" ";case"ctrl-c":return p("c");case"ctrl-d":return p("d");case"ctrl-z":return p("z");case"ctrl-l":return p("l");case"ctrl-r":return p("r");case"ctrl-u":return p("u");case"ctrl-w":return p("w");case"arrow-left":return b("D",t);case"arrow-up":return b("A",t);case"arrow-down":return b("B",t);case"arrow-right":return b("C",t);case"home":return x("H",t);case"end":return x("F",t);case"page-up":return`${d}[5~`;case"page-down":return`${d}[6~`;case"delete":return`${d}[3~`;case"backspace":return Y;case"meta-backward-word":return`${d}b`;case"meta-forward-word":return`${d}f`}}function p(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function b(e,t){return t?.applicationCursorKeysMode===!0?`${d}O${e}`:`${d}[${e}`}function x(e,t){return t?.applicationCursorKeysMode===!0?`${d}O${e}`:`${d}[${e}`}var X=Object.defineProperty,J=Object.getOwnPropertyDescriptor,y=(e,t,i,r)=>{for(var n=r>1?void 0:r?J(t,i):t,a=e.length-1,u;a>=0;a--)(u=e[a])&&(n=(r?u(t,i,n):u(n))||n);return r&&n&&X(t,i,n),n};const Z=8,G=500;let f=class extends K{constructor(){super(...arguments),this.refocusOnClick=!0,this.onInput=()=>{},this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(W(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType==="mouse"&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){const t=this.pointerStart;t?.pointerId===e.pointerId&&I(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){const i=this.pointerStart;i?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(i.key.id!==t.id||I(i,e))&&this.sendSoftKey(t,{refocus:e.pointerType==="mouse"}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<G){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return l`
2
2
  <div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
3
3
  ${q.map(e=>l`
4
4
  <button
@@ -1,4 +1,4 @@
1
- import{i as A,b as P,a as V,n as z,t as F}from"./index-uWm_YNRB.js";import"./vendor-editor-core-D9EJm1dE.js";import"./vendor-editor-languages-N6dcxgRO.js";class U{diff(e,t,i={}){let o;typeof i=="function"?(o=i,i={}):"callback"in i&&(o=i.callback);const r=this.castInput(e,i),s=this.castInput(t,i),u=this.removeEmpty(this.tokenize(r,i)),l=this.removeEmpty(this.tokenize(s,i));return this.diffWithOptionsObj(u,l,i,o)}diffWithOptionsObj(e,t,i,o){var r;const s=c=>{if(c=this.postProcess(c,i),o){setTimeout(function(){o(c)},0);return}else return c},u=t.length,l=e.length;let d=1,a=u+l;i.maxEditLength!=null&&(a=Math.min(a,i.maxEditLength));const g=(r=i.timeout)!==null&&r!==void 0?r:1/0,v=Date.now()+g,f=[{oldPos:-1,lastComponent:void 0}];let h=this.extractCommon(f[0],t,e,0,i);if(f[0].oldPos+1>=l&&h+1>=u)return s(this.buildValues(f[0].lastComponent,t,e));let w=-1/0,y=1/0;const $=()=>{for(let c=Math.max(w,-d);c<=Math.min(y,d);c+=2){let p;const x=f[c-1],b=f[c+1];x&&(f[c-1]=void 0);let D=!1;if(b){const S=b.oldPos-c;D=b&&0<=S&&S<u}const k=x&&x.oldPos+1<l;if(!D&&!k){f[c]=void 0;continue}if(!k||D&&x.oldPos<b.oldPos?p=this.addToPath(b,!0,!1,0,i):p=this.addToPath(x,!1,!0,1,i),h=this.extractCommon(p,t,e,c,i),p.oldPos+1>=l&&h+1>=u)return s(this.buildValues(p.lastComponent,t,e))||!0;f[c]=p,p.oldPos+1>=l&&(y=Math.min(y,c-1)),h+1>=u&&(w=Math.max(w,c+1))}d++};if(o)(function c(){setTimeout(function(){if(d>a||Date.now()>v)return o(void 0);$()||c()},0)})();else for(;d<=a&&Date.now()<=v;){const c=$();if(c)return c}}addToPath(e,t,i,o,r){const s=e.lastComponent;return s&&!r.oneChangePerToken&&s.added===t&&s.removed===i?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:t,removed:i,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:t,removed:i,previousComponent:s}}}extractCommon(e,t,i,o,r){const s=t.length,u=i.length;let l=e.oldPos,d=l-o,a=0;for(;d+1<s&&l+1<u&&this.equals(i[l+1],t[d+1],r);)d++,l++,a++,r.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return a&&!r.oneChangePerToken&&(e.lastComponent={count:a,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,d}equals(e,t,i){return i.comparator?i.comparator(e,t):e===t||!!i.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){const t=[];for(let i=0;i<e.length;i++)e[i]&&t.push(e[i]);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,i){const o=[];let r;for(;e;)o.push(e),r=e.previousComponent,delete e.previousComponent,e=r;o.reverse();const s=o.length;let u=0,l=0,d=0;for(;u<s;u++){const a=o[u];if(a.removed)a.value=this.join(i.slice(d,d+a.count)),d+=a.count;else{if(!a.added&&this.useLongestToken){let g=t.slice(l,l+a.count);g=g.map(function(v,f){const h=i[d+f];return h.length>v.length?h:v}),a.value=this.join(g)}else a.value=this.join(t.slice(l,l+a.count));l+=a.count,a.added||(d+=a.count)}}return o}}class R extends U{}const q=new R;function j(n,e,t){return q.diff(n,e,t)}const B=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,C=5e3,H=20,G=.2,E=.25;function J(n){const e=K(n);return X(e),e}function K(n){const e=Q(n),t=[];let i,o;for(const r of e){const s=B.exec(r);if(s!==null){i=Number(s[1]),o=Number(s[2]),t.push(m("hunk","",r));continue}if(i!==void 0&&o!==void 0){if(r.startsWith("+")){t.push(m("add","+",r.slice(1),{newLineNumber:o})),o++;continue}if(r.startsWith("-")){t.push(m("remove","-",r.slice(1),{oldLineNumber:i})),i++;continue}if(r.startsWith(" ")){t.push(m("context"," ",r.slice(1),{oldLineNumber:i,newLineNumber:o})),i++,o++;continue}if(r.startsWith("\\")){t.push(m("marker","",r));continue}}i=void 0,o=void 0,t.push(m("meta","",r))}return t}function Q(n){if(n==="")return[];const e=n.replace(/\r\n/g,`
1
+ import{i as A,b as P,a as V,n as z,t as F}from"./index-Df4Ex27j.js";import"./vendor-editor-core-D9EJm1dE.js";import"./vendor-editor-languages-N6dcxgRO.js";class U{diff(e,t,i={}){let o;typeof i=="function"?(o=i,i={}):"callback"in i&&(o=i.callback);const r=this.castInput(e,i),s=this.castInput(t,i),u=this.removeEmpty(this.tokenize(r,i)),l=this.removeEmpty(this.tokenize(s,i));return this.diffWithOptionsObj(u,l,i,o)}diffWithOptionsObj(e,t,i,o){var r;const s=c=>{if(c=this.postProcess(c,i),o){setTimeout(function(){o(c)},0);return}else return c},u=t.length,l=e.length;let d=1,a=u+l;i.maxEditLength!=null&&(a=Math.min(a,i.maxEditLength));const g=(r=i.timeout)!==null&&r!==void 0?r:1/0,v=Date.now()+g,f=[{oldPos:-1,lastComponent:void 0}];let h=this.extractCommon(f[0],t,e,0,i);if(f[0].oldPos+1>=l&&h+1>=u)return s(this.buildValues(f[0].lastComponent,t,e));let w=-1/0,y=1/0;const $=()=>{for(let c=Math.max(w,-d);c<=Math.min(y,d);c+=2){let p;const x=f[c-1],b=f[c+1];x&&(f[c-1]=void 0);let D=!1;if(b){const S=b.oldPos-c;D=b&&0<=S&&S<u}const k=x&&x.oldPos+1<l;if(!D&&!k){f[c]=void 0;continue}if(!k||D&&x.oldPos<b.oldPos?p=this.addToPath(b,!0,!1,0,i):p=this.addToPath(x,!1,!0,1,i),h=this.extractCommon(p,t,e,c,i),p.oldPos+1>=l&&h+1>=u)return s(this.buildValues(p.lastComponent,t,e))||!0;f[c]=p,p.oldPos+1>=l&&(y=Math.min(y,c-1)),h+1>=u&&(w=Math.max(w,c+1))}d++};if(o)(function c(){setTimeout(function(){if(d>a||Date.now()>v)return o(void 0);$()||c()},0)})();else for(;d<=a&&Date.now()<=v;){const c=$();if(c)return c}}addToPath(e,t,i,o,r){const s=e.lastComponent;return s&&!r.oneChangePerToken&&s.added===t&&s.removed===i?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:t,removed:i,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:t,removed:i,previousComponent:s}}}extractCommon(e,t,i,o,r){const s=t.length,u=i.length;let l=e.oldPos,d=l-o,a=0;for(;d+1<s&&l+1<u&&this.equals(i[l+1],t[d+1],r);)d++,l++,a++,r.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return a&&!r.oneChangePerToken&&(e.lastComponent={count:a,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,d}equals(e,t,i){return i.comparator?i.comparator(e,t):e===t||!!i.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){const t=[];for(let i=0;i<e.length;i++)e[i]&&t.push(e[i]);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,i){const o=[];let r;for(;e;)o.push(e),r=e.previousComponent,delete e.previousComponent,e=r;o.reverse();const s=o.length;let u=0,l=0,d=0;for(;u<s;u++){const a=o[u];if(a.removed)a.value=this.join(i.slice(d,d+a.count)),d+=a.count;else{if(!a.added&&this.useLongestToken){let g=t.slice(l,l+a.count);g=g.map(function(v,f){const h=i[d+f];return h.length>v.length?h:v}),a.value=this.join(g)}else a.value=this.join(t.slice(l,l+a.count));l+=a.count,a.added||(d+=a.count)}}return o}}class R extends U{}const q=new R;function j(n,e,t){return q.diff(n,e,t)}const B=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,C=5e3,H=20,G=.2,E=.25;function J(n){const e=K(n);return X(e),e}function K(n){const e=Q(n),t=[];let i,o;for(const r of e){const s=B.exec(r);if(s!==null){i=Number(s[1]),o=Number(s[2]),t.push(m("hunk","",r));continue}if(i!==void 0&&o!==void 0){if(r.startsWith("+")){t.push(m("add","+",r.slice(1),{newLineNumber:o})),o++;continue}if(r.startsWith("-")){t.push(m("remove","-",r.slice(1),{oldLineNumber:i})),i++;continue}if(r.startsWith(" ")){t.push(m("context"," ",r.slice(1),{oldLineNumber:i,newLineNumber:o})),i++,o++;continue}if(r.startsWith("\\")){t.push(m("marker","",r));continue}}i=void 0,o=void 0,t.push(m("meta","",r))}return t}function Q(n){if(n==="")return[];const e=n.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
3
  `).split(`
4
4
  `);return e.at(-1)===""&&e.pop(),e}function m(n,e,t,i={}){return{kind:n,prefix:e,text:t,spans:t===""?[]:[{text:t,changed:!1}],...i}}function X(n){let e=0;for(;e<n.length;){if(n[e]?.kind!=="remove"){e++;continue}const i=e;for(;n[e]?.kind==="remove";)e++;const o=e;for(;n[e]?.kind==="add";)e++;if(o===e)continue;const r=n.slice(i,o),s=n.slice(o,e);Y(r,s)}}function Y(n,e){if(!(n.length+e.length>H))for(const t of Z(n,e)){const i=te(t.removed.text,t.added.text);i!==void 0&&(t.removed.spans=i.removed,t.added.spans=i.added)}}function Z(n,e){if(n.length===e.length)return n.map((o,r)=>({removed:o,added:e[r]})).filter(T);if(n.length===1)return ee(n[0],e);if(e.length===1)return ne(n,e[0]);const t=[],i=Math.min(n.length,e.length);for(let o=0;o<i;o++){const r=n[o],s=e[o];r===void 0||s===void 0||O(r.text,s.text)>=E&&t.push({removed:r,added:s})}return t}function T(n){return n.added!==void 0}function ee(n,e){if(n===void 0)return[];const t=N(n.text,e);return t===void 0?[]:[{removed:n,added:t}]}function ne(n,e){if(e===void 0)return[];const t=N(e.text,n);return t===void 0?[]:[{removed:t,added:e}]}function N(n,e){let t,i=E;for(const o of e){const r=O(n,o.text);r<=i||(t=o,i=r)}return t}function te(n,e){if(n===e||n.length>C||e.length>C)return;const t=j(n,e),i=_(t,n,e);if(Math.max(n.length,e.length)>=20&&i<G)return;const o=[],r=[];for(const s of t)s.value!==""&&(s.added?r.push({text:s.value,changed:!0}):s.removed?o.push({text:s.value,changed:!0}):(o.push({text:s.value,changed:!1}),r.push({text:s.value,changed:!1})));if(!(!o.some(s=>s.changed)&&!r.some(s=>s.changed)))return{removed:M(o),added:M(r)}}function O(n,e){return n===e?1:n.length>C||e.length>C?0:_(j(n,e),n,e)}function _(n,e,t){const i=Math.max(e.length,t.length);return i===0?1:n.reduce((r,s)=>s.added||s.removed?r:r+s.value.length,0)/i}function M(n){const e=[];for(const t of n){const i=e[e.length-1];i?.changed===t.changed?i.text+=t.text:e.push({...t})}return e}var ie=Object.defineProperty,oe=Object.getOwnPropertyDescriptor,W=(n,e,t,i)=>{for(var o=i>1?void 0:i?oe(e,t):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(o=(i?s(e,t,o):s(o))||o);return i&&o&&ie(e,t,o),o};let L=class extends A{constructor(){super(...arguments),this.diff=""}render(){const n=J(this.diff);return n.length===0?P`<p class="empty">No diff.</p>`:P`
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CJNBz-Ox.js","assets/vendor-editor-core-D9EJm1dE.js","assets/vendor-editor-languages-N6dcxgRO.js","assets/UnifiedDiffViewer-BUqme4se.js","assets/TerminalPanel-B9-LUv7E.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Mp4aTsTY.js","assets/vendor-editor-core-D9EJm1dE.js","assets/vendor-editor-languages-N6dcxgRO.js","assets/UnifiedDiffViewer-Db5Yxwri.js","assets/TerminalPanel-Cb2CgFtQ.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
2
  import{Q as aa,w as wi,J as wn,R as Lp,S as Wp,G as Op,U as _p,V as jp,A as Fp,W as Bp,X as Np,Y as la,x as ca,Z as zp,_ as Up}from"./vendor-editor-core-D9EJm1dE.js";import{m as Hp,d as qp,i as Kp}from"./vendor-editor-languages-N6dcxgRO.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&s(r)}).observe(document,{childList:!0,subtree:!0});function i(o){const n={};return o.integrity&&(n.integrity=o.integrity),o.referrerPolicy&&(n.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?n.credentials="include":o.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function s(o){if(o.ep)return;o.ep=!0;const n=i(o);fetch(o.href,n)}})();const fo=globalThis,fr=fo.ShadowRoot&&(fo.ShadyCSS===void 0||fo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gr=Symbol(),da=new WeakMap;let Pc=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==gr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(fr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=da.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&da.set(i,t))}return t}toString(){return this.cssText}};const Vp=e=>new Pc(typeof e=="string"?e:e+"",void 0,gr),me=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,n)=>s+(r=>{if(r._$cssResult$===!0)return r.cssText;if(typeof r=="number")return r;throw Error("Value passed to 'css' function must be a 'css' function result: "+r+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[n+1],e[0]);return new Pc(i,e,gr)},Gp=(e,t)=>{if(fr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=fo.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},pa=fr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Vp(i)})(e):e;const{is:Yp,defineProperty:Xp,getOwnPropertyDescriptor:Jp,getOwnPropertyNames:Qp,getOwnPropertySymbols:Zp,getPrototypeOf:eh}=Object,Jo=globalThis,ha=Jo.trustedTypes,th=ha?ha.emptyScript:"",ih=Jo.reactiveElementPolyfillSupport,Ds=(e,t)=>e,Po={toAttribute(e,t){switch(t){case Boolean:e=e?th:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},mr=(e,t)=>!Yp(e,t),ua={attribute:!0,type:String,converter:Po,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),Jo.litPropertyMetadata??=new WeakMap;let is=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=ua){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Xp(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:n}=Jp(this.prototype,t)??{get(){return this[i]},set(r){this[i]=r}};return{get:o,set(r){const a=o?.call(this);n?.call(this,r),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ua}static _$Ei(){if(this.hasOwnProperty(Ds("elementProperties")))return;const t=eh(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ds("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ds("properties"))){const i=this.properties,s=[...Qp(i),...Zp(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(pa(o))}else t!==void 0&&i.push(pa(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Gp(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const n=(s.converter?.toAttribute!==void 0?s.converter:Po).toAttribute(i,s.type);this._$Em=t,n==null?this.removeAttribute(o):this.setAttribute(o,n),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const n=s.getPropertyOptions(o),r=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Po;this._$Em=o;const a=r.fromAttribute(i,n.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,n){if(t!==void 0){const r=this.constructor;if(o===!1&&(n=this[t]),s??=r.getPropertyOptions(t),!((s.hasChanged??mr)(n,i)||s.useDefault&&s.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(r._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:n},r){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,r??i??this[t]),n!==!0||r!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,n]of this._$Ep)this[o]=n;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,n]of s){const{wrapped:r}=n,a=this[o];r!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,n,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};is.elementStyles=[],is.shadowRootOptions={mode:"open"},is[Ds("elementProperties")]=new Map,is[Ds("finalized")]=new Map,ih?.({ReactiveElement:is}),(Jo.reactiveElementVersions??=[]).push("2.1.2");const vr=globalThis,fa=e=>e,Co=vr.trustedTypes,ga=Co?Co.createPolicy("lit-html",{createHTML:e=>e}):void 0,Cc="$lit$",ki=`lit$${Math.random().toFixed(9).slice(2)}$`,Mc="?"+ki,sh=`<${Mc}>`,Hi=document,Ws=()=>Hi.createComment(""),Os=e=>e===null||typeof e!="object"&&typeof e!="function",br=Array.isArray,oh=e=>br(e)||typeof e?.[Symbol.iterator]=="function",yn=`[
3
3
  \f\r]`,vs=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ma=/-->/g,va=/>/g,Ei=RegExp(`>|${yn}(?:([^\\s"'>=/]+)(${yn}*=${yn}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),ba=/'/g,wa=/"/g,Rc=/^(?:script|style|textarea|title)$/i,Tc=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),u=Tc(1),bt=Tc(2),Ci=Symbol.for("lit-noChange"),Ce=Symbol.for("lit-nothing"),ya=new WeakMap,Fi=Hi.createTreeWalker(Hi,129);function Ac(e,t){if(!br(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return ga!==void 0?ga.createHTML(t):t}const nh=(e,t)=>{const i=e.length-1,s=[];let o,n=t===2?"<svg>":t===3?"<math>":"",r=vs;for(let a=0;a<i;a++){const l=e[a];let c,p,d=-1,h=0;for(;h<l.length&&(r.lastIndex=h,p=r.exec(l),p!==null);)h=r.lastIndex,r===vs?p[1]==="!--"?r=ma:p[1]!==void 0?r=va:p[2]!==void 0?(Rc.test(p[2])&&(o=RegExp("</"+p[2],"g")),r=Ei):p[3]!==void 0&&(r=Ei):r===Ei?p[0]===">"?(r=o??vs,d=-1):p[1]===void 0?d=-2:(d=r.lastIndex-p[2].length,c=p[1],r=p[3]===void 0?Ei:p[3]==='"'?wa:ba):r===wa||r===ba?r=Ei:r===ma||r===va?r=vs:(r=Ei,o=void 0);const g=r===Ei&&e[a+1].startsWith("/>")?" ":"";n+=r===vs?l+sh:d>=0?(s.push(c),l.slice(0,d)+Cc+l.slice(d)+ki+g):l+ki+(d===-2?a:g)}return[Ac(e,n+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class _s{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let n=0,r=0;const a=t.length-1,l=this.parts,[c,p]=nh(t,i);if(this.el=_s.createElement(c,s),Fi.currentNode=this.el.content,i===2||i===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(o=Fi.nextNode())!==null&&l.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const d of o.getAttributeNames())if(d.endsWith(Cc)){const h=p[r++],g=o.getAttribute(d).split(ki),m=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:m[2],strings:g,ctor:m[1]==="."?ah:m[1]==="?"?lh:m[1]==="@"?ch:Qo}),o.removeAttribute(d)}else d.startsWith(ki)&&(l.push({type:6,index:n}),o.removeAttribute(d));if(Rc.test(o.tagName)){const d=o.textContent.split(ki),h=d.length-1;if(h>0){o.textContent=Co?Co.emptyScript:"";for(let g=0;g<h;g++)o.append(d[g],Ws()),Fi.nextNode(),l.push({type:2,index:++n});o.append(d[h],Ws())}}}else if(o.nodeType===8)if(o.data===Mc)l.push({type:2,index:n});else{let d=-1;for(;(d=o.data.indexOf(ki,d+1))!==-1;)l.push({type:7,index:n}),d+=ki.length-1}n++}}static createElement(t,i){const s=Hi.createElement("template");return s.innerHTML=t,s}}function ls(e,t,i=e,s){if(t===Ci)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const n=Os(t)?void 0:t._$litDirective$;return o?.constructor!==n&&(o?._$AO?.(!1),n===void 0?o=void 0:(o=new n(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ls(e,o._$AS(e,t.values),o,s)),t}class rh{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Hi).importNode(i,!0);Fi.currentNode=o;let n=Fi.nextNode(),r=0,a=0,l=s[0];for(;l!==void 0;){if(r===l.index){let c;l.type===2?c=new us(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new dh(n,this,t)),this._$AV.push(c),l=s[++a]}r!==l?.index&&(n=Fi.nextNode(),r++)}return Fi.currentNode=Hi,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class us{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=Ce,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ls(this,t,i),Os(t)?t===Ce||t==null||t===""?(this._$AH!==Ce&&this._$AR(),this._$AH=Ce):t!==this._$AH&&t!==Ci&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):oh(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==Ce&&Os(this._$AH)?this._$AA.nextSibling.data=t:this.T(Hi.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=_s.createElement(Ac(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const n=new rh(o,this),r=n.u(this.options);n.p(i),this.T(r),this._$AH=n}}_$AC(t){let i=ya.get(t.strings);return i===void 0&&ya.set(t.strings,i=new _s(t)),i}k(t){br(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const n of t)o===i.length?i.push(s=new us(this.O(Ws()),this.O(Ws()),this,this.options)):s=i[o],s._$AI(n),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=fa(t).nextSibling;fa(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Qo=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,n){this.type=1,this._$AH=Ce,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=n,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=Ce}_$AI(t,i=this,s,o){const n=this.strings;let r=!1;if(n===void 0)t=ls(this,t,i,0),r=!Os(t)||t!==this._$AH&&t!==Ci,r&&(this._$AH=t);else{const a=t;let l,c;for(t=n[0],l=0;l<n.length-1;l++)c=ls(this,a[s+l],i,l),c===Ci&&(c=this._$AH[l]),r||=!Os(c)||c!==this._$AH[l],c===Ce?t=Ce:t!==Ce&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}r&&!o&&this.j(t)}j(t){t===Ce?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},ah=class extends Qo{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===Ce?void 0:t}},lh=class extends Qo{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==Ce)}},ch=class extends Qo{constructor(t,i,s,o,n){super(t,i,s,o,n),this.type=5}_$AI(t,i=this){if((t=ls(this,t,i,0)??Ce)===Ci)return;const s=this._$AH,o=t===Ce&&s!==Ce||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,n=t!==Ce&&(s===Ce||o);o&&this.element.removeEventListener(this.name,this,s),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},dh=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){ls(this,t)}};const ph={I:us},hh=vr.litHtmlPolyfillSupport;hh?.(_s,us),(vr.litHtmlVersions??=[]).push("3.3.3");const uh=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const n=i?.renderBefore??null;s._$litPart$=o=new us(t.insertBefore(Ws(),n),n,void 0,i??{})}return o._$AI(e),o};const wr=globalThis;let le=class extends is{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=uh(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ci}};le._$litElement$=!0,le.finalized=!0,wr.litElementHydrateSupport?.({LitElement:le});const fh=wr.litElementPolyfillSupport;fh?.({LitElement:le});(wr.litElementVersions??=[]).push("4.2.2");function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){return e instanceof Error?e.message:String(e)}const ue=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const gh={attribute:!0,type:String,converter:Po,reflect:!1,hasChanged:mr},mh=(e=gh,t,i)=>{const{kind:s,metadata:o}=i;let n=globalThis.litPropertyMetadata.get(o);if(n===void 0&&globalThis.litPropertyMetadata.set(o,n=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),n.set(i.name,e),s==="accessor"){const{name:r}=i;return{set(a){const l=t.get.call(this);t.set.call(this,a),this.requestUpdate(r,l,e,!0,a)},init(a){return a!==void 0&&this.C(r,void 0,e,a),a}}}if(s==="setter"){const{name:r}=i;return function(a){const l=this[r];t.call(this,a),this.requestUpdate(r,l,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function f(e){return(t,i)=>typeof i=="object"?mh(e,t,i):((s,o,n)=>{const r=o.hasOwnProperty(n);return o.constructor.createProperty(n,s),r?Object.getOwnPropertyDescriptor(o,n):void 0})(e,t,i)}function R(e){return f({...e,state:!0,attribute:!1})}const vh=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function We(e,t){return(i,s,o)=>{const n=r=>r.renderRoot?.querySelector(e)??null;return vh(i,s,{get(){return n(this)}})}}async function L(e,t){const i=new Headers(t?.headers);t?.body!==void 0&&!i.has("content-type")&&i.set("content-type","application/json");const s=await fetch(e,{...t,headers:i});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(bh(o)??s.statusText)}return await s.json()}function bh(e){if(Fe(e))return typeof e.error=="string"?e.error:void 0}function wh(e){return typeof e=="string"?e:e.id}function yh(e){return typeof e=="string"?void 0:e.cwd}function xh(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const n=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${n?`?${n}`:""}`}function Sh(e,t,i="local"){const s=new URLSearchParams,o=yh(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const n=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(wh(e))}/messages${n===""?"":`?${n}`}`}function kh(e,t,i,s){const o=new URLSearchParams({path:i});return s?.createDirs===!1&&o.set("createDirs","false"),s?.overwrite===!1&&o.set("overwrite","false"),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`}function $h(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function xa(e,t,i,s){const o=new URLSearchParams({path:i});return`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/raw?${o.toString()}`}const ae=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Ic(e){return typeof e=="string"?e:e.id}function yr(e){return typeof e=="string"?void 0:e.cwd}function Dc(e,t="local"){return`${ae(t)}/sessions/${encodeURIComponent(Ic(e))}`}function He(e,t,i="local"){return`${Dc(e,i)}/${t}`}function Qs(e,t,i="local"){return`${He(e,t,i)}${Ec(e)}`}function Ph(e,t="local"){return`${Dc(e,t)}${Ec(e)}`}function Ec(e){const t=yr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Je(e,t={}){const i=yr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Sa(e){return JSON.stringify({sessions:e.map(Ch)})}function Ch(e){const t=Ic(e),i=yr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const Lc={ompWebStatus:(e="local")=>L(e==="local"?"/api/omp-web/status":`${ae(e)}/omp-web/status`),ompWebRuntime:()=>L("/api/omp-web/runtime")},Mh={machines:()=>L("/api/machines"),addMachine:e=>L("/api/machines",{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>L(`/api/machines/${encodeURIComponent(e)}`,{method:"DELETE"}),health:e=>L(`/api/machines/${encodeURIComponent(e)}/health`),runtime:e=>L(`/api/machines/${encodeURIComponent(e)}/runtime`)};function ka(e){return e===void 0?"/api/config":`${ae(e)}/config`}function Rh(e){return e===void 0?"/api/plugins":`${ae(e)}/plugins`}const Gt={config:e=>L(ka(e)),saveConfig:(e,t)=>L(ka(t),{method:"PUT",body:JSON.stringify({config:e})})},Cs={plugins:e=>L(Rh(e))};function Zs(e="",t){const i=t===void 0?"/api/pi-packages":`${ae(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const Ms={packages:e=>L(Zs("",e)),install:(e,t)=>{const i={source:e};return L(Zs("install",t),{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return L(Zs("remove",i),{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return L(Zs("update",t),{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},Wc={workspaceActivity:(e="local")=>L(`${ae(e)}/activity`)},Th={projects:(e="local")=>L(`${ae(e)}/projects`),addProject:(e,t,i,s="local")=>L(`${ae(s)}/projects`,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>L(`${ae(t)}/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),projectDirectories:(e,t="local")=>L(`${ae(t)}/project-directories?q=${encodeURIComponent(e)}`)},ss={workspaces:(e,t="local")=>L(`${ae(t)}/projects/${e}/workspaces`),deleteWorkspace:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`),workspaceFile:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`),writeWorkspaceFile:(e,t,i,s,o,n="local")=>{const r=new URLSearchParams({path:i});o?.createDirs===!1&&r.set("createDirs","false"),o?.overwrite===!1&&r.set("overwrite","false");const a=s instanceof Uint8Array,l=a?new Uint8Array(s):new TextEncoder().encode(s);return L(`${ae(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,{method:"PUT",body:l,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const o=new URLSearchParams({path:i});return L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,o,n="local")=>{const r=new URLSearchParams({fromPath:i,toPath:s});return o?.createDirs===!1&&r.set("createDirs","false"),o?.overwrite===!0&&r.set("overwrite","true"),L(`${ae(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${r.toString()}`,{method:"POST"})}},Xn={sessions:(e,t="local")=>L(`${ae(t)}/sessions?cwd=${encodeURIComponent(e)}`),startSession:(e,t="local")=>L(`${ae(t)}/sessions`,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>L(`${ae(t)}/sessions/cleanup/preview`,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>L(`${ae(t)}/sessions/cleanup`,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>L(`${ae(t)}/sessions/bulk/archive`,{method:"POST",body:Sa(e)}),deleteArchivedMany:(e,t="local")=>L(`${ae(t)}/sessions/bulk/delete-archived`,{method:"POST",body:Sa(e)}),messages:(e,t,i="local")=>L(Sh(e,t,i)),status:(e,t="local")=>L(Qs(e,"status",t)),models:(e,t="local")=>L(Qs(e,"models",t)),setModel:(e,t,i,s,o)=>{const n=typeof s=="boolean"?s:void 0;return L(He(e,"model",typeof s=="string"?s:o??"local"),{method:"POST",body:Je(e,{provider:t,modelId:i,...n===!0?{persist:!0}:{}})})},cycleModel:(e,t,i="local")=>L(He(e,"model/cycle",i),{method:"POST",body:Je(e,{direction:t})}),thinkingLevels:(e,t="local")=>L(Qs(e,"thinking-levels",t)),setThinkingLevel:(e,t,i="local")=>L(He(e,"thinking-level",i),{method:"POST",body:Je(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>L(He(e,"thinking-level/cycle",t),{method:"POST",body:Je(e)}),commands:(e,t="local")=>L(Qs(e,"commands",t)),prompt:(e,t,i,s="local",o)=>L(He(e,"prompt",s),{method:"POST",body:Je(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>L(He(e,"attachments",i),{method:"POST",body:Je(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>L(He(e,"shell",i),{method:"POST",body:Je(e,{text:t})}),runCommand:(e,t,i="local")=>L(He(e,"commands/run",i),{method:"POST",body:Je(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>L(He(e,"commands/respond",s),{method:"POST",body:Je(e,{requestId:t,value:i})}),respondToAsk:(e,t,i,s="local")=>L(He(e,"ask/respond",s),{method:"POST",body:Je(e,{requestId:t,result:i})}),abort:(e,t="local")=>L(He(e,"abort",t),{method:"POST",body:Je(e)}),stop:(e,t="local")=>L(He(e,"stop",t),{method:"POST",body:Je(e)}),archive:(e,t="local")=>L(He(e,"archive",t),{method:"POST",body:Je(e)}),archiveWithDescendants:(e,t="local")=>L(He(e,"archive-tree",t),{method:"POST",body:Je(e)}),restore:(e,t="local")=>L(He(e,"restore",t),{method:"POST",body:Je(e)}),deleteArchived:(e,t="local")=>L(Ph(e,t),{method:"DELETE"}),detachParent:(e,t="local")=>L(He(e,"detach-parent",t),{method:"POST",body:Je(e)}),reloadSession:(e,t="local")=>L(He(e,"reload",t),{method:"POST",body:Je(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return L(`${ae(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`)},saveApiKey:(e,t,i="local")=>L(`${ae(i)}/auth/api-key`,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>L(`${ae(t)}/auth/logout`,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>L(`${ae(t)}/auth/oauth`,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>L(`${ae(t)}/auth/oauth/${encodeURIComponent(e)}`),respondOAuthFlow:(e,t,i,s="local")=>L(`${ae(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>L(`${ae(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,{method:"POST"})},ns={terminals:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`),startTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>L(`${ae(t)}/terminal-command-runs${Ih(e)}`),getCommandRun:(e,t="local")=>Ah(e,t),cancelCommandRun:(e,t="local")=>L(`${ae(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,{method:"POST"})};async function Ah(e,t){const i=await fetch(`${ae(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Dh(s)??i.statusText)}return await i.json()}}function Ih(e){if(e===void 0)return"";const 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));const i=t.toString();return i===""?"":`?${i}`}function Dh(e){if(!Fe(e))return;const t=e.error;return typeof t=="string"?t:void 0}const Eh={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?L(`${ae(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`):(s.set("cwd",e),L(`${ae(i.machineId)}/files?${s.toString()}`))}},Lh={gitStatus:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`),gitDiff:(e,t,i,s="local")=>L(xh(s,e,t,i))},_e={...Lc,...Mh,...Gt,...Cs,...Ms,...Wc,...Th,...ss,...Xn,...ns,...Eh,...Lh};function Wh(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Sr()}${xr(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function a1(e,t,i,s,o="local"){const n=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Sr()}${xr(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${n}`)}function Oh(e="local"){return new WebSocket(`${Sr()}${xr(e)}/events`)}function xr(e){return`/api/machines/${encodeURIComponent(e)}`}function Sr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const Es=".omp-web/uploads";class Zo extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Oc extends Error{constructor(t,i){super(Hh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function $a(e){return e?.uploads?.defaultFolder??Es}function _h(e,t){return e?.uploads?.defaultFolder??t}function kr(e,t){const i=Pa(e,"upload destination",{allowEmpty:!0}),s=Pa(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function jh(e,t,i,s={}){const o=s.xhrFactory?.()??new XMLHttpRequest;let n=!1,r=!1;return{promise:new Promise((l,c)=>{const p=h=>{n||(n=!0,c(h))},d=h=>{n||(n=!0,l(h))};o.open("PUT",kh(e,t,i.path,Nh(s)),!0),o.responseType="json",o.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),o.upload.onprogress=h=>{s.onProgress?.(zh(h,i.file.size))},o.onload=()=>{if(o.status>=200&&o.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),d(_c(o))}catch(h){p(h instanceof Error?h:new Error(String(h)))}return}p(new Error(Vh(o)))},o.onerror=()=>{p(new Error("Workspace upload failed"))},o.onabort=()=>{p(new Zo(r?void 0:"Workspace upload aborted"))},o.send(i.file)}),cancel:()=>{n||(r=!0,o.abort())}}}function Fh(e,t,i,s={}){const o=s.destinationFolder??Es,n=i.map((d,h)=>({index:h,name:d.name,path:kr(o,d.name),loaded:0,total:d.size,percent:$r(0,d.size),lengthComputable:!0,done:!1}));let r,a=0;const l={requested:!1},c=()=>{s.onProgress?.(Uh(n,a,n.every(d=>d.done)))};return{promise:(async()=>{const d=[],h=[];for(let g=0;g<i.length;g+=1){if(l.requested)throw new Zo;a=g;const m=i[g],v=n[g];if(!(m===void 0||v===void 0)){r=jh(e,t,{path:v.path,file:m},{...Bh(s),onProgress:w=>{v.total=w.total,v.loaded=Math.min(w.loaded,v.total),v.percent=w.percent,v.lengthComputable=w.lengthComputable,c()}});try{const w=await r.promise;v.loaded=v.total,v.percent=1,v.lengthComputable=!0,v.done=!0,d.push(w),c()}catch(w){if(qh(w,l))throw w;const x=Re(w);v.loaded=v.total,v.percent=1,v.lengthComputable=!0,v.done=!0,v.error=x,h.push({index:g,name:m.name,path:v.path,error:x}),c()}finally{r=void 0}}}if(h.length>0)throw new Oc(h,d);return d})(),cancel:()=>{l.requested=!0,r?.cancel()}}}function Bh(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 Nh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function zh(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:$r(e.loaded,i),lengthComputable:e.lengthComputable}}function Uh(e,t,i){const s=e.reduce((n,r)=>n+r.total,0),o=e.reduce((n,r)=>n+r.loaded,0);return{currentFileIndex:t,files:e.map(n=>({...n})),loaded:o,total:s,percent:$r(o,s),done:i}}function $r(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Hh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function qh(e,t){return t.requested||e instanceof Zo}function Pa(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Kh(s))throw new Error(`${t} must be workspace-relative`);const o=s.split(/[\\/]+/u).filter(n=>n!==""&&n!==".");if(o.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(o.some(n=>n===".."))throw new Error(`${t} must not contain path traversal`);return o.join("/")}function Kh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function _c(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Vh(e){const t=Gh(e);return Fe(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function Gh(e){try{return _c(e)}catch{return}}function go(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Yh(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,planReviewDialog:void 0,askDialog:void 0,btwState:void 0,modelDialog:void 0,modelActionDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,ompWebStatus:void 0,error:""}}const kt={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},Xh=Object.values(kt);new Set(Xh);function jt(e,t){return e?.capabilities?.includes(t)===!0}function Mi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function jc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Fc="local";function xn(e,t){return`${e}:${t}`}function Bc(e,t){return`${e}:${t}`}function C(e){return e.selectedMachine?.id??Fc}class Jh{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Wc}async refresh(t=C(this.getState())){this.applyMachineActivitySnapshot(t,Qh(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=C(this.getState())){const s=this.getState(),o=C(s)===i,n=s.machineActivities[i]??(o?s.workspaceActivities:{}),r=Zh(n,t);this.setState({machineActivities:{...s.machineActivities,[i]:r},...o?{workspaceActivities:r}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...C(s)===t?{workspaceActivities:i}:{}})}}function Qh(e){const t={};for(const i of e.workspaces)jc(i)&&(t[i.cwd]=i);return t}function Zh(e,t){const i={...e};return jc(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class eu{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??_e,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=tu(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:C(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(n=>n.id===t&&(i===void 0||n.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,C(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:C(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,C(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",n={...i};delete n.error,this.setState({authDialog:{...n,responding:!0}});try{const r=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,C(this.getState()));this.updateOAuthFlow(r)}catch(r){this.setState({authDialog:{...i,responding:!1,error:String(r)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,C(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:C(this.getState())}),s=i.filter(n=>n.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,C(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,n=t.prompt?.requestId??t.select?.requestId,r=o!==void 0&&o===n,a=r?s:"",l=r&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:l}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,C(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,C(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function tu(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Ns(e){return e.replaceAll(":",".")}function iu(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,n]of t.entries()){if(!o.startsWith(i))continue;const r=o.slice(i.length),a=s[r];a===void 0?s[r]=n:Array.isArray(a)?a.push(n):s[r]=[a,n]}return s}function Sn(e,t){const i=iu(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function Wt(e,t,i,s){const o=new URL(window.location.href),n=`${e}--${t}`;if(o.searchParams.delete(n),i!=null&&i!=="")if(Array.isArray(i))for(const r of i)o.searchParams.append(n,String(r));else o.searchParams.set(n,String(i));su(o,s)}function su(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function ou(e){const t=e.files.map((s,o)=>{const n=s.size;return{index:o,name:s.name,path:kr(e.destinationFolder,s.name),size:s.size,loaded:0,total:n,percent:Ma(0,n),lengthComputable:!0,status:o===0?"uploading":"pending"}}),i=t.reduce((s,o)=>s+o.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:i,percent:Ma(0,i),status:"uploading",startedAt:e.startedAt}}function nu(e,t){const i=new Map(t.files.map(o=>[o.index,o])),s=e.files.map(o=>{const n=i.get(o.index);if(n===void 0)return o;const r={...o,path:n.path,loaded:n.loaded,total:n.total,percent:n.percent,lengthComputable:n.lengthComputable,status:n.error!==void 0?"error":n.done?"completed":t.currentFileIndex===o.index?"uploading":o.status};return n.error===void 0?delete r.error:r.error=n.error,r});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function ru(e,t,i){const s=e.files.map((n,r)=>{const a=t[r];return{...n,...a===void 0?{}:{path:a.path,response:a},loaded:n.total,percent:1,lengthComputable:!0,status:"completed"}}),o=Pr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...o,status:"completed",completedAt:i}}function au(e,t,i){const s=e.files.map(o=>o.status==="completed"||o.status==="error"?o:o.status==="uploading"||o.index===e.currentFileIndex?{...o,status:"error",error:t}:{...o,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Pr(s),status:"error",error:t,completedAt:i}}function Ca(e,t){const i="Upload cancelled",s=e.files.map(o=>o.status==="completed"||o.status==="error"?o:{...o,status:"cancelled",error:i});return{...e,files:s,...Pr(s),status:"cancelled",error:i,completedAt:t}}function Pr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Ma(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const Ra=Ns("core:workspace.files");class lu{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=o.api??_e,this.uploadWorkspaceFiles=o.uploadWorkspaceFiles??Fh,this.createUploadBatchId=o.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=o.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=C(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),n={...this.getState().expandedDirs};await Promise.all(Object.keys(n).map(async r=>{n[r]=(await this.api.workspaceTree(t.id,i.id,r,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Ta(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,C(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Wt(Ra,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,C(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(cu(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Wt(Ra,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,o=this.getState().selectedWorkspace;if(s===void 0||o===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const n=C(this.getState()),r=i.overwrite??!1,a=i.createDirs??!0;let l;try{l=ou({id:this.createUploadBatchId(),projectId:s.id,workspaceId:o.id,machineId:n,destinationFolder:i.destinationFolder,overwrite:r,createDirs:a,files:t,startedAt:this.now()})}catch(d){this.setState({error:String(d)});return}this.setUploadBatch(l);let c;try{c=this.uploadWorkspaceFiles(s.id,o.id,t,{destinationFolder:i.destinationFolder,machineId:n,overwrite:r,createDirs:a,onProgress:d=>{this.updateUploadProgress(l.id,d)}})}catch(d){return this.failUploadBatch(l.id,d),{batchId:l.id,done:Promise.resolve()}}this.uploadTasks.set(l.id,c);const p=c.promise.then(async d=>{await this.completeUploadBatch(l.id,d,i)}).catch(async d=>{await this.handleUploadFailure(l.id,d,i)}).finally(()=>{this.uploadTasks.delete(l.id)});return{batchId:l.id,done:p}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(Ca(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Ta(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(nu(s,i))}async completeUploadBatch(t,i,s){const o=this.getUploadBatch(t);if(o?.status!=="uploading"||(this.setUploadBatch(ru(o,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(o)))return;await this.refreshFiles();const n=i[0]?.path;s.selectUploadedFile!==!1&&n!==void 0&&this.isCurrentWorkspaceBatch(o)&&await this.selectFile(n)}async handleUploadFailure(t,i,s){const o=this.failUploadBatch(t,i);if(!(i instanceof Oc)||i.responses.length===0||o===void 0||!this.isCurrentWorkspaceBatch(o))return;await this.refreshFiles();const n=i.responses[0]?.path;s.selectUploadedFile!==!1&&n!==void 0&&this.isCurrentWorkspaceBatch(o)&&await this.selectFile(n)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(du(i)){const r=Ca(s,this.now());return this.setUploadBatch(r),r}const o=Re(i),n=au(s,o,this.now());return this.setUploadBatch(n,{error:o}),n}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&C(i)===t.machineId}}function cu(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function du(e){return e instanceof Zo}function Ta(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Aa=Ns("core:workspace.git");class pu{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await _e.gitStatus(t.id,i.id,C(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(n=>n.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Wt(Aa,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),Wt(Aa,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,n]=await Promise.all([_e.gitDiff(i.id,s.id,{path:t},C(this.getState())),_e.gitDiff(i.id,s.id,{path:t,staged:!0},C(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:n,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class hu{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await _e.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(n=>n.id));this.setState({machines:i,selectedMachine:s,machineActivities:Ia(this.getState().machineActivities,o),machineRuntimes:Ia(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,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,...go()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await _e.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await _e.deleteMachine(t.id);const o=this.getState().machines.filter(r=>r.id!==t.id),n=o.find(r=>r.id==="local")??o[0];return this.setState({machines:o,machineStatuses:kn(this.getState().machineStatuses,t.id),machineRuntimes:kn(this.getState().machineRuntimes,t.id),machineActivities:kn(this.getState().machineActivities,t.id)}),s&&n!==void 0?(i.selectFallback===!1||await this.selectMachine(n),n):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await _e.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await _e.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await _e.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>_e.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>_e.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function kn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ia(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class uu{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=C(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await _e.projects(t);if(C(this.getState())!==t)return;const s=new Set(i.map(n=>n.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([n])=>s.has(n)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){C(this.getState())===t&&this.setState({error:String(i)})}finally{C(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await _e.addProject(t.trim(),void 0,i,C(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(n=>n.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await _e.closeProject(t,C(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Jn="omp-web:cached-new-sessions:v1",fu="browserCachedNew",fs="local";function zs(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Da(e,t=fs,i=zs()){if(e.messageCount!==0||e.archived===!0)return;const s=Cr(i).filter(o=>o.id!==e.id||o.machineId!==t);Mr([Qn(e,t),...s],i)}function Qn(e,t=fs){return{...e,browserCachedNew:!0,machineId:t}}function Ea(e,t=fs,i=zs()){const s=Cr(i).filter(o=>o.id!==e||o.machineId!==t);Mr(s,i)}function Nc(e,t,i=fs,s=zs()){const o=new Set(t.map(l=>l.id)),n=Cr(s),r=n.filter(l=>l.machineId!==i||!o.has(l.id));return r.length!==n.length&&Mr(r,s),[...r.filter(l=>l.machineId===i&&l.cwd===e),...t]}function Mo(e){return e===void 0?!1:vu(e)&&e.browserCachedNew===!0}function gu(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:fs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Cr(e=zs()){try{const t=e?.getItem(Jn);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>mu(s)):[]}catch{return[]}}function Mr(e,t=zs()){try{e.length===0?t?.removeItem(Jn):t?.setItem(Jn,JSON.stringify(e))}catch{}}function mu(e){if(!Fe(e))return[];const t=Xi(e,"id"),i=Xi(e,"path"),s=Xi(e,"cwd"),o=Xi(e,"created"),n=Xi(e,"modified"),r=Xi(e,"firstMessage"),a=bu(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||n===void 0||r===void 0||a!==0)return[];const l=$n(e,"name"),c=$n(e,"parentSessionPath"),p=$n(e,"machineId")??fs;return[{id:t,path:i,cwd:s,...l===void 0?{}:{name:l},created:o,modified:n,messageCount:a,firstMessage:r,...c===void 0?{}:{parentSessionPath:c},machineId:p,browserCachedNew:!0}]}function vu(e){return fu in e}function Xi(e,t){const i=e[t];return typeof i=="string"?i:void 0}function $n(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function bu(e,t){const i=e[t];return typeof i=="number"?i:void 0}function wu(e){return Ou(e.flatMap(Rr)).filter(t=>t.parts.length>0)}function Yt(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Ji(e,t){const i=Ru(t);return i===void 0?e:{...e,meta:i}}function yu(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Yt(t,i)]}function xu(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Rr(e){if(ku(e))return[e];if(ke(e,"role")==="bashExecution")return[Ji(Iu(e),e)];const t=Pu(e);if(t!==void 0)return t.map(p=>Ji(p,e));const i=Du(ke(e,"role")),s=Eu(Mt(e,"content"),e),o=i==="user"?$u(s):void 0;if(o!==void 0)return o.map(p=>Ji(p,e));const n=Mu(e);if(i==="tool")return[Ji({role:i,parts:s,...n===void 0?{}:{source:n}},e)];const r=s.filter(p=>p.type!=="empty"),a=i==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":i,l=r.length>0?[Ji({role:a,parts:r,...n===void 0?{}:{source:n}},e)]:[],c=Su(e);return c===void 0?l:[...l,Ji(c,e)]}function Su(e){if(ke(e,"role")!=="assistant"||ke(e,"stopReason")!=="error")return;const t=ke(e,"errorMessage")?.trim();return Yt("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function ku(e){const t=ke(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Mt(e,"parts"))}function $u(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Cu(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 Pu(e){if(!Fe(e)||e.customType!=="skill-prompt")return;const t=Fe(e.details)?e.details:void 0,i=typeof t?.name=="string"?t.name:"skill",s=typeof t?.path=="string"?t.path:"",o=typeof e.content=="string"?e.content:"",n=typeof t?.args=="string"&&t.args.trim()!==""?t.args.trim():void 0;return[{role:"user",parts:[{type:"skillInvocation",name:i,location:s,content:o},...n!==void 0?[{type:"text",text:n}]:[]]}]}function Cu(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t!==null){const s=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...s===void 0||s===""?{}:{userMessage:s}}}const i=/^\[IMPORTANT: User invoked the "([^"]+)" skill; follow its instructions\. Full skill below\.\]\n\n([\s\S]*?)(?:\n\n---\n\n\[Skill directory: ([^\]]+)\][\s\S]*?(?:\nUser: ([\s\S]+))?)?$/.exec(e);if(i!==null){const s=i[4]?.trim();return{name:i[1]??"skill",location:i[3]??"",content:i[2]??"",...s===void 0||s===""?{}:{userMessage:s}}}}function Mu(e){const t=ke(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ru(e){const t=Tu(Mt(e,"timestamp")),i=Au(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Tu(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Au(e){if(ke(e,"role")!=="assistant")return;const t=ke(e,"provider"),i=ke(e,"model"),s=ke(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Iu(e){const t=ke(e,"command")??"",i=mo(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Mt(e,"output");s!=null&&i.push("",To(s));const o=Mt(e,"exitCode");o!=null&&i.push("",`exit ${To(o)}`),mo(e,"cancelled")===!0&&i.push("","cancelled"),mo(e,"truncated")===!0&&i.push("","output truncated");const n=ke(e,"fullOutputPath");return n!==void 0&&n!==""&&i.push("",`full output: ${n}`),{role:"bash",parts:[{type:"text",text:i.join(`
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),ba=/'/g,wa=/"/g,Rc=/^(?:script|style|textarea|title)$/i,Tc=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),u=Tc(1),bt=Tc(2),Ci=Symbol.for("lit-noChange"),Ce=Symbol.for("lit-nothing"),ya=new WeakMap,Fi=Hi.createTreeWalker(Hi,129);function Ac(e,t){if(!br(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return ga!==void 0?ga.createHTML(t):t}const nh=(e,t)=>{const i=e.length-1,s=[];let o,n=t===2?"<svg>":t===3?"<math>":"",r=vs;for(let a=0;a<i;a++){const l=e[a];let c,p,d=-1,h=0;for(;h<l.length&&(r.lastIndex=h,p=r.exec(l),p!==null);)h=r.lastIndex,r===vs?p[1]==="!--"?r=ma:p[1]!==void 0?r=va:p[2]!==void 0?(Rc.test(p[2])&&(o=RegExp("</"+p[2],"g")),r=Ei):p[3]!==void 0&&(r=Ei):r===Ei?p[0]===">"?(r=o??vs,d=-1):p[1]===void 0?d=-2:(d=r.lastIndex-p[2].length,c=p[1],r=p[3]===void 0?Ei:p[3]==='"'?wa:ba):r===wa||r===ba?r=Ei:r===ma||r===va?r=vs:(r=Ei,o=void 0);const g=r===Ei&&e[a+1].startsWith("/>")?" ":"";n+=r===vs?l+sh:d>=0?(s.push(c),l.slice(0,d)+Cc+l.slice(d)+ki+g):l+ki+(d===-2?a:g)}return[Ac(e,n+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class _s{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let n=0,r=0;const a=t.length-1,l=this.parts,[c,p]=nh(t,i);if(this.el=_s.createElement(c,s),Fi.currentNode=this.el.content,i===2||i===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(o=Fi.nextNode())!==null&&l.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const d of o.getAttributeNames())if(d.endsWith(Cc)){const h=p[r++],g=o.getAttribute(d).split(ki),m=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:m[2],strings:g,ctor:m[1]==="."?ah:m[1]==="?"?lh:m[1]==="@"?ch:Qo}),o.removeAttribute(d)}else d.startsWith(ki)&&(l.push({type:6,index:n}),o.removeAttribute(d));if(Rc.test(o.tagName)){const d=o.textContent.split(ki),h=d.length-1;if(h>0){o.textContent=Co?Co.emptyScript:"";for(let g=0;g<h;g++)o.append(d[g],Ws()),Fi.nextNode(),l.push({type:2,index:++n});o.append(d[h],Ws())}}}else if(o.nodeType===8)if(o.data===Mc)l.push({type:2,index:n});else{let d=-1;for(;(d=o.data.indexOf(ki,d+1))!==-1;)l.push({type:7,index:n}),d+=ki.length-1}n++}}static createElement(t,i){const s=Hi.createElement("template");return s.innerHTML=t,s}}function ls(e,t,i=e,s){if(t===Ci)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const n=Os(t)?void 0:t._$litDirective$;return o?.constructor!==n&&(o?._$AO?.(!1),n===void 0?o=void 0:(o=new n(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ls(e,o._$AS(e,t.values),o,s)),t}class rh{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Hi).importNode(i,!0);Fi.currentNode=o;let n=Fi.nextNode(),r=0,a=0,l=s[0];for(;l!==void 0;){if(r===l.index){let c;l.type===2?c=new us(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new dh(n,this,t)),this._$AV.push(c),l=s[++a]}r!==l?.index&&(n=Fi.nextNode(),r++)}return Fi.currentNode=Hi,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class us{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=Ce,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ls(this,t,i),Os(t)?t===Ce||t==null||t===""?(this._$AH!==Ce&&this._$AR(),this._$AH=Ce):t!==this._$AH&&t!==Ci&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):oh(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==Ce&&Os(this._$AH)?this._$AA.nextSibling.data=t:this.T(Hi.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=_s.createElement(Ac(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const n=new rh(o,this),r=n.u(this.options);n.p(i),this.T(r),this._$AH=n}}_$AC(t){let i=ya.get(t.strings);return i===void 0&&ya.set(t.strings,i=new _s(t)),i}k(t){br(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const n of t)o===i.length?i.push(s=new us(this.O(Ws()),this.O(Ws()),this,this.options)):s=i[o],s._$AI(n),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=fa(t).nextSibling;fa(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Qo=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,n){this.type=1,this._$AH=Ce,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=n,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=Ce}_$AI(t,i=this,s,o){const n=this.strings;let r=!1;if(n===void 0)t=ls(this,t,i,0),r=!Os(t)||t!==this._$AH&&t!==Ci,r&&(this._$AH=t);else{const a=t;let l,c;for(t=n[0],l=0;l<n.length-1;l++)c=ls(this,a[s+l],i,l),c===Ci&&(c=this._$AH[l]),r||=!Os(c)||c!==this._$AH[l],c===Ce?t=Ce:t!==Ce&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}r&&!o&&this.j(t)}j(t){t===Ce?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},ah=class extends Qo{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===Ce?void 0:t}},lh=class extends Qo{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==Ce)}},ch=class extends Qo{constructor(t,i,s,o,n){super(t,i,s,o,n),this.type=5}_$AI(t,i=this){if((t=ls(this,t,i,0)??Ce)===Ci)return;const s=this._$AH,o=t===Ce&&s!==Ce||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,n=t!==Ce&&(s===Ce||o);o&&this.element.removeEventListener(this.name,this,s),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},dh=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){ls(this,t)}};const ph={I:us},hh=vr.litHtmlPolyfillSupport;hh?.(_s,us),(vr.litHtmlVersions??=[]).push("3.3.3");const uh=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const n=i?.renderBefore??null;s._$litPart$=o=new us(t.insertBefore(Ws(),n),n,void 0,i??{})}return o._$AI(e),o};const wr=globalThis;let le=class extends is{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=uh(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ci}};le._$litElement$=!0,le.finalized=!0,wr.litElementHydrateSupport?.({LitElement:le});const fh=wr.litElementPolyfillSupport;fh?.({LitElement:le});(wr.litElementVersions??=[]).push("4.2.2");function Fe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){return e instanceof Error?e.message:String(e)}const ue=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const gh={attribute:!0,type:String,converter:Po,reflect:!1,hasChanged:mr},mh=(e=gh,t,i)=>{const{kind:s,metadata:o}=i;let n=globalThis.litPropertyMetadata.get(o);if(n===void 0&&globalThis.litPropertyMetadata.set(o,n=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),n.set(i.name,e),s==="accessor"){const{name:r}=i;return{set(a){const l=t.get.call(this);t.set.call(this,a),this.requestUpdate(r,l,e,!0,a)},init(a){return a!==void 0&&this.C(r,void 0,e,a),a}}}if(s==="setter"){const{name:r}=i;return function(a){const l=this[r];t.call(this,a),this.requestUpdate(r,l,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function f(e){return(t,i)=>typeof i=="object"?mh(e,t,i):((s,o,n)=>{const r=o.hasOwnProperty(n);return o.constructor.createProperty(n,s),r?Object.getOwnPropertyDescriptor(o,n):void 0})(e,t,i)}function R(e){return f({...e,state:!0,attribute:!1})}const vh=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function We(e,t){return(i,s,o)=>{const n=r=>r.renderRoot?.querySelector(e)??null;return vh(i,s,{get(){return n(this)}})}}async function L(e,t){const i=new Headers(t?.headers);t?.body!==void 0&&!i.has("content-type")&&i.set("content-type","application/json");const s=await fetch(e,{...t,headers:i});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(bh(o)??s.statusText)}return await s.json()}function bh(e){if(Fe(e))return typeof e.error=="string"?e.error:void 0}function wh(e){return typeof e=="string"?e:e.id}function yh(e){return typeof e=="string"?void 0:e.cwd}function xh(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const n=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${n?`?${n}`:""}`}function Sh(e,t,i="local"){const s=new URLSearchParams,o=yh(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const n=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(wh(e))}/messages${n===""?"":`?${n}`}`}function kh(e,t,i,s){const o=new URLSearchParams({path:i});return s?.createDirs===!1&&o.set("createDirs","false"),s?.overwrite===!1&&o.set("overwrite","false"),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`}function $h(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function xa(e,t,i,s){const o=new URLSearchParams({path:i});return`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/raw?${o.toString()}`}const ae=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Ic(e){return typeof e=="string"?e:e.id}function yr(e){return typeof e=="string"?void 0:e.cwd}function Dc(e,t="local"){return`${ae(t)}/sessions/${encodeURIComponent(Ic(e))}`}function He(e,t,i="local"){return`${Dc(e,i)}/${t}`}function Qs(e,t,i="local"){return`${He(e,t,i)}${Ec(e)}`}function Ph(e,t="local"){return`${Dc(e,t)}${Ec(e)}`}function Ec(e){const t=yr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Je(e,t={}){const i=yr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Sa(e){return JSON.stringify({sessions:e.map(Ch)})}function Ch(e){const t=Ic(e),i=yr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const Lc={ompWebStatus:(e="local")=>L(e==="local"?"/api/omp-web/status":`${ae(e)}/omp-web/status`),ompWebRuntime:()=>L("/api/omp-web/runtime")},Mh={machines:async()=>{const e=await L("/api/machines");return Array.isArray(e)?e:e.machines??[]},addMachine:e=>L("/api/machines",{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>L(`/api/machines/${encodeURIComponent(e)}`,{method:"DELETE"}),health:e=>L(`/api/machines/${encodeURIComponent(e)}/health`),runtime:e=>L(`/api/machines/${encodeURIComponent(e)}/runtime`)};function ka(e){return e===void 0?"/api/config":`${ae(e)}/config`}function Rh(e){return e===void 0?"/api/plugins":`${ae(e)}/plugins`}const Gt={config:e=>L(ka(e)),saveConfig:(e,t)=>L(ka(t),{method:"PUT",body:JSON.stringify({config:e})})},Cs={plugins:e=>L(Rh(e))};function Zs(e="",t){const i=t===void 0?"/api/pi-packages":`${ae(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const Ms={packages:e=>L(Zs("",e)),install:(e,t)=>{const i={source:e};return L(Zs("install",t),{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return L(Zs("remove",i),{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return L(Zs("update",t),{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},Wc={workspaceActivity:(e="local")=>L(`${ae(e)}/activity`)},Th={projects:(e="local")=>L(`${ae(e)}/projects`),addProject:(e,t,i,s="local")=>L(`${ae(s)}/projects`,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>L(`${ae(t)}/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),projectDirectories:(e,t="local")=>L(`${ae(t)}/project-directories?q=${encodeURIComponent(e)}`)},ss={workspaces:(e,t="local")=>L(`${ae(t)}/projects/${e}/workspaces`),deleteWorkspace:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`),workspaceFile:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`),writeWorkspaceFile:(e,t,i,s,o,n="local")=>{const r=new URLSearchParams({path:i});o?.createDirs===!1&&r.set("createDirs","false"),o?.overwrite===!1&&r.set("overwrite","false");const a=s instanceof Uint8Array,l=a?new Uint8Array(s):new TextEncoder().encode(s);return L(`${ae(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,{method:"PUT",body:l,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const o=new URLSearchParams({path:i});return L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,o,n="local")=>{const r=new URLSearchParams({fromPath:i,toPath:s});return o?.createDirs===!1&&r.set("createDirs","false"),o?.overwrite===!0&&r.set("overwrite","true"),L(`${ae(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${r.toString()}`,{method:"POST"})}},Xn={sessions:(e,t="local")=>L(`${ae(t)}/sessions?cwd=${encodeURIComponent(e)}`),startSession:(e,t="local")=>L(`${ae(t)}/sessions`,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>L(`${ae(t)}/sessions/cleanup/preview`,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>L(`${ae(t)}/sessions/cleanup`,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>L(`${ae(t)}/sessions/bulk/archive`,{method:"POST",body:Sa(e)}),deleteArchivedMany:(e,t="local")=>L(`${ae(t)}/sessions/bulk/delete-archived`,{method:"POST",body:Sa(e)}),messages:(e,t,i="local")=>L(Sh(e,t,i)),status:(e,t="local")=>L(Qs(e,"status",t)),models:(e,t="local")=>L(Qs(e,"models",t)),setModel:(e,t,i,s,o)=>{const n=typeof s=="boolean"?s:void 0;return L(He(e,"model",typeof s=="string"?s:o??"local"),{method:"POST",body:Je(e,{provider:t,modelId:i,...n===!0?{persist:!0}:{}})})},cycleModel:(e,t,i="local")=>L(He(e,"model/cycle",i),{method:"POST",body:Je(e,{direction:t})}),thinkingLevels:(e,t="local")=>L(Qs(e,"thinking-levels",t)),setThinkingLevel:(e,t,i="local")=>L(He(e,"thinking-level",i),{method:"POST",body:Je(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>L(He(e,"thinking-level/cycle",t),{method:"POST",body:Je(e)}),commands:(e,t="local")=>L(Qs(e,"commands",t)),prompt:(e,t,i,s="local",o)=>L(He(e,"prompt",s),{method:"POST",body:Je(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>L(He(e,"attachments",i),{method:"POST",body:Je(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>L(He(e,"shell",i),{method:"POST",body:Je(e,{text:t})}),runCommand:(e,t,i="local")=>L(He(e,"commands/run",i),{method:"POST",body:Je(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>L(He(e,"commands/respond",s),{method:"POST",body:Je(e,{requestId:t,value:i})}),respondToAsk:(e,t,i,s="local")=>L(He(e,"ask/respond",s),{method:"POST",body:Je(e,{requestId:t,result:i})}),abort:(e,t="local")=>L(He(e,"abort",t),{method:"POST",body:Je(e)}),stop:(e,t="local")=>L(He(e,"stop",t),{method:"POST",body:Je(e)}),archive:(e,t="local")=>L(He(e,"archive",t),{method:"POST",body:Je(e)}),archiveWithDescendants:(e,t="local")=>L(He(e,"archive-tree",t),{method:"POST",body:Je(e)}),restore:(e,t="local")=>L(He(e,"restore",t),{method:"POST",body:Je(e)}),deleteArchived:(e,t="local")=>L(Ph(e,t),{method:"DELETE"}),detachParent:(e,t="local")=>L(He(e,"detach-parent",t),{method:"POST",body:Je(e)}),reloadSession:(e,t="local")=>L(He(e,"reload",t),{method:"POST",body:Je(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return L(`${ae(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`)},saveApiKey:(e,t,i="local")=>L(`${ae(i)}/auth/api-key`,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>L(`${ae(t)}/auth/logout`,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>L(`${ae(t)}/auth/oauth`,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>L(`${ae(t)}/auth/oauth/${encodeURIComponent(e)}`),respondOAuthFlow:(e,t,i,s="local")=>L(`${ae(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>L(`${ae(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,{method:"POST"})},ns={terminals:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`),startTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>L(`${ae(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>L(`${ae(t)}/terminal-command-runs${Ih(e)}`),getCommandRun:(e,t="local")=>Ah(e,t),cancelCommandRun:(e,t="local")=>L(`${ae(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,{method:"POST"})};async function Ah(e,t){const i=await fetch(`${ae(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Dh(s)??i.statusText)}return await i.json()}}function Ih(e){if(e===void 0)return"";const 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));const i=t.toString();return i===""?"":`?${i}`}function Dh(e){if(!Fe(e))return;const t=e.error;return typeof t=="string"?t:void 0}const Eh={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?L(`${ae(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`):(s.set("cwd",e),L(`${ae(i.machineId)}/files?${s.toString()}`))}},Lh={gitStatus:(e,t,i="local")=>L(`${ae(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`),gitDiff:(e,t,i,s="local")=>L(xh(s,e,t,i))},_e={...Lc,...Mh,...Gt,...Cs,...Ms,...Wc,...Th,...ss,...Xn,...ns,...Eh,...Lh};function Wh(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Sr()}${xr(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function a1(e,t,i,s,o="local"){const n=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Sr()}${xr(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${n}`)}function Oh(e="local"){return new WebSocket(`${Sr()}${xr(e)}/events`)}function xr(e){return`/api/machines/${encodeURIComponent(e)}`}function Sr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const Es=".omp-web/uploads";class Zo extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Oc extends Error{constructor(t,i){super(Hh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function $a(e){return e?.uploads?.defaultFolder??Es}function _h(e,t){return e?.uploads?.defaultFolder??t}function kr(e,t){const i=Pa(e,"upload destination",{allowEmpty:!0}),s=Pa(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function jh(e,t,i,s={}){const o=s.xhrFactory?.()??new XMLHttpRequest;let n=!1,r=!1;return{promise:new Promise((l,c)=>{const p=h=>{n||(n=!0,c(h))},d=h=>{n||(n=!0,l(h))};o.open("PUT",kh(e,t,i.path,Nh(s)),!0),o.responseType="json",o.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),o.upload.onprogress=h=>{s.onProgress?.(zh(h,i.file.size))},o.onload=()=>{if(o.status>=200&&o.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),d(_c(o))}catch(h){p(h instanceof Error?h:new Error(String(h)))}return}p(new Error(Vh(o)))},o.onerror=()=>{p(new Error("Workspace upload failed"))},o.onabort=()=>{p(new Zo(r?void 0:"Workspace upload aborted"))},o.send(i.file)}),cancel:()=>{n||(r=!0,o.abort())}}}function Fh(e,t,i,s={}){const o=s.destinationFolder??Es,n=i.map((d,h)=>({index:h,name:d.name,path:kr(o,d.name),loaded:0,total:d.size,percent:$r(0,d.size),lengthComputable:!0,done:!1}));let r,a=0;const l={requested:!1},c=()=>{s.onProgress?.(Uh(n,a,n.every(d=>d.done)))};return{promise:(async()=>{const d=[],h=[];for(let g=0;g<i.length;g+=1){if(l.requested)throw new Zo;a=g;const m=i[g],v=n[g];if(!(m===void 0||v===void 0)){r=jh(e,t,{path:v.path,file:m},{...Bh(s),onProgress:w=>{v.total=w.total,v.loaded=Math.min(w.loaded,v.total),v.percent=w.percent,v.lengthComputable=w.lengthComputable,c()}});try{const w=await r.promise;v.loaded=v.total,v.percent=1,v.lengthComputable=!0,v.done=!0,d.push(w),c()}catch(w){if(qh(w,l))throw w;const x=Re(w);v.loaded=v.total,v.percent=1,v.lengthComputable=!0,v.done=!0,v.error=x,h.push({index:g,name:m.name,path:v.path,error:x}),c()}finally{r=void 0}}}if(h.length>0)throw new Oc(h,d);return d})(),cancel:()=>{l.requested=!0,r?.cancel()}}}function Bh(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 Nh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function zh(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:$r(e.loaded,i),lengthComputable:e.lengthComputable}}function Uh(e,t,i){const s=e.reduce((n,r)=>n+r.total,0),o=e.reduce((n,r)=>n+r.loaded,0);return{currentFileIndex:t,files:e.map(n=>({...n})),loaded:o,total:s,percent:$r(o,s),done:i}}function $r(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Hh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function qh(e,t){return t.requested||e instanceof Zo}function Pa(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Kh(s))throw new Error(`${t} must be workspace-relative`);const o=s.split(/[\\/]+/u).filter(n=>n!==""&&n!==".");if(o.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(o.some(n=>n===".."))throw new Error(`${t} must not contain path traversal`);return o.join("/")}function Kh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function _c(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Vh(e){const t=Gh(e);return Fe(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function Gh(e){try{return _c(e)}catch{return}}function go(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Yh(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,planReviewDialog:void 0,askDialog:void 0,btwState:void 0,modelDialog:void 0,modelActionDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,ompWebStatus:void 0,error:""}}const kt={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},Xh=Object.values(kt);new Set(Xh);function jt(e,t){return e?.capabilities?.includes(t)===!0}function Mi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function jc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Fc="local";function xn(e,t){return`${e}:${t}`}function Bc(e,t){return`${e}:${t}`}function C(e){return e.selectedMachine?.id??Fc}class Jh{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Wc}async refresh(t=C(this.getState())){this.applyMachineActivitySnapshot(t,Qh(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=C(this.getState())){const s=this.getState(),o=C(s)===i,n=s.machineActivities[i]??(o?s.workspaceActivities:{}),r=Zh(n,t);this.setState({machineActivities:{...s.machineActivities,[i]:r},...o?{workspaceActivities:r}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...C(s)===t?{workspaceActivities:i}:{}})}}function Qh(e){const t={};for(const i of e.workspaces)jc(i)&&(t[i.cwd]=i);return t}function Zh(e,t){const i={...e};return jc(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class eu{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??_e,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=tu(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:C(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(n=>n.id===t&&(i===void 0||n.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,C(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:C(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,C(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",n={...i};delete n.error,this.setState({authDialog:{...n,responding:!0}});try{const r=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,C(this.getState()));this.updateOAuthFlow(r)}catch(r){this.setState({authDialog:{...i,responding:!1,error:String(r)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,C(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:C(this.getState())}),s=i.filter(n=>n.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,C(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,n=t.prompt?.requestId??t.select?.requestId,r=o!==void 0&&o===n,a=r?s:"",l=r&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:l}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,C(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,C(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function tu(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Ns(e){return e.replaceAll(":",".")}function iu(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,n]of t.entries()){if(!o.startsWith(i))continue;const r=o.slice(i.length),a=s[r];a===void 0?s[r]=n:Array.isArray(a)?a.push(n):s[r]=[a,n]}return s}function Sn(e,t){const i=iu(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function Wt(e,t,i,s){const o=new URL(window.location.href),n=`${e}--${t}`;if(o.searchParams.delete(n),i!=null&&i!=="")if(Array.isArray(i))for(const r of i)o.searchParams.append(n,String(r));else o.searchParams.set(n,String(i));su(o,s)}function su(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function ou(e){const t=e.files.map((s,o)=>{const n=s.size;return{index:o,name:s.name,path:kr(e.destinationFolder,s.name),size:s.size,loaded:0,total:n,percent:Ma(0,n),lengthComputable:!0,status:o===0?"uploading":"pending"}}),i=t.reduce((s,o)=>s+o.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:i,percent:Ma(0,i),status:"uploading",startedAt:e.startedAt}}function nu(e,t){const i=new Map(t.files.map(o=>[o.index,o])),s=e.files.map(o=>{const n=i.get(o.index);if(n===void 0)return o;const r={...o,path:n.path,loaded:n.loaded,total:n.total,percent:n.percent,lengthComputable:n.lengthComputable,status:n.error!==void 0?"error":n.done?"completed":t.currentFileIndex===o.index?"uploading":o.status};return n.error===void 0?delete r.error:r.error=n.error,r});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function ru(e,t,i){const s=e.files.map((n,r)=>{const a=t[r];return{...n,...a===void 0?{}:{path:a.path,response:a},loaded:n.total,percent:1,lengthComputable:!0,status:"completed"}}),o=Pr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...o,status:"completed",completedAt:i}}function au(e,t,i){const s=e.files.map(o=>o.status==="completed"||o.status==="error"?o:o.status==="uploading"||o.index===e.currentFileIndex?{...o,status:"error",error:t}:{...o,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Pr(s),status:"error",error:t,completedAt:i}}function Ca(e,t){const i="Upload cancelled",s=e.files.map(o=>o.status==="completed"||o.status==="error"?o:{...o,status:"cancelled",error:i});return{...e,files:s,...Pr(s),status:"cancelled",error:i,completedAt:t}}function Pr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Ma(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const Ra=Ns("core:workspace.files");class lu{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=o.api??_e,this.uploadWorkspaceFiles=o.uploadWorkspaceFiles??Fh,this.createUploadBatchId=o.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=o.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=C(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),n={...this.getState().expandedDirs};await Promise.all(Object.keys(n).map(async r=>{n[r]=(await this.api.workspaceTree(t.id,i.id,r,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Ta(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,C(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Wt(Ra,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,C(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(cu(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Wt(Ra,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,o=this.getState().selectedWorkspace;if(s===void 0||o===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const n=C(this.getState()),r=i.overwrite??!1,a=i.createDirs??!0;let l;try{l=ou({id:this.createUploadBatchId(),projectId:s.id,workspaceId:o.id,machineId:n,destinationFolder:i.destinationFolder,overwrite:r,createDirs:a,files:t,startedAt:this.now()})}catch(d){this.setState({error:String(d)});return}this.setUploadBatch(l);let c;try{c=this.uploadWorkspaceFiles(s.id,o.id,t,{destinationFolder:i.destinationFolder,machineId:n,overwrite:r,createDirs:a,onProgress:d=>{this.updateUploadProgress(l.id,d)}})}catch(d){return this.failUploadBatch(l.id,d),{batchId:l.id,done:Promise.resolve()}}this.uploadTasks.set(l.id,c);const p=c.promise.then(async d=>{await this.completeUploadBatch(l.id,d,i)}).catch(async d=>{await this.handleUploadFailure(l.id,d,i)}).finally(()=>{this.uploadTasks.delete(l.id)});return{batchId:l.id,done:p}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(Ca(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Ta(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(nu(s,i))}async completeUploadBatch(t,i,s){const o=this.getUploadBatch(t);if(o?.status!=="uploading"||(this.setUploadBatch(ru(o,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(o)))return;await this.refreshFiles();const n=i[0]?.path;s.selectUploadedFile!==!1&&n!==void 0&&this.isCurrentWorkspaceBatch(o)&&await this.selectFile(n)}async handleUploadFailure(t,i,s){const o=this.failUploadBatch(t,i);if(!(i instanceof Oc)||i.responses.length===0||o===void 0||!this.isCurrentWorkspaceBatch(o))return;await this.refreshFiles();const n=i.responses[0]?.path;s.selectUploadedFile!==!1&&n!==void 0&&this.isCurrentWorkspaceBatch(o)&&await this.selectFile(n)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(du(i)){const r=Ca(s,this.now());return this.setUploadBatch(r),r}const o=Re(i),n=au(s,o,this.now());return this.setUploadBatch(n,{error:o}),n}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&C(i)===t.machineId}}function cu(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function du(e){return e instanceof Zo}function Ta(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Aa=Ns("core:workspace.git");class pu{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await _e.gitStatus(t.id,i.id,C(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(n=>n.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Wt(Aa,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),Wt(Aa,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,n]=await Promise.all([_e.gitDiff(i.id,s.id,{path:t},C(this.getState())),_e.gitDiff(i.id,s.id,{path:t,staged:!0},C(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:n,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class hu{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await _e.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(n=>n.id));this.setState({machines:i,selectedMachine:s,machineActivities:Ia(this.getState().machineActivities,o),machineRuntimes:Ia(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,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,...go()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await _e.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await _e.deleteMachine(t.id);const o=this.getState().machines.filter(r=>r.id!==t.id),n=o.find(r=>r.id==="local")??o[0];return this.setState({machines:o,machineStatuses:kn(this.getState().machineStatuses,t.id),machineRuntimes:kn(this.getState().machineRuntimes,t.id),machineActivities:kn(this.getState().machineActivities,t.id)}),s&&n!==void 0?(i.selectFallback===!1||await this.selectMachine(n),n):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await _e.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await _e.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await _e.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>_e.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>_e.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function kn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ia(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class uu{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=C(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await _e.projects(t);if(C(this.getState())!==t)return;const s=new Set(i.map(n=>n.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([n])=>s.has(n)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){C(this.getState())===t&&this.setState({error:String(i)})}finally{C(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await _e.addProject(t.trim(),void 0,i,C(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(n=>n.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await _e.closeProject(t,C(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Jn="omp-web:cached-new-sessions:v1",fu="browserCachedNew",fs="local";function zs(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Da(e,t=fs,i=zs()){if(e.messageCount!==0||e.archived===!0)return;const s=Cr(i).filter(o=>o.id!==e.id||o.machineId!==t);Mr([Qn(e,t),...s],i)}function Qn(e,t=fs){return{...e,browserCachedNew:!0,machineId:t}}function Ea(e,t=fs,i=zs()){const s=Cr(i).filter(o=>o.id!==e||o.machineId!==t);Mr(s,i)}function Nc(e,t,i=fs,s=zs()){const o=new Set(t.map(l=>l.id)),n=Cr(s),r=n.filter(l=>l.machineId!==i||!o.has(l.id));return r.length!==n.length&&Mr(r,s),[...r.filter(l=>l.machineId===i&&l.cwd===e),...t]}function Mo(e){return e===void 0?!1:vu(e)&&e.browserCachedNew===!0}function gu(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:fs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Cr(e=zs()){try{const t=e?.getItem(Jn);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>mu(s)):[]}catch{return[]}}function Mr(e,t=zs()){try{e.length===0?t?.removeItem(Jn):t?.setItem(Jn,JSON.stringify(e))}catch{}}function mu(e){if(!Fe(e))return[];const t=Xi(e,"id"),i=Xi(e,"path"),s=Xi(e,"cwd"),o=Xi(e,"created"),n=Xi(e,"modified"),r=Xi(e,"firstMessage"),a=bu(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||n===void 0||r===void 0||a!==0)return[];const l=$n(e,"name"),c=$n(e,"parentSessionPath"),p=$n(e,"machineId")??fs;return[{id:t,path:i,cwd:s,...l===void 0?{}:{name:l},created:o,modified:n,messageCount:a,firstMessage:r,...c===void 0?{}:{parentSessionPath:c},machineId:p,browserCachedNew:!0}]}function vu(e){return fu in e}function Xi(e,t){const i=e[t];return typeof i=="string"?i:void 0}function $n(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function bu(e,t){const i=e[t];return typeof i=="number"?i:void 0}function wu(e){return Ou(e.flatMap(Rr)).filter(t=>t.parts.length>0)}function Yt(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Ji(e,t){const i=Ru(t);return i===void 0?e:{...e,meta:i}}function yu(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Yt(t,i)]}function xu(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Rr(e){if(ku(e))return[e];if(ke(e,"role")==="bashExecution")return[Ji(Iu(e),e)];const t=Pu(e);if(t!==void 0)return t.map(p=>Ji(p,e));const i=Du(ke(e,"role")),s=Eu(Mt(e,"content"),e),o=i==="user"?$u(s):void 0;if(o!==void 0)return o.map(p=>Ji(p,e));const n=Mu(e);if(i==="tool")return[Ji({role:i,parts:s,...n===void 0?{}:{source:n}},e)];const r=s.filter(p=>p.type!=="empty"),a=i==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":i,l=r.length>0?[Ji({role:a,parts:r,...n===void 0?{}:{source:n}},e)]:[],c=Su(e);return c===void 0?l:[...l,Ji(c,e)]}function Su(e){if(ke(e,"role")!=="assistant"||ke(e,"stopReason")!=="error")return;const t=ke(e,"errorMessage")?.trim();return Yt("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function ku(e){const t=ke(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Mt(e,"parts"))}function $u(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Cu(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 Pu(e){if(!Fe(e)||e.customType!=="skill-prompt")return;const t=Fe(e.details)?e.details:void 0,i=typeof t?.name=="string"?t.name:"skill",s=typeof t?.path=="string"?t.path:"",o=typeof e.content=="string"?e.content:"",n=typeof t?.args=="string"&&t.args.trim()!==""?t.args.trim():void 0;return[{role:"user",parts:[{type:"skillInvocation",name:i,location:s,content:o},...n!==void 0?[{type:"text",text:n}]:[]]}]}function Cu(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t!==null){const s=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...s===void 0||s===""?{}:{userMessage:s}}}const i=/^\[IMPORTANT: User invoked the "([^"]+)" skill; follow its instructions\. Full skill below\.\]\n\n([\s\S]*?)(?:\n\n---\n\n\[Skill directory: ([^\]]+)\][\s\S]*?(?:\nUser: ([\s\S]+))?)?$/.exec(e);if(i!==null){const s=i[4]?.trim();return{name:i[1]??"skill",location:i[3]??"",content:i[2]??"",...s===void 0||s===""?{}:{userMessage:s}}}}function Mu(e){const t=ke(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ru(e){const t=Tu(Mt(e,"timestamp")),i=Au(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Tu(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Au(e){if(ke(e,"role")!=="assistant")return;const t=ke(e,"provider"),i=ke(e,"model"),s=ke(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Iu(e){const t=ke(e,"command")??"",i=mo(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Mt(e,"output");s!=null&&i.push("",To(s));const o=Mt(e,"exitCode");o!=null&&i.push("",`exit ${To(o)}`),mo(e,"cancelled")===!0&&i.push("","cancelled"),mo(e,"truncated")===!0&&i.push("","output truncated");const n=ke(e,"fullOutputPath");return n!==void 0&&n!==""&&i.push("",`full output: ${n}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
5
  `)}]}}function Du(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Eu(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=ke(i,"type"),o=ke(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const n=ke(i,"thinking")??o;return n!==void 0&&n!==""?[{type:"thinking",text:n}]:[]}if(s==="toolCall"){const n=ke(i,"name")??"tool",r=Mt(i,"arguments"),a=ke(i,"id"),l=n==="read"?Wu(ke(r,"path")):void 0;return l!==void 0?[{type:"skillRead",...l,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:n,summary:Us(r),...r===void 0?{}:{args:r}}]}if(s==="image"){const n=ke(i,"data"),r=ke(i,"mimeType");return n!==void 0&&n!==""&&r!==void 0&&r!==""?[{type:"image",mimeType:r,data:n}]:[{type:"text",text:"[image]"}]}return La(i)}).map(i=>i.type==="text"&&ke(t,"role")==="toolResult"?Lu(i.text,t):i):La(e)}function Lu(e,t){const i=ke(t,"toolCallId"),s=Mt(t,"content"),o=Mt(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:ke(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:mo(t,"isError")===!0}}function Wu(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function Ou(e){const t=[],i=new Map;for(const s of e){let o=[];const n={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},r=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...n}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){r();const l=_u(a),c=t.length;t.push({role:"tool",parts:[l],...n}),l.toolCallId!==void 0&&i.set(l.toolCallId,{lineIndex:c,partIndex:0});continue}if(a.type==="toolResult"){const l=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(l!==void 0&&ju(t,l,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}r()}return t}function _u(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 ju(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const n=Ro(i.details)??o.preview,r={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...n===void 0?{}:{preview:n}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),r,...s.parts.slice(t.partIndex+1)]},!0}function Ro(e){const t=Mt(e,"preview");if(!Fe(t))return;const i=ke(t,"diff"),s=ke(t,"error"),o=Bu(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function La(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Us(e)}]:[{type:"text",text:To(e)}]}function Us(e){if(!Fe(e))return To(e);const t=ke(e,"command");if(t!==void 0)return t;const i=ke(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,n])=>n!=null).slice(0,3).map(([n,r])=>`${n}: ${Fu(r)}`).join(" · ")}function Fu(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!==null?"object":""}function Mt(e,t){return Fe(e)?e[t]:void 0}function ke(e,t){const i=Mt(e,t);return typeof i=="string"?i:void 0}function mo(e,t){const i=Mt(e,t);return typeof i=="boolean"?i:void 0}function Bu(e,t){const i=Mt(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function To(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Nu="omp-web:prompt-draft:";function Ao(e){return`${Nu}${e}`}function en(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function zc(e,t=en()){try{return t?.getItem(Ao(e))??""}catch{return""}}function Io(e,t,i=en()){try{t?i?.setItem(Ao(e),t):i?.removeItem(Ao(e))}catch{}}function Tr(e,t=en()){try{t?.removeItem(Ao(e))}catch{}}function zu(e,t,i=en()){const s=zc(e,i);s!==""&&(Io(t,s,i),Tr(e,i))}function Uu(e,t){return Yt("bash",`${t===!0?`excluded from context
6
6
 
7
7
  `:""}$ ${e}`)}function Hu(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Yt("bash",t)];const o=Ku(s.text)?"":`
@@ -4106,7 +4106,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
4106
4106
  gap: 12px;
4107
4107
  }
4108
4108
  .binary-file-view p { margin: 0; }
4109
- `];bi([f({attribute:!1})],Ut.prototype,"context",2);bi([We("#workspace-upload-input")],Ut.prototype,"uploadInput",2);bi([R()],Ut.prototype,"pendingUpload",2);bi([R()],Ut.prototype,"destinationFolder",2);bi([R()],Ut.prototype,"overwrite",2);bi([R()],Ut.prototype,"createDirs",2);bi([R()],Ut.prototype,"formError",2);bi([R()],Ut.prototype,"dragActive",2);Ut=bi([ue("workspace-files-panel")],Ut);function o$(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function n$(e,t){if(e.length===0)return"Choose at least one file to upload.";for(const i of e)try{kr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function r$(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function a$(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mc(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function po(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function l$(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function c$(e){const t=e.files.length,i=t===1?"file":"files";switch(e.status){case"completed":return`Uploaded ${String(t)} ${i}`;case"error":return`Upload failed for ${String(t)} ${i}`;case"cancelled":return`Upload cancelled for ${String(t)} ${i}`;case"uploading":return`Uploading ${String(t)} ${i}`}}function d$(e){switch(e.status){case"completed":return"Done";case"error":return"Failed";case"cancelled":return"Cancelled";case"uploading":return Ip(e.percent)}}function p$(e){return e.status==="uploading"?e.percent:1}function h$(e){switch(e.status){case"pending":return"Pending";case"uploading":return Ip(e.percent);case"completed":return"Done";case"error":return"Error";case"cancelled":return"Cancelled"}}function u$(e){return e.error!==void 0?e.error:e.response!==void 0?`Wrote ${e.response.path}`:`${e.path} · ${ji(e.loaded)} / ${ji(e.total)}`}function Ip(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function f$(){na(()=>import("./CodeViewer-CJNBz-Ox.js"),__vite__mapDeps([0,1,2]))}function ji(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${qn(t)} KB`;const i=t/1024;return i<1024?`${qn(i)} MB`:`${qn(i/1024)} GB`}function qn(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var g$=Object.defineProperty,m$=Object.getOwnPropertyDescriptor,Dp=(e,t,i,s)=>{for(var o=s>1?void 0:s?m$(t,i):t,n=e.length-1,r;n>=0;n--)(r=e[n])&&(o=(s?r(t,i,o):r(o))||o);return s&&o&&g$(t,i,o),o};let Xo=class extends le{get executions(){if(!this.context)return[];const e=this.context.state.messages;if(e.length===0)return[];const t=[];for(const i of e)for(const s of i.parts)s.type==="toolExecution"&&(s.toolName==="task"||s.toolName==="todo")&&t.push(s);return t}render(){const e=this.executions;return e.length===0?u`
4109
+ `];bi([f({attribute:!1})],Ut.prototype,"context",2);bi([We("#workspace-upload-input")],Ut.prototype,"uploadInput",2);bi([R()],Ut.prototype,"pendingUpload",2);bi([R()],Ut.prototype,"destinationFolder",2);bi([R()],Ut.prototype,"overwrite",2);bi([R()],Ut.prototype,"createDirs",2);bi([R()],Ut.prototype,"formError",2);bi([R()],Ut.prototype,"dragActive",2);Ut=bi([ue("workspace-files-panel")],Ut);function o$(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function n$(e,t){if(e.length===0)return"Choose at least one file to upload.";for(const i of e)try{kr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function r$(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function a$(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mc(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function po(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function l$(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function c$(e){const t=e.files.length,i=t===1?"file":"files";switch(e.status){case"completed":return`Uploaded ${String(t)} ${i}`;case"error":return`Upload failed for ${String(t)} ${i}`;case"cancelled":return`Upload cancelled for ${String(t)} ${i}`;case"uploading":return`Uploading ${String(t)} ${i}`}}function d$(e){switch(e.status){case"completed":return"Done";case"error":return"Failed";case"cancelled":return"Cancelled";case"uploading":return Ip(e.percent)}}function p$(e){return e.status==="uploading"?e.percent:1}function h$(e){switch(e.status){case"pending":return"Pending";case"uploading":return Ip(e.percent);case"completed":return"Done";case"error":return"Error";case"cancelled":return"Cancelled"}}function u$(e){return e.error!==void 0?e.error:e.response!==void 0?`Wrote ${e.response.path}`:`${e.path} · ${ji(e.loaded)} / ${ji(e.total)}`}function Ip(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function f$(){na(()=>import("./CodeViewer-Mp4aTsTY.js"),__vite__mapDeps([0,1,2]))}function ji(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${qn(t)} KB`;const i=t/1024;return i<1024?`${qn(i)} MB`:`${qn(i/1024)} GB`}function qn(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var g$=Object.defineProperty,m$=Object.getOwnPropertyDescriptor,Dp=(e,t,i,s)=>{for(var o=s>1?void 0:s?m$(t,i):t,n=e.length-1,r;n>=0;n--)(r=e[n])&&(o=(s?r(t,i,o):r(o))||o);return s&&o&&g$(t,i,o),o};let Xo=class extends le{get executions(){if(!this.context)return[];const e=this.context.state.messages;if(e.length===0)return[];const t=[];for(const i of e)for(const s of i.parts)s.type==="toolExecution"&&(s.toolName==="task"||s.toolName==="todo")&&t.push(s);return t}render(){const e=this.executions;return e.length===0?u`
4110
4110
  <section class="panel-content">
4111
4111
  <div class="empty-state" role="status">
4112
4112
  <h2>No tasks</h2>
@@ -4234,7 +4234,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
4234
4234
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
4235
4235
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
4236
4236
  </section>
4237
- `}function P$(){na(()=>import("./UnifiedDiffViewer-BUqme4se.js"),__vite__mapDeps([3,1,2]))}function C$(){na(()=>import("./TerminalPanel-B9-LUv7E.js"),__vite__mapDeps([4,5,6,1,2]))}function M$(e){return u`<workspace-tasks-panel .context=${e}></workspace-tasks-panel>`}function R$(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function T$(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const A$={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:qk(),workspacePanels:w$()}})},I$={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},D$={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},E$={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},L$={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"omp-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:D$},{id:"omp-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:E$},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:I$}],themePairs:[{id:"omp-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"omp-web-light",dark:"omp-web-dark"}]}})},bc=[1e3,3e3,8e3,15e3,3e4];function W$(){const e=new em;return e.register({id:"core",plugin:A$}),e.register({id:"themes",plugin:L$}),e}function wc(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function O$(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function _$(e,t){return Ep(e,t)}function Ep(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function j$(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function yc(e){return Mi(e.status,e.activity)}function F$(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function xc(){return{}}function Sc(e,t){return JSON.stringify([e,t])}function B$(e){const t=Math.min(e,bc.length-1);return bc[t]??3e4}function N$(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Kn(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function z$(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}}var U$=Object.defineProperty,H$=Object.getOwnPropertyDescriptor,vt=(e,t,i,s)=>{for(var o=s>1?void 0:s?H$(t,i):t,n=e.length-1,r;n>=0;n--)(r=e[n])&&(o=(s?r(t,i,o):r(o))||o);return s&&o&&U$(t,i,o),o};const q$=900*1e3,K$=750,V$=[1e3,3e3,8e3,15e3,3e4],kc={capture:!0},Vn="auto:on",$c="auto:off",ho="theme:",Gn=Ns("core:workspace.files"),Yn=Ns("core:workspace.git"),uo=Ns("core:workspace.terminal"),G$=320,Y$=2,X$="(min-width: 1181px)";let nt=class extends le{constructor(){super(...arguments),this.state=Yh(),this.chatPreferences=Pt(),this.handleChatPreferencesChanged=e=>{if(e instanceof CustomEvent&&sn(e.detail)?this.chatPreferences=e.detail:this.chatPreferences=Pt(),this.chatPreferences.hideWorkspaces&&this.state.workspaces.length>0&&this.state.selectedWorkspace?.id!==this.state.workspaces[0]?.id){const t=this.state.workspaces[0];t!==void 0&&this.workspaces.selectWorkspace(t)}this.requestUpdate()},this.sessions=new qf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Ff),this.activity=new Jh(()=>this.state,e=>{this.setState(e)}),this.auth=new eu(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new sg(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new eg),this.projects=new uu(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new hu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new lu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new mg,this.realtime=new Ba,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new ag,this.terminalSelection=new fg,this.appShell=new gm(this),this.panelCollapse=new Cm(this),this.panelResize=new Rm(this),this.navigationSections=new km(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=W$(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Wg()??Dg,this.activeThemeId=Lr,this.isRefreshingApp=!1,this.settingsSection=pl(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=$a(void 0),this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),this.chatPreferences=Pt(),pi()?.addEventListener(di,this.handleChatPreferencesChanged),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,kc),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.ompWebStatusTimer=window.setInterval(()=>{this.scheduleOmpWebStatusRefresh()},q$),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.scheduleOmpWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,kc),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),pi()?.removeEventListener(di,this.handleChatPreferencesChanged),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.ompWebStatusTimer!==void 0&&window.clearInterval(this.ompWebStatusTimer),this.ompWebStatusTimer=void 0,this.clearScheduledOmpWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!j$(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),O$(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=dl();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=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,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}scheduleOmpWebStatusRefresh(e=K$){this.clearScheduledOmpWebStatusRefresh(),this.ompWebStatusDeferredTimer=window.setTimeout(()=>{this.ompWebStatusDeferredTimer=void 0,this.refreshOmpWebStatus()},e)}clearScheduledOmpWebStatusRefresh(){this.ompWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.ompWebStatusDeferredTimer),this.ompWebStatusDeferredTimer=void 0)}async refreshOmpWebStatus(){const e=C(this.state);try{const t=await Lc.ompWebStatus(e);C(this.state)===e&&this.setState({ompWebStatus:t})}catch(t){C(this.state)===e&&this.setState({ompWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=C(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[C(this.state)]:this.state.machines.filter(t=>Ep(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await Gt.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=$a(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.scheduleOmpWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const 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(dl(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=C(this.state),n=e.projectId===void 0||e.projectId===""?xc():i,r=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=n.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(r))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:n.selectedFilePath,selectedDiffPath:n.selectedDiffPath,selectedTerminalId:n.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){n.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(n.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,n.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const l=this.state.projects.find(c=>c.id===e.projectId);if(!l){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(l,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(r))return;this.setState({selectedFilePath:n.selectedFilePath,selectedDiffPath:n.selectedDiffPath,selectedTerminalId:n.selectedTerminalId}),n.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(n.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,n.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),C(this.state)!==o&&this.scheduleOmpWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?xc():{selectedFilePath:Sn(Gn,"file"),selectedDiffPath:Sn(Yn,"diff"),selectedTerminalId:Sn(uo,"terminal")}}routeForSelectedMachine(e){const 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){Mn(e,{replace:!0}),Wt(Gn,"file",void 0,{replace:!0}),Wt(Yn,"diff",void 0,{replace:!0}),Wt(uo,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.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=B$(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;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.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>=V$.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",n=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),r=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${r}${n===void 0?"":` ${n}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.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){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{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 Kn(),t()&&(this.chatView?.restoreScrollPosition(),this.chatView?.focusConversation()))))}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(),Mn({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(Ya(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Ya(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mn(Xa(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Wt(Gn,"file",e.selectedFilePath,{replace:!0}),Wt(Yn,"diff",e.selectedDiffPath,{replace:!0}),Wt(uo,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??lg(e.id);if(await this.restoreRouteFor(Xa(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);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=C(this.state)){const i=Sc(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=Hm(e,{api:{runTerminalCommand:(n,r)=>ns.runTerminalCommand(n,r,t),listCommandRuns:n=>ns.listCommandRuns(n,t),getCommandRun:n=>ns.getCommandRun(n,t)},openTerminal:(n,r)=>{this.openRuntimeTerminal(t,n,r)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((C(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:i?.terminalId},"core:workspace.terminal"),C(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const 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){Wt(uo,"terminal",e,t)}terminalWorkspaceKey(e){return`${C(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,Rn(e)}closeSettings(){this.settingsSection=void 0,Rn(void 0)}navigateSettings(e){this.settingsSection=e,Rn(e)}restoreSettingsRoute(){this.settingsSection=pl()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},C(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Ba;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=C(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>_$(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):F$(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const 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){const t=C(this.state);try{const i=await ns.terminals(e.projectId,e.id,t);if(C(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=yc(e),s=yc(t);i&&!s&&(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.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({ompWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return u`
4237
+ `}function P$(){na(()=>import("./UnifiedDiffViewer-Db5Yxwri.js"),__vite__mapDeps([3,1,2]))}function C$(){na(()=>import("./TerminalPanel-Cb2CgFtQ.js"),__vite__mapDeps([4,5,6,1,2]))}function M$(e){return u`<workspace-tasks-panel .context=${e}></workspace-tasks-panel>`}function R$(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function T$(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const A$={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:qk(),workspacePanels:w$()}})},I$={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},D$={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},E$={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},L$={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"omp-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:D$},{id:"omp-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:E$},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:I$}],themePairs:[{id:"omp-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"omp-web-light",dark:"omp-web-dark"}]}})},bc=[1e3,3e3,8e3,15e3,3e4];function W$(){const e=new em;return e.register({id:"core",plugin:A$}),e.register({id:"themes",plugin:L$}),e}function wc(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function O$(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function _$(e,t){return Ep(e,t)}function Ep(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function j$(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function yc(e){return Mi(e.status,e.activity)}function F$(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function xc(){return{}}function Sc(e,t){return JSON.stringify([e,t])}function B$(e){const t=Math.min(e,bc.length-1);return bc[t]??3e4}function N$(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Kn(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function z$(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}}var U$=Object.defineProperty,H$=Object.getOwnPropertyDescriptor,vt=(e,t,i,s)=>{for(var o=s>1?void 0:s?H$(t,i):t,n=e.length-1,r;n>=0;n--)(r=e[n])&&(o=(s?r(t,i,o):r(o))||o);return s&&o&&U$(t,i,o),o};const q$=900*1e3,K$=750,V$=[1e3,3e3,8e3,15e3,3e4],kc={capture:!0},Vn="auto:on",$c="auto:off",ho="theme:",Gn=Ns("core:workspace.files"),Yn=Ns("core:workspace.git"),uo=Ns("core:workspace.terminal"),G$=320,Y$=2,X$="(min-width: 1181px)";let nt=class extends le{constructor(){super(...arguments),this.state=Yh(),this.chatPreferences=Pt(),this.handleChatPreferencesChanged=e=>{if(e instanceof CustomEvent&&sn(e.detail)?this.chatPreferences=e.detail:this.chatPreferences=Pt(),this.chatPreferences.hideWorkspaces&&this.state.workspaces.length>0&&this.state.selectedWorkspace?.id!==this.state.workspaces[0]?.id){const t=this.state.workspaces[0];t!==void 0&&this.workspaces.selectWorkspace(t)}this.requestUpdate()},this.sessions=new qf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Ff),this.activity=new Jh(()=>this.state,e=>{this.setState(e)}),this.auth=new eu(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new sg(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new eg),this.projects=new uu(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new hu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new lu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new mg,this.realtime=new Ba,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new ag,this.terminalSelection=new fg,this.appShell=new gm(this),this.panelCollapse=new Cm(this),this.panelResize=new Rm(this),this.navigationSections=new km(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=W$(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Wg()??Dg,this.activeThemeId=Lr,this.isRefreshingApp=!1,this.settingsSection=pl(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=$a(void 0),this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),this.chatPreferences=Pt(),pi()?.addEventListener(di,this.handleChatPreferencesChanged),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,kc),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.ompWebStatusTimer=window.setInterval(()=>{this.scheduleOmpWebStatusRefresh()},q$),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.scheduleOmpWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,kc),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),pi()?.removeEventListener(di,this.handleChatPreferencesChanged),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.ompWebStatusTimer!==void 0&&window.clearInterval(this.ompWebStatusTimer),this.ompWebStatusTimer=void 0,this.clearScheduledOmpWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!j$(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),O$(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=dl();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=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,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}scheduleOmpWebStatusRefresh(e=K$){this.clearScheduledOmpWebStatusRefresh(),this.ompWebStatusDeferredTimer=window.setTimeout(()=>{this.ompWebStatusDeferredTimer=void 0,this.refreshOmpWebStatus()},e)}clearScheduledOmpWebStatusRefresh(){this.ompWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.ompWebStatusDeferredTimer),this.ompWebStatusDeferredTimer=void 0)}async refreshOmpWebStatus(){const e=C(this.state);try{const t=await Lc.ompWebStatus(e);C(this.state)===e&&this.setState({ompWebStatus:t})}catch(t){C(this.state)===e&&this.setState({ompWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=C(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[C(this.state)]:this.state.machines.filter(t=>Ep(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await Gt.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=$a(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.scheduleOmpWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const 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(dl(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=C(this.state),n=e.projectId===void 0||e.projectId===""?xc():i,r=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=n.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(r))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:n.selectedFilePath,selectedDiffPath:n.selectedDiffPath,selectedTerminalId:n.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){n.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(n.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,n.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const l=this.state.projects.find(c=>c.id===e.projectId);if(!l){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(l,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(r))return;this.setState({selectedFilePath:n.selectedFilePath,selectedDiffPath:n.selectedDiffPath,selectedTerminalId:n.selectedTerminalId}),n.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(n.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,n.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),C(this.state)!==o&&this.scheduleOmpWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?xc():{selectedFilePath:Sn(Gn,"file"),selectedDiffPath:Sn(Yn,"diff"),selectedTerminalId:Sn(uo,"terminal")}}routeForSelectedMachine(e){const 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){Mn(e,{replace:!0}),Wt(Gn,"file",void 0,{replace:!0}),Wt(Yn,"diff",void 0,{replace:!0}),Wt(uo,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.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=B$(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;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.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>=V$.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",n=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),r=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${r}${n===void 0?"":` ${n}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.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){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{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 Kn(),t()&&(this.chatView?.restoreScrollPosition(),this.chatView?.focusConversation()))))}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(),Mn({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(Ya(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Ya(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mn(Xa(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Wt(Gn,"file",e.selectedFilePath,{replace:!0}),Wt(Yn,"diff",e.selectedDiffPath,{replace:!0}),Wt(uo,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??lg(e.id);if(await this.restoreRouteFor(Xa(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);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=C(this.state)){const i=Sc(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=Hm(e,{api:{runTerminalCommand:(n,r)=>ns.runTerminalCommand(n,r,t),listCommandRuns:n=>ns.listCommandRuns(n,t),getCommandRun:n=>ns.getCommandRun(n,t)},openTerminal:(n,r)=>{this.openRuntimeTerminal(t,n,r)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((C(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:i?.terminalId},"core:workspace.terminal"),C(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const 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){Wt(uo,"terminal",e,t)}terminalWorkspaceKey(e){return`${C(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,Rn(e)}closeSettings(){this.settingsSection=void 0,Rn(void 0)}navigateSettings(e){this.settingsSection=e,Rn(e)}restoreSettingsRoute(){this.settingsSection=pl()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},C(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Ba;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=C(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>_$(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):F$(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const 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){const t=C(this.state);try{const i=await ns.terminals(e.projectId,e.id,t);if(C(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=yc(e),s=yc(t);i&&!s&&(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.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({ompWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return u`
4238
4238
  <workspace-panel
4239
4239
  id="workspace-panel"
4240
4240
  .workspace=${e}
@@ -57,7 +57,7 @@
57
57
  html, body { margin: 0; height: 100%; overflow: hidden; background: var(--pi-bg); color: var(--pi-text); }
58
58
  body { min-height: 100dvh; }
59
59
  </style>
60
- <script type="module" crossorigin src="/assets/index-uWm_YNRB.js"></script>
60
+ <script type="module" crossorigin src="/assets/index-Df4Ex27j.js"></script>
61
61
  <link rel="modulepreload" crossorigin href="/assets/vendor-editor-core-D9EJm1dE.js">
62
62
  <link rel="modulepreload" crossorigin href="/assets/vendor-editor-languages-N6dcxgRO.js">
63
63
  <link rel="stylesheet" crossorigin href="/assets/index-DGBYb2j9.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theruansilva/omp-web",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Web UI for Oh My Pi Coding Agent",
5
5
  "license": "MIT",
6
6
  "author": "theruansilva",