@jmfederico/pi-web 1.202605.4 → 1.202605.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -9
- package/dist/client/assets/{CodeViewer-9gb7No3w.js → CodeViewer-CbO-Cu6v.js} +1 -1
- package/dist/client/assets/TerminalPanel-D4bhXEax.js +47 -0
- package/dist/client/assets/{index-JYhVnrMr.js → index-C0G9UyhD.js} +19 -19
- package/dist/client/index.html +1 -1
- package/dist/server/terminalProxyRoutes.js +4 -14
- package/dist/server/terminalProxyRoutes.js.map +1 -1
- package/dist/server/terminals/terminalRoutes.js +4 -0
- package/dist/server/terminals/terminalRoutes.js.map +1 -1
- package/dist/server/terminals/terminalSize.js +17 -0
- package/dist/server/terminals/terminalSize.js.map +1 -0
- package/dist/server/webSocketBridge.js +32 -0
- package/dist/server/webSocketBridge.js.map +1 -0
- package/extensions/pi-web.ts +1 -20
- package/package.json +10 -3
- package/dist/client/assets/TerminalPanel-DdSh7XN3.js +0 -47
package/README.md
CHANGED
|
@@ -166,15 +166,6 @@ pi-web-sessiond
|
|
|
166
166
|
PI_WEB_PORT=8504 pi-web-server
|
|
167
167
|
```
|
|
168
168
|
|
|
169
|
-
To install directly from the GitHub repository instead of npm:
|
|
170
|
-
|
|
171
|
-
```bash
|
|
172
|
-
npm install -g github:jmfederico/pi-web#main
|
|
173
|
-
pi-web install
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
For git installs, `dist/` must already be present in the repository because npm does not run the package's `prepack` script for git dependencies.
|
|
177
|
-
|
|
178
169
|
## Development quick start
|
|
179
170
|
|
|
180
171
|
```bash
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{w as a,J as d,$ as h,A as f,X as m,U as g,_ as v,a0 as y}from"./vendor-editor-core-B4Sq6exx.js";import{g as w,r as b,p as C,h as j,c as x,m as _,j as k,a as u}from"./vendor-editor-languages-DznYbTkJ.js";import{d as E}from"./vendor-editor-legacy-B4QLsWF8.js";import{i as H,b as O,a as S,n as p,e as P,t as L}from"./index-
|
|
1
|
+
import{w as a,J as d,$ as h,A as f,X as m,U as g,_ as v,a0 as y}from"./vendor-editor-core-B4Sq6exx.js";import{g as w,r as b,p as C,h as j,c as x,m as _,j as k,a as u}from"./vendor-editor-languages-DznYbTkJ.js";import{d as E}from"./vendor-editor-legacy-B4QLsWF8.js";import{i as H,b as O,a as S,n as p,e as P,t as L}from"./index-C0G9UyhD.js";var D=Object.defineProperty,F=Object.getOwnPropertyDescriptor,n=(e,o,i,s)=>{for(var t=s>1?void 0:s?F(o,i):o,c=e.length-1,l;c>=0;c--)(l=e[c])&&(t=(s?l(o,i,t):l(t))||t);return s&&t&&D(o,i,t),t};let r=class extends H{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 O`<div class="host"></div>`}recreateEditor(){this.editorHost&&(this.view?.destroy(),this.view=new a({parent:this.editorHost,state:d.create({doc:this.content,extensions:[h(),f.of(m),g(v,{fallback:!0}),d.readOnly.of(!0),a.editable.of(!1),a.lineWrapping,M,...R(this.language)]})}))}};r.styles=S`
|
|
2
2
|
:host { display: block; min-height: 0; height: 100%; }
|
|
3
3
|
.host { height: 100%; min-height: 0; overflow: auto; }
|
|
4
4
|
`;n([p()],r.prototype,"content",2);n([p()],r.prototype,"language",2);n([P(".host")],r.prototype,"editorHost",2);r=n([L("code-viewer")],r);const M=a.theme({"&":{height:"100%",color:"#e6edf3",backgroundColor:"#0d1117",fontSize:"12px"},".cm-scroller":{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",lineHeight:"1.45"},".cm-gutters":{backgroundColor:"#0d1117",color:"#6e7681",borderRight:"1px solid #21262d"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-activeLine":{backgroundColor:"transparent"},".cm-content":{caretColor:"transparent"},"&.cm-focused":{outline:"none"}});function R(e){if(e===void 0)return[];switch(e){case"typescript":return[u({typescript:!0})];case"javascript":return[u()];case"json":return[k()];case"markdown":return[_()];case"css":return[x()];case"html":return[j()];case"python":return[C()];case"rust":return[b()];case"go":return[w()];case"diff":return[y.define(E)];default:return[]}}export{r as CodeViewer};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import{i as v,c as p,d as w,b as c,a as g,n as b,e as x,r as d,t as y}from"./index-C0G9UyhD.js";import{D as h,o as m}from"./vendor-terminal-DjQ08hXu.js";import"./vendor-editor-core-B4Sq6exx.js";import"./vendor-editor-languages-DznYbTkJ.js";var T=Object.defineProperty,k=Object.getOwnPropertyDescriptor,a=(e,t,i,r)=>{for(var s=r>1?void 0:r?k(t,i):t,o=e.length-1,l;o>=0;o--)(l=e[o])&&(s=(r?l(t,i,s):l(s))||s);return r&&s&&T(t,i,s),s};const u={cursorBlink:!0,convertEol:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:13,theme:{background:"#05070a",foreground:"#e6edf3",cursor:"#58a6ff",selectionBackground:"#264f78"}},S={cols:100,rows:30};let n=class extends v{constructor(){super(...arguments),this.autoStart=!1,this.terminals=[],this.loading=!1,this.visible=!1,this.suppressTerminalInput=!1}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.disposeTerminalView(),super.disconnectedCallback()}willUpdate(){const e=this.workspace?.path;e!==this.observedCwd&&(this.observedCwd=e,this.loadedCwd=void 0,this.terminals=[],this.selectedId=void 0,this.disposeTerminalView())}updated(){this.loadVisibleWorkspaceTerminals(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){const e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{if(this.workspace===void 0)return;const e=await p.terminals(this.workspace.projectId,this.workspace.id);this.terminals=e,this.selectedId=e.find(t=>!t.exited)?.id??e[0]?.id,e.length===0&&this.autoStart&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{const e=this.measureTerminalSize()??S,t=await p.startTerminal(this.workspace.projectId,this.workspace.id,e);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await p.closeTerminal(this.workspace.projectId,this.workspace.id,e);const i=this.terminals.filter(r=>r.id!==e);this.terminals=i,this.selectedId===e&&(this.selectedId=i[0]?.id,this.disposeTerminalView())}catch(i){this.error=i instanceof Error?i.message:String(i)}}selectTerminal(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}ensureTerminalView(){const e=this.workspace;if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||this.terminalHost===void 0||e===void 0)return;const t=new h(u),i=new m;t.loadAddon(i),t.open(this.terminalHost),this.terminal=t,this.fitAddon=i,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(this.terminalHost),t.onData(s=>{if(this.suppressTerminalInput)return;const o=z(s);o!==""&&this.send({type:"input",data:o})});const r=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,t,r),requestAnimationFrame(()=>{this.fitAndNotify()}),t.focus()}connectSocket(e,t,i,r,s){const o=w(e,t,i,s);o.binaryType="arraybuffer",this.socket=o,o.addEventListener("open",()=>{this.fitAndNotify()}),o.addEventListener("message",l=>{this.handleSocketMessage(l.data,i,r)}),o.addEventListener("close",()=>{this.socket===o&&(this.socket=void 0)})}async handleSocketMessage(e,t,i){try{const r=I(await O(e));r.type==="output"&&this.writeTerminalOutput(i,r.data,r.replay===!0),r.type==="exit"&&(i.writeln(`\r
|
|
2
|
+
[process exited${r.exitCode===void 0?"":` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(s=>s.id===t?{...s,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:s)),r.type==="error"&&i.writeln(`\r
|
|
3
|
+
[terminal error: ${r.message}]`)}catch(r){i.writeln(`\r
|
|
4
|
+
[terminal error: ${r instanceof Error?r.message:String(r)}]`)}}writeTerminalOutput(e,t,i){if(!i){e.write(t);return}this.suppressTerminalInput=!0,e.write(t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){const e=this.fitTerminal();e!==void 0&&this.send({type:"resize",...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;const e=this.fitAddon.proposeDimensions(),t=f(e);if(t!==void 0)return this.fitAddon.fit(),t}measureTerminalSize(){const e=this.fitTerminal();if(e!==void 0)return e;if(this.terminal!==void 0||this.terminalHost===void 0)return;const t=new h(u),i=new m;t.loadAddon(i),t.open(this.terminalHost);const r=f(i.proposeDimensions());return t.dispose(),r}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0}render(){return c`
|
|
5
|
+
<section class="terminal-shell">
|
|
6
|
+
<div class="terminal-tabs">
|
|
7
|
+
${this.terminals.map(e=>c`
|
|
8
|
+
<button class=${this.selectedId===e.id?"selected":""} @click=${()=>{this.selectTerminal(e.id)}}>
|
|
9
|
+
<span>${e.name}${e.exited?" · exited":""}</span>
|
|
10
|
+
<small @click=${t=>{this.closeTerminal(e.id,t)}}>×</small>
|
|
11
|
+
</button>
|
|
12
|
+
`)}
|
|
13
|
+
<button class="new" ?disabled=${this.workspace===void 0} @click=${()=>{this.startTerminal()}}>+ Shell</button>
|
|
14
|
+
</div>
|
|
15
|
+
${this.error===void 0?null:c`<p class="error">${this.error}</p>`}
|
|
16
|
+
${this.loading?c`<p class="muted">Loading terminals…</p>`:null}
|
|
17
|
+
<div class="terminal-host"></div>
|
|
18
|
+
</section>
|
|
19
|
+
`}};n.styles=g`
|
|
20
|
+
:host { flex: 1 1 auto; min-height: 0; display: flex; }
|
|
21
|
+
.terminal-shell { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: #05070a; }
|
|
22
|
+
.terminal-tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; padding: 6px; border-bottom: 1px solid #21262d; background: #0d1117; overflow: auto; }
|
|
23
|
+
button { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 180px; border: 1px solid #30363d; border-radius: 7px; background: #161b22; color: #e6edf3; padding: 5px 7px; cursor: pointer; }
|
|
24
|
+
button.selected { border-color: #58a6ff; background: #0d2847; }
|
|
25
|
+
button.new { flex: 0 0 auto; color: #8b949e; }
|
|
26
|
+
button span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
27
|
+
button small { color: #8b949e; font-size: 14px; line-height: 1; }
|
|
28
|
+
button small:hover { color: #ff7b72; }
|
|
29
|
+
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
30
|
+
.terminal-host { flex: 1 1 auto; min-height: 0; padding: 6px; box-sizing: border-box; overflow: hidden; }
|
|
31
|
+
.terminal-host .xterm { height: 100%; cursor: text; position: relative; user-select: none; }
|
|
32
|
+
.terminal-host .xterm.focus, .terminal-host .xterm:focus { outline: none; }
|
|
33
|
+
.terminal-host .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
34
|
+
.terminal-host .xterm-helper-textarea { position: absolute !important; left: -9999em !important; top: 0 !important; width: 0 !important; height: 0 !important; min-width: 0 !important; min-height: 0 !important; padding: 0 !important; border: 0 !important; margin: 0 !important; opacity: 0 !important; z-index: -5 !important; white-space: nowrap !important; overflow: hidden !important; resize: none !important; outline: 0 !important; appearance: none !important; }
|
|
35
|
+
.terminal-host .xterm-viewport { position: absolute; inset: 0; overflow-y: scroll; cursor: default; background-color: #05070a; }
|
|
36
|
+
.terminal-host .xterm-screen { position: relative; }
|
|
37
|
+
.terminal-host .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
38
|
+
.terminal-host .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
39
|
+
.terminal-host .xterm-accessibility:not(.debug), .terminal-host .xterm-message { position: absolute; inset: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
40
|
+
.terminal-host .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
41
|
+
.terminal-host .xterm-accessibility-tree { font-family: monospace; user-select: text; white-space: pre; }
|
|
42
|
+
.terminal-host .xterm-accessibility-tree > div { transform-origin: left; width: fit-content; }
|
|
43
|
+
.terminal-host .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
44
|
+
.error { flex: 0 0 auto; margin: 0; padding: 8px; color: #ff7b72; border-bottom: 1px solid #30363d; background: #161b22; }
|
|
45
|
+
.muted { margin: 10px; color: #8b949e; }
|
|
46
|
+
.xterm { height: 100%; }
|
|
47
|
+
`;a([b({attribute:!1})],n.prototype,"workspace",2);a([b({type:Boolean})],n.prototype,"autoStart",2);a([x(".terminal-host")],n.prototype,"terminalHost",2);a([d()],n.prototype,"terminals",2);a([d()],n.prototype,"selectedId",2);a([d()],n.prototype,"loading",2);a([d()],n.prototype,"error",2);a([d()],n.prototype,"visible",2);n=a([y("terminal-panel")],n);function I(e){const t=JSON.parse(e);if(!C(t))return{type:"error",message:"Invalid terminal message"};const i=t;return i.type==="output"&&typeof i.data=="string"?{type:"output",data:i.data,...typeof i.replay=="boolean"?{replay:i.replay}:{}}:i.type==="exit"?{type:"exit",...typeof i.exitCode=="number"?{exitCode:i.exitCode}:{}}:i.type==="error"&&typeof i.message=="string"?{type:"error",message:i.message}:{type:"error",message:"Invalid terminal message"}}function z(e){return e.replaceAll("\x1B[I","").replaceAll("\x1B[O","")}async function O(e){return typeof e=="string"?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function f(e){if(!(e===void 0||!A(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function A(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function C(e){return typeof e=="object"&&e!==null}export{n as TerminalPanel,z as filterTerminalInput};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-
|
|
2
|
-
import{Q as Kt,w as Te,J as ft,R as Ci,S as Ai,G as Mi,U as Ei,V as Ii,A as Ri,W as _i,X as Di,Y as Li,Z as Qt,x as Zt,_ as ji}from"./vendor-editor-core-B4Sq6exx.js";import{m as Oi,i as qi,d as
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CbO-Cu6v.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-D4bhXEax.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as Kt,w as Te,J as ft,R as Ci,S as Ai,G as Mi,U as Ei,V as Ii,A as Ri,W as _i,X as Di,Y as Li,Z as Qt,x as Zt,_ as ji}from"./vendor-editor-core-B4Sq6exx.js";import{m as Oi,i as qi,d as Fi}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&i(n)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();const Ve=globalThis,St=Ve.ShadowRoot&&(Ve.ShadyCSS===void 0||Ve.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,$t=Symbol(),Jt=new WeakMap;let Ws=class{constructor(e,s,i){if(this._$cssResult$=!0,i!==$t)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=s}get styleSheet(){let e=this.o;const s=this.t;if(St&&e===void 0){const i=s!==void 0&&s.length===1;i&&(e=Jt.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Jt.set(s,e))}return e}toString(){return this.cssText}};const zi=t=>new Ws(typeof t=="string"?t:t+"",void 0,$t),G=(t,...e)=>{const s=t.length===1?t[0]:e.reduce((i,r,o)=>i+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+t[o+1],t[0]);return new Ws(s,t,$t)},Wi=(t,e)=>{if(St)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const i=document.createElement("style"),r=Ve.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=s.cssText,t.appendChild(i)}},Yt=St?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const i of e.cssRules)s+=i.cssText;return zi(s)})(t):t;const{is:Ni,defineProperty:Ui,getOwnPropertyDescriptor:Bi,getOwnPropertyNames:Hi,getOwnPropertySymbols:Vi,getPrototypeOf:Gi}=Object,nt=globalThis,Xt=nt.trustedTypes,Ki=Xt?Xt.emptyScript:"",Qi=nt.reactiveElementPolyfillSupport,De=(t,e)=>t,Ke={toAttribute(t,e){switch(e){case Boolean:t=t?Ki:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let s=t;switch(e){case Boolean:s=t!==null;break;case Number:s=t===null?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch{s=null}}return s}},Pt=(t,e)=>!Ni(t,e),es={attribute:!0,type:String,converter:Ke,reflect:!1,useDefault:!1,hasChanged:Pt};Symbol.metadata??=Symbol("metadata"),nt.litPropertyMetadata??=new WeakMap;let be=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=es){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(e,s),!s.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,s);r!==void 0&&Ui(this.prototype,e,r)}}static getPropertyDescriptor(e,s,i){const{get:r,set:o}=Bi(this.prototype,e)??{get(){return this[s]},set(n){this[s]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(e,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??es}static _$Ei(){if(this.hasOwnProperty(De("elementProperties")))return;const e=Gi(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(De("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(De("properties"))){const s=this.properties,i=[...Hi(s),...Vi(s)];for(const r of i)this.createProperty(r,s[r])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[i,r]of s)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[s,i]of this.elementProperties){const r=this._$Eu(s,i);r!==void 0&&this._$Eh.set(r,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)s.unshift(Yt(r))}else e!==void 0&&s.push(Yt(e));return s}static _$Eu(e,s){const i=s.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Wi(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,s,i){this._$AK(e,i)}_$ET(e,s){const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const o=(i.converter?.toAttribute!==void 0?i.converter:Ke).toAttribute(s,i.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,s){const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ke;this._$Em=r;const a=n.fromAttribute(s,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,s,i,r=!1,o){if(e!==void 0){const n=this.constructor;if(r===!1&&(o=this[e]),i??=n.getPropertyOptions(e),!((i.hasChanged??Pt)(o,s)||i.useDefault&&i.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,s,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:i,reflect:r,wrapped:o},n){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,n??s??this[e]),o!==!0||n!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[r,o]of i){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(s)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(s)}willUpdate(e){}_$AE(e){this._$EO?.forEach(s=>s.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(s=>this._$ET(s,this[s])),this._$EM()}updated(e){}firstUpdated(e){}};be.elementStyles=[],be.shadowRootOptions={mode:"open"},be[De("elementProperties")]=new Map,be[De("finalized")]=new Map,Qi?.({ReactiveElement:be}),(nt.reactiveElementVersions??=[]).push("2.1.2");const Tt=globalThis,ts=t=>t,Qe=Tt.trustedTypes,ss=Qe?Qe.createPolicy("lit-html",{createHTML:t=>t}):void 0,Ns="$lit$",te=`lit$${Math.random().toFixed(9).slice(2)}$`,Us="?"+te,Zi=`<${Us}>`,le=document,Le=()=>le.createComment(""),je=t=>t===null||typeof t!="object"&&typeof t!="function",Ct=Array.isArray,Ji=t=>Ct(t)||typeof t?.[Symbol.iterator]=="function",gt=`[
|
|
3
3
|
\f\r]`,Ce=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,is=/-->/g,rs=/>/g,re=RegExp(`>|${gt}(?:([^\\s"'>=/]+)(${gt}*=${gt}*(?:[^
|
|
4
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),os=/'/g,ns=/"/g,Bs=/^(?:script|style|textarea|title)$/i,Yi=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),p=Yi(1),se=Symbol.for("lit-noChange"),C=Symbol.for("lit-nothing"),as=new WeakMap,ae=le.createTreeWalker(le,129);function Hs(t,e){if(!Ct(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return ss!==void 0?ss.createHTML(e):e}const Xi=(t,e)=>{const s=t.length-1,i=[];let r,o=e===2?"<svg>":e===3?"<math>":"",n=Ce;for(let a=0;a<s;a++){const l=t[a];let c,u,d=-1,f=0;for(;f<l.length&&(n.lastIndex=f,u=n.exec(l),u!==null);)f=n.lastIndex,n===Ce?u[1]==="!--"?n=is:u[1]!==void 0?n=rs:u[2]!==void 0?(Bs.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=re):u[3]!==void 0&&(n=re):n===re?u[0]===">"?(n=r??Ce,d=-1):u[1]===void 0?d=-2:(d=n.lastIndex-u[2].length,c=u[1],n=u[3]===void 0?re:u[3]==='"'?ns:os):n===ns||n===os?n=re:n===is||n===rs?n=Ce:(n=re,r=void 0);const g=n===re&&t[a+1].startsWith("/>")?" ":"";o+=n===Ce?l+Zi:d>=0?(i.push(c),l.slice(0,d)+Ns+l.slice(d)+te+g):l+te+(d===-2?a:g)}return[Hs(t,o+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Oe{constructor({strings:e,_$litType$:s},i){let r;this.parts=[];let o=0,n=0;const a=e.length-1,l=this.parts,[c,u]=Xi(e,s);if(this.el=Oe.createElement(c,i),ae.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ae.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(Ns)){const f=u[n++],g=r.getAttribute(d).split(te),m=/([.?@])?(.*)/.exec(f);l.push({type:1,index:o,name:m[2],strings:g,ctor:m[1]==="."?tr:m[1]==="?"?sr:m[1]==="@"?ir:at}),r.removeAttribute(d)}else d.startsWith(te)&&(l.push({type:6,index:o}),r.removeAttribute(d));if(Bs.test(r.tagName)){const d=r.textContent.split(te),f=d.length-1;if(f>0){r.textContent=Qe?Qe.emptyScript:"";for(let g=0;g<f;g++)r.append(d[g],Le()),ae.nextNode(),l.push({type:2,index:++o});r.append(d[f],Le())}}}else if(r.nodeType===8)if(r.data===Us)l.push({type:2,index:o});else{let d=-1;for(;(d=r.data.indexOf(te,d+1))!==-1;)l.push({type:7,index:o}),d+=te.length-1}o++}}static createElement(e,s){const i=le.createElement("template");return i.innerHTML=e,i}}function ye(t,e,s=t,i){if(e===se)return e;let r=i!==void 0?s._$Co?.[i]:s._$Cl;const o=je(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(t),r._$AT(t,s,i)),i!==void 0?(s._$Co??=[])[i]=r:s._$Cl=r),r!==void 0&&(e=ye(t,r._$AS(t,e.values),r,i)),e}class er{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:i}=this._$AD,r=(e?.creationScope??le).importNode(s,!0);ae.currentNode=r;let o=ae.nextNode(),n=0,a=0,l=i[0];for(;l!==void 0;){if(n===l.index){let c;l.type===2?c=new ke(o,o.nextSibling,this,e):l.type===1?c=new l.ctor(o,l.name,l.strings,this,e):l.type===6&&(c=new rr(o,this,e)),this._$AV.push(c),l=i[++a]}n!==l?.index&&(o=ae.nextNode(),n++)}return ae.currentNode=le,r}p(e){let s=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,s),s+=i.strings.length-2):i._$AI(e[s])),s++}}class ke{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,i,r){this.type=2,this._$AH=C,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=i,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=ye(this,e,s),je(e)?e===C||e==null||e===""?(this._$AH!==C&&this._$AR(),this._$AH=C):e!==this._$AH&&e!==se&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ji(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==C&&je(this._$AH)?this._$AA.nextSibling.data=e:this.T(le.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=Oe.createElement(Hs(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(s);else{const o=new er(r,this),n=o.u(this.options);o.p(s),this.T(n),this._$AH=o}}_$AC(e){let s=as.get(e.strings);return s===void 0&&as.set(e.strings,s=new Oe(e)),s}k(e){Ct(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let i,r=0;for(const o of e)r===s.length?s.push(i=new ke(this.O(Le()),this.O(Le()),this,this.options)):i=s[r],i._$AI(o),r++;r<s.length&&(this._$AR(i&&i._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const i=ts(e).nextSibling;ts(e).remove(),e=i}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}let at=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,i,r,o){this.type=1,this._$AH=C,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=C}_$AI(e,s=this,i,r){const o=this.strings;let n=!1;if(o===void 0)e=ye(this,e,s,0),n=!je(e)||e!==this._$AH&&e!==se,n&&(this._$AH=e);else{const a=e;let l,c;for(e=o[0],l=0;l<o.length-1;l++)c=ye(this,a[i+l],s,l),c===se&&(c=this._$AH[l]),n||=!je(c)||c!==this._$AH[l],c===C?e=C:e!==C&&(e+=(c??"")+o[l+1]),this._$AH[l]=c}n&&!r&&this.j(e)}j(e){e===C?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},tr=class extends at{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===C?void 0:e}},sr=class extends at{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==C)}},ir=class extends at{constructor(e,s,i,r,o){super(e,s,i,r,o),this.type=5}_$AI(e,s=this){if((e=ye(this,e,s,0)??C)===se)return;const i=this._$AH,r=e===C&&i!==C||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,o=e!==C&&(i===C||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}};class rr{constructor(e,s,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){ye(this,e)}}const or={I:ke},nr=Tt.litHtmlPolyfillSupport;nr?.(Oe,ke),(Tt.litHtmlVersions??=[]).push("3.3.2");const ar=(t,e,s)=>{const i=s?.renderBefore??e;let r=i._$litPart$;if(r===void 0){const o=s?.renderBefore??null;i._$litPart$=r=new ke(e.insertBefore(Le(),o),o,void 0,s??{})}return r._$AI(t),r};const At=globalThis;let _=class extends be{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=ar(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return se}};_._$litElement$=!0,_.finalized=!0,At.litElementHydrateSupport?.({LitElement:_});const lr=At.litElementPolyfillSupport;lr?.({LitElement:_});(At.litElementVersions??=[]).push("4.2.2");const W=t=>(e,s)=>{s!==void 0?s.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};const cr={attribute:!0,type:String,converter:Ke,reflect:!1,hasChanged:Pt},dr=(t=cr,e,s)=>{const{kind:i,metadata:r}=s;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),i==="setter"&&((t=Object.create(t)).wrapped=!0),o.set(s.name,t),i==="accessor"){const{name:n}=s;return{set(a){const l=e.get.call(this);e.set.call(this,a),this.requestUpdate(n,l,t,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,t,a),a}}}if(i==="setter"){const{name:n}=s;return function(a){const l=this[n];e.call(this,a),this.requestUpdate(n,l,t,!0,a)}}throw Error("Unsupported decorator location: "+i)};function h(t){return(e,s)=>typeof s=="object"?dr(t,e,s):((i,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,i),n?Object.getOwnPropertyDescriptor(r,o):void 0})(t,e,s)}function $(t){return h({...t,state:!0,attribute:!1})}const pr=(t,e,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(t,e,s),s);function ve(t,e){return(s,i,r)=>{const o=n=>n.renderRoot?.querySelector(t)??null;return pr(s,i,{get(){return o(this)}})}}async function x(t,e,s){const i=new Headers(s?.headers);s?.body!==void 0&&i.set("content-type","application/json");const r=await fetch(t,{...s,headers:i});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(hr(n)??r.statusText)}const o=await r.json();return e(o)}function hr(t){if(ur(t))return typeof t.error=="string"?t.error:void 0}function ur(t){return typeof t=="object"&&t!==null}function fr(t){return typeof t=="object"&&t!==null}function v(t){if(!fr(t))throw new Error("Expected object response");return t}function b(t,e){const s=t[e];if(typeof s!="string")throw new Error(`Expected string field: ${e}`);return s}function D(t,e){const s=t[e];if(s!==void 0){if(typeof s!="string")throw new Error(`Expected optional string field: ${e}`);return s}}function N(t,e){const s=t[e];if(typeof s!="number")throw new Error(`Expected number field: ${e}`);return s}function z(t,e){const s=t[e];if(typeof s!="boolean")throw new Error(`Expected boolean field: ${e}`);return s}function F(t){return e=>{if(!Array.isArray(e))throw new Error("Expected array response");return e.map(t)}}function gr(t){if(!Array.isArray(t))throw new Error("Expected array response");return t}function mr(t){if(Array.isArray(t))return{messages:t,start:0,total:t.length};const e=v(t);return{messages:gr(e.messages),start:N(e,"start"),total:N(e,"total")}}function ls(t){const e=v(t);return{id:b(e,"id"),name:b(e,"name"),path:b(e,"path"),createdAt:b(e,"createdAt")}}function br(t){const e=v(t),s=D(e,"branch");return{id:b(e,"id"),projectId:b(e,"projectId"),path:b(e,"path"),label:b(e,"label"),...s===void 0?{}:{branch:s},isMain:z(e,"isMain"),isGitRepo:z(e,"isGitRepo"),isGitWorktree:z(e,"isGitWorktree")}}function bt(t){const e=v(t),s=D(e,"name"),i=D(e,"parentSessionPath"),r=D(e,"archivedAt");return{id:b(e,"id"),path:b(e,"path"),cwd:b(e,"cwd"),...s===void 0?{}:{name:s},created:b(e,"created"),modified:b(e,"modified"),messageCount:N(e,"messageCount"),firstMessage:b(e,"firstMessage"),...i===void 0?{}:{parentSessionPath:i},...e.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ae(t){const e=v(t);return{sessionId:b(e,"sessionId"),isStreaming:z(e,"isStreaming"),isCompacting:z(e,"isCompacting"),isBashRunning:z(e,"isBashRunning"),pendingMessageCount:N(e,"pendingMessageCount"),queuedMessages:e.queuedMessages===void 0?[]:F(yr)(e.queuedMessages),tokens:wr(e.tokens),cost:N(e,"cost"),...xr(e.model),...$r(e.contextUsage),...E("thinkingLevel",D(e,"thinkingLevel"))}}function yr(t){const e=v(t),s=b(e,"kind");if(s!=="steer"&&s!=="followUp")throw new Error("Invalid queued message kind");return{kind:s,text:b(e,"text")}}function wr(t){const e=v(t);return{input:N(e,"input"),output:N(e,"output"),cacheRead:N(e,"cacheRead"),cacheWrite:N(e,"cacheWrite"),total:N(e,"total")}}function Vs(t){const e=v(t);return{...E("provider",D(e,"provider")),...E("id",D(e,"id")),...E("name",D(e,"name")),...E("contextWindow",qe(e,"contextWindow")),...E("reasoning",e.reasoning)}}function xr(t){return t===void 0?{}:{model:Vs(t)}}function kr(t){const e=v(t);return{models:F(Vs)(e.models)}}function vr(t){if(t!=="off"&&t!=="minimal"&&t!=="low"&&t!=="medium"&&t!=="high"&&t!=="xhigh")throw new Error("Invalid thinking level");return t}function Sr(t){const e=v(t);return{levels:F(vr)(e.levels)}}function $r(t){if(t===void 0)return{};const e=v(t);return{contextUsage:{tokens:us(e,"tokens"),contextWindow:N(e,"contextWindow"),percent:us(e,"percent")}}}function Pr(t){const e=v(t),s=b(e,"source");if(s!=="extension"&&s!=="prompt"&&s!=="skill"&&s!=="builtin")throw new Error("Invalid command source");return{name:b(e,"name"),source:s,...E("description",D(e,"description"))}}function Gs(t){const e=v(t),s=b(e,"kind");if(s!=="tracked"&&s!=="untracked"&&s!=="other")throw new Error("Invalid file kind");return{path:b(e,"path"),kind:s}}function Tr(t){const e=v(t);return{path:b(e,"path"),entries:F(Cr)(e.entries),scannedAt:b(e,"scannedAt"),truncated:z(e,"truncated")}}function Cr(t){const e=v(t),s=b(e,"type");if(s!=="file"&&s!=="directory"&&s!=="symlink")throw new Error("Invalid file tree entry type");return{name:b(e,"name"),path:b(e,"path"),type:s,...E("size",qe(e,"size")),...E("modifiedAt",D(e,"modifiedAt"))}}function Ar(t){const e=v(t),s=b(e,"encoding");if(s!=="utf8")throw new Error("Invalid file encoding");return{path:b(e,"path"),...E("language",D(e,"language")),encoding:s,size:N(e,"size"),modifiedAt:b(e,"modifiedAt"),content:b(e,"content"),truncated:z(e,"truncated"),binary:z(e,"binary")}}function Mr(t){const e=v(t);return{isGitRepo:z(e,"isGitRepo"),hash:b(e,"hash"),...E("branch",D(e,"branch")),...E("upstream",D(e,"upstream")),...E("ahead",qe(e,"ahead")),...E("behind",qe(e,"behind")),files:F(Er)(e.files)}}function Er(t){const e=v(t);return{path:b(e,"path"),...E("oldPath",D(e,"oldPath")),index:cs(e.index),workingTree:cs(e.workingTree)}}function cs(t){switch(t){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return t;default:throw new Error("Invalid git file state")}}function Ir(t){const e=v(t);return{...E("path",D(e,"path")),staged:z(e,"staged"),hash:b(e,"hash"),diff:b(e,"diff"),truncated:z(e,"truncated")}}function ds(t){const e=v(t);return{id:b(e,"id"),cwd:b(e,"cwd"),name:b(e,"name"),createdAt:b(e,"createdAt"),exited:z(e,"exited"),...E("exitCode",qe(e,"exitCode"))}}function ps(t){const e=v(t),s=b(e,"type");if(s==="unsupported")return{type:s,message:b(e,"message")};if(s==="select")return{type:s,requestId:b(e,"requestId"),title:b(e,"title"),options:F(Rr)(e.options)};if(s==="done")return{type:s,...E("message",D(e,"message")),..._r(e.session)};throw new Error("Invalid command result type")}function Rr(t){const e=v(t);return{value:b(e,"value"),label:b(e,"label"),...E("description",D(e,"description"))}}function _r(t){return t===void 0?{}:{session:bt(t)}}function hs(t){if(v(t).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Ks(t){if(v(t).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Dr(t){if(v(t).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Lr(t){if(v(t).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function jr(t){if(v(t).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function Or(t){if(v(t).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function qr(t){if(v(t).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function qe(t,e){const s=t[e];if(s!==void 0){if(typeof s!="number")throw new Error(`Expected optional number field: ${e}`);return s}}function us(t,e){const s=t[e];if(s===null)return null;if(typeof s!="number")throw new Error(`Expected number|null field: ${e}`);return s}function E(t,e){return e===void 0?{}:{[t]:e}}function zr(t,e,s){const i=new URLSearchParams;s?.path!==void 0&&i.set("path",s.path),s?.staged===!0&&i.set("staged","true");const r=i.toString();return`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/diff${r?`?${r}`:""}`}function Fr(t,e){const s=new URLSearchParams;e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.before!==void 0&&s.set("before",String(e.before));const i=s.toString();return`/api/sessions/${t}/messages${i?`?${i}`:""}`}const Wr={projects:()=>x("/api/projects",F(ls)),addProject:(t,e,s)=>x("/api/projects",ls,{method:"POST",body:JSON.stringify({path:t,name:e,create:s})}),closeProject:t=>x(`/api/projects/${encodeURIComponent(t)}`,Ks,{method:"DELETE"}),projectDirectories:t=>x(`/api/project-directories?q=${encodeURIComponent(t)}`,F(Gs))},Nr={workspaces:t=>x(`/api/projects/${t}/workspaces`,F(br)),workspaceTree:(t,e,s="")=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/tree?path=${encodeURIComponent(s)}`,Tr),workspaceFile:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/file?path=${encodeURIComponent(s)}`,Ar)},Ur={sessions:t=>x(`/api/sessions?cwd=${encodeURIComponent(t)}`,F(bt)),startSession:t=>x("/api/sessions",bt,{method:"POST",body:JSON.stringify({cwd:t})}),messages:(t,e)=>x(Fr(t,e),mr),status:t=>x(`/api/sessions/${t}/status`,Ae),models:t=>x(`/api/sessions/${t}/models`,kr),setModel:(t,e,s)=>x(`/api/sessions/${t}/model`,Ae,{method:"POST",body:JSON.stringify({provider:e,modelId:s})}),cycleModel:(t,e)=>x(`/api/sessions/${t}/model/cycle`,Ae,{method:"POST",body:JSON.stringify({direction:e})}),thinkingLevels:t=>x(`/api/sessions/${t}/thinking-levels`,Sr),setThinkingLevel:(t,e)=>x(`/api/sessions/${t}/thinking-level`,Ae,{method:"POST",body:JSON.stringify({level:e})}),cycleThinkingLevel:t=>x(`/api/sessions/${t}/thinking-level/cycle`,Ae,{method:"POST"}),commands:t=>x(`/api/sessions/${t}/commands`,F(Pr)),prompt:(t,e,s)=>x(`/api/sessions/${t}/prompt`,hs,{method:"POST",body:JSON.stringify(s===void 0?{text:e}:{text:e,streamingBehavior:s})}),shell:(t,e)=>x(`/api/sessions/${t}/shell`,hs,{method:"POST",body:JSON.stringify({text:e})}),runCommand:(t,e)=>x(`/api/sessions/${t}/commands/run`,ps,{method:"POST",body:JSON.stringify({text:e})}),respondToCommand:(t,e,s)=>x(`/api/sessions/${t}/commands/respond`,ps,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),abort:t=>x(`/api/sessions/${t}/abort`,Dr,{method:"POST"}),stop:t=>x(`/api/sessions/${t}/stop`,Lr,{method:"POST"}),archive:t=>x(`/api/sessions/${t}/archive`,jr,{method:"POST"}),restore:t=>x(`/api/sessions/${t}/restore`,Or,{method:"POST"}),detachParent:t=>x(`/api/sessions/${t}/detach-parent`,qr,{method:"POST"})},Qs={terminals:(t,e)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,F(ds)),startTerminal:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,ds,{method:"POST",body:JSON.stringify(s??{})}),closeTerminal:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}`,Ks,{method:"DELETE"})},Br={files:(t,e,s,i)=>x(`/api/files?cwd=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}${s!==void 0?`&kind=${encodeURIComponent(s)}`:""}${i!==void 0?`&mode=${encodeURIComponent(i)}`:""}`,F(Gs))},Hr={gitStatus:(t,e)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/status`,Mr),gitDiff:(t,e,s)=>x(zr(t,e,s),Ir)},y={...Wr,...Nr,...Ur,...Qs,...Br,...Hr};function Vr(t){return new WebSocket(`${Mt()}/api/sessions/${t}/events`)}function lc(t,e,s){return new WebSocket(`${Mt()}/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}/socket`)}function Gr(){return new WebSocket(`${Mt()}/api/events`)}function Mt(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Kr(){return{projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,error:""}}function Ze(t){return t.replaceAll(":",".")}function Qr(t){const e=new URLSearchParams(window.location.search),s=`${t}--`,i={};for(const[r,o]of e.entries()){if(!r.startsWith(s))continue;const n=r.slice(s.length),a=i[n];a===void 0?i[n]=o:Array.isArray(a)?a.push(o):i[n]=[a,o]}return i}function fs(t,e){const s=Qr(t)[e];return Array.isArray(s)?s[0]:s===""?void 0:s}function Je(t,e,s,i){const r=new URL(window.location.href),o=`${t}--${e}`;if(r.searchParams.delete(o),s!=null&&s!=="")if(Array.isArray(s))for(const n of s)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(s));Zr(r,i)}function Zr(t,e){const s=`${t.pathname}${t.search}${t.hash}`,i=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==i&&(e?.replace===!0?window.history.replaceState({},"",t):window.history.pushState({},"",t))}const gs=Ze("core:workspace.files");class Jr{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}async refreshFiles(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await y.workspaceTree(e.id,s.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await y.workspaceTree(e.id,s.id,o)).entries})),this.setState({fileTree:i.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(i){this.setState({error:String(i)})}}async expandDir(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:Xr(this.getState().expandedDirs,e)});return}try{const r=await y.workspaceTree(s.id,i.id,e);this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Je(gs,"file",e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{const r=await y.workspaceFile(s.id,i.id,e);this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==e)return;if(Yr(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Je(gs,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function Yr(t){const e=String(t);return e.includes("Path does not exist")||e.includes("ENOENT")||e.includes("no such file or directory")}function Xr(t,e){return Object.fromEntries(Object.entries(t).filter(([s])=>s!==e))}const ms=Ze("core:workspace.git");class eo{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await y.gitStatus(e.id,s.id);this.setState({gitStatus:i,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(i.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Je(ms,"diff",void 0,{replace:!0})))}catch(i){this.setState({error:String(i)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),Je(ms,"diff",e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0))try{const[r,o]=await Promise.all([y.gitDiff(s.id,i.id,{path:e}),y.gitDiff(s.id,i.id,{path:e,staged:!0})]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const e=this.getState();(e.workspaceTool==="core:workspace.git"||e.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class to{constructor(e,s,i){this.getState=e,this.setState=s,this.workspaces=i}async loadProjects(){this.setState({error:""});try{this.setState({projects:await y.projects()})}catch(e){this.setState({error:String(e)})}}async addProject(e,s){if(e.trim()!=="")try{const i=await y.addProject(e.trim(),void 0,s),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i)}catch(i){this.setState({error:String(i)})}}async closeProject(e){try{await y.closeProject(e),this.workspaces.forgetProject(e);const s=this.getState();this.setState({projects:s.projects.filter(i=>i.id!==e)}),s.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(s){this.setState({error:String(s)})}}}function me(t){return t.flatMap(lt).filter(e=>e.parts.length>0)}function Q(t,e){return{role:t,parts:[{type:"text",text:e}]}}function Ne(t,e){const s=lo(e);return s===void 0?t:{...t,meta:s}}function so(t,e,s){if(s==="")return t;const i=t.at(-1),r=i?.parts.at(-1);return i?.role===e&&r?.type==="text"?[...t.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...r,text:r.text+s}]}]:i?.role===e?[...t.slice(0,-1),{...i,parts:[...i.parts,{type:"text",text:s}]}]:[...t,Q(e,s)]}function io(t,e){if(e==="")return t;const s=t.at(-1),i=s?.parts.at(-1);return s?.role==="assistant"&&i?.type==="thinking"?[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:i.text+e}]}]:s?.role==="assistant"?[...t.slice(0,-1),{...s,parts:[...s.parts,{type:"thinking",text:e}]}]:[...t,{role:"assistant",parts:[{type:"thinking",text:e}]}]}function lt(t){if(ro(t))return[t];if(M(t,"role")==="bashExecution")return[Ne(ho(t),t)];const e=uo(M(t,"role")),s=fo(ie(t,"content"),t),i=e==="user"?oo(s):void 0;if(i!==void 0)return i.map(a=>Ne(a,t));const r=ao(t);if(e==="tool")return[Ne({role:e,parts:s,...r===void 0?{}:{source:r}},t)];const o=s.filter(a=>a.type!=="empty"),n=e==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":e;return o.length>0?[Ne({role:n,parts:o,...r===void 0?{}:{source:r}},t)]:[]}function ro(t){const e=M(t,"role");return(e==="user"||e==="assistant"||e==="tool"||e==="system"||e==="bash"||e==="skill")&&Array.isArray(ie(t,"parts"))}function oo(t){if(t.length!==1||t[0]?.type!=="text")return;const e=no(t[0].text);if(e!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:e.name,location:e.location,content:e.content}]},...e.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:e.userMessage}]}]]}function no(t){const e=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(t);if(e===null)return;const s=e[4]?.trim();return{name:e[1]??"skill",location:e[2]??"",content:e[3]??"",...s===void 0||s===""?{}:{userMessage:s}}}function ao(t){const e=M(t,"source");if(e==="compaction"||e==="branch_summary")return e}function lo(t){const e=co(ie(t,"timestamp")),s=po(t);if(!(e===void 0&&s===void 0))return{...e===void 0?{}:{timestamp:e},...s===void 0?{}:{model:s}}}function co(t){if(typeof t=="number"&&Number.isFinite(t))return new Date(t).toISOString();if(typeof t!="string"||t==="")return;const e=Date.parse(t);return Number.isFinite(e)?new Date(e).toISOString():void 0}function po(t){if(M(t,"role")!=="assistant")return;const e=M(t,"provider"),s=M(t,"model"),i=M(t,"responseModel");if(!((e===void 0||e==="")&&(s===void 0||s==="")&&(i===void 0||i==="")))return{...e===void 0||e===""?{}:{provider:e},...s===void 0||s===""?{}:{id:s},...i===void 0||i===""?{}:{responseId:i}}}function ho(t){const e=M(t,"command")??"",s=Ge(t,"excludeFromContext")===!0?["excluded from context","",`$ ${e}`]:[`$ ${e}`],i=ie(t,"output");i!=null&&s.push("",Ye(i));const r=ie(t,"exitCode");r!=null&&s.push("",`exit ${Ye(r)}`),Ge(t,"cancelled")===!0&&s.push("","cancelled"),Ge(t,"truncated")===!0&&s.push("","output truncated");const o=M(t,"fullOutputPath");return o!==void 0&&o!==""&&s.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:s.join(`
|
|
4
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),os=/'/g,ns=/"/g,Bs=/^(?:script|style|textarea|title)$/i,Yi=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),p=Yi(1),se=Symbol.for("lit-noChange"),C=Symbol.for("lit-nothing"),as=new WeakMap,ae=le.createTreeWalker(le,129);function Hs(t,e){if(!Ct(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return ss!==void 0?ss.createHTML(e):e}const Xi=(t,e)=>{const s=t.length-1,i=[];let r,o=e===2?"<svg>":e===3?"<math>":"",n=Ce;for(let a=0;a<s;a++){const l=t[a];let c,u,d=-1,f=0;for(;f<l.length&&(n.lastIndex=f,u=n.exec(l),u!==null);)f=n.lastIndex,n===Ce?u[1]==="!--"?n=is:u[1]!==void 0?n=rs:u[2]!==void 0?(Bs.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=re):u[3]!==void 0&&(n=re):n===re?u[0]===">"?(n=r??Ce,d=-1):u[1]===void 0?d=-2:(d=n.lastIndex-u[2].length,c=u[1],n=u[3]===void 0?re:u[3]==='"'?ns:os):n===ns||n===os?n=re:n===is||n===rs?n=Ce:(n=re,r=void 0);const g=n===re&&t[a+1].startsWith("/>")?" ":"";o+=n===Ce?l+Zi:d>=0?(i.push(c),l.slice(0,d)+Ns+l.slice(d)+te+g):l+te+(d===-2?a:g)}return[Hs(t,o+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Oe{constructor({strings:e,_$litType$:s},i){let r;this.parts=[];let o=0,n=0;const a=e.length-1,l=this.parts,[c,u]=Xi(e,s);if(this.el=Oe.createElement(c,i),ae.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ae.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(Ns)){const f=u[n++],g=r.getAttribute(d).split(te),m=/([.?@])?(.*)/.exec(f);l.push({type:1,index:o,name:m[2],strings:g,ctor:m[1]==="."?tr:m[1]==="?"?sr:m[1]==="@"?ir:at}),r.removeAttribute(d)}else d.startsWith(te)&&(l.push({type:6,index:o}),r.removeAttribute(d));if(Bs.test(r.tagName)){const d=r.textContent.split(te),f=d.length-1;if(f>0){r.textContent=Qe?Qe.emptyScript:"";for(let g=0;g<f;g++)r.append(d[g],Le()),ae.nextNode(),l.push({type:2,index:++o});r.append(d[f],Le())}}}else if(r.nodeType===8)if(r.data===Us)l.push({type:2,index:o});else{let d=-1;for(;(d=r.data.indexOf(te,d+1))!==-1;)l.push({type:7,index:o}),d+=te.length-1}o++}}static createElement(e,s){const i=le.createElement("template");return i.innerHTML=e,i}}function ye(t,e,s=t,i){if(e===se)return e;let r=i!==void 0?s._$Co?.[i]:s._$Cl;const o=je(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(t),r._$AT(t,s,i)),i!==void 0?(s._$Co??=[])[i]=r:s._$Cl=r),r!==void 0&&(e=ye(t,r._$AS(t,e.values),r,i)),e}class er{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:i}=this._$AD,r=(e?.creationScope??le).importNode(s,!0);ae.currentNode=r;let o=ae.nextNode(),n=0,a=0,l=i[0];for(;l!==void 0;){if(n===l.index){let c;l.type===2?c=new ke(o,o.nextSibling,this,e):l.type===1?c=new l.ctor(o,l.name,l.strings,this,e):l.type===6&&(c=new rr(o,this,e)),this._$AV.push(c),l=i[++a]}n!==l?.index&&(o=ae.nextNode(),n++)}return ae.currentNode=le,r}p(e){let s=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,s),s+=i.strings.length-2):i._$AI(e[s])),s++}}class ke{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,i,r){this.type=2,this._$AH=C,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=i,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=ye(this,e,s),je(e)?e===C||e==null||e===""?(this._$AH!==C&&this._$AR(),this._$AH=C):e!==this._$AH&&e!==se&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ji(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==C&&je(this._$AH)?this._$AA.nextSibling.data=e:this.T(le.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=Oe.createElement(Hs(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(s);else{const o=new er(r,this),n=o.u(this.options);o.p(s),this.T(n),this._$AH=o}}_$AC(e){let s=as.get(e.strings);return s===void 0&&as.set(e.strings,s=new Oe(e)),s}k(e){Ct(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let i,r=0;for(const o of e)r===s.length?s.push(i=new ke(this.O(Le()),this.O(Le()),this,this.options)):i=s[r],i._$AI(o),r++;r<s.length&&(this._$AR(i&&i._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const i=ts(e).nextSibling;ts(e).remove(),e=i}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}let at=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,i,r,o){this.type=1,this._$AH=C,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=C}_$AI(e,s=this,i,r){const o=this.strings;let n=!1;if(o===void 0)e=ye(this,e,s,0),n=!je(e)||e!==this._$AH&&e!==se,n&&(this._$AH=e);else{const a=e;let l,c;for(e=o[0],l=0;l<o.length-1;l++)c=ye(this,a[i+l],s,l),c===se&&(c=this._$AH[l]),n||=!je(c)||c!==this._$AH[l],c===C?e=C:e!==C&&(e+=(c??"")+o[l+1]),this._$AH[l]=c}n&&!r&&this.j(e)}j(e){e===C?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},tr=class extends at{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===C?void 0:e}},sr=class extends at{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==C)}},ir=class extends at{constructor(e,s,i,r,o){super(e,s,i,r,o),this.type=5}_$AI(e,s=this){if((e=ye(this,e,s,0)??C)===se)return;const i=this._$AH,r=e===C&&i!==C||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,o=e!==C&&(i===C||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}};class rr{constructor(e,s,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){ye(this,e)}}const or={I:ke},nr=Tt.litHtmlPolyfillSupport;nr?.(Oe,ke),(Tt.litHtmlVersions??=[]).push("3.3.2");const ar=(t,e,s)=>{const i=s?.renderBefore??e;let r=i._$litPart$;if(r===void 0){const o=s?.renderBefore??null;i._$litPart$=r=new ke(e.insertBefore(Le(),o),o,void 0,s??{})}return r._$AI(t),r};const At=globalThis;let _=class extends be{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=ar(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return se}};_._$litElement$=!0,_.finalized=!0,At.litElementHydrateSupport?.({LitElement:_});const lr=At.litElementPolyfillSupport;lr?.({LitElement:_});(At.litElementVersions??=[]).push("4.2.2");const W=t=>(e,s)=>{s!==void 0?s.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};const cr={attribute:!0,type:String,converter:Ke,reflect:!1,hasChanged:Pt},dr=(t=cr,e,s)=>{const{kind:i,metadata:r}=s;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),i==="setter"&&((t=Object.create(t)).wrapped=!0),o.set(s.name,t),i==="accessor"){const{name:n}=s;return{set(a){const l=e.get.call(this);e.set.call(this,a),this.requestUpdate(n,l,t,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,t,a),a}}}if(i==="setter"){const{name:n}=s;return function(a){const l=this[n];e.call(this,a),this.requestUpdate(n,l,t,!0,a)}}throw Error("Unsupported decorator location: "+i)};function h(t){return(e,s)=>typeof s=="object"?dr(t,e,s):((i,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,i),n?Object.getOwnPropertyDescriptor(r,o):void 0})(t,e,s)}function $(t){return h({...t,state:!0,attribute:!1})}const pr=(t,e,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(t,e,s),s);function ve(t,e){return(s,i,r)=>{const o=n=>n.renderRoot?.querySelector(t)??null;return pr(s,i,{get(){return o(this)}})}}async function x(t,e,s){const i=new Headers(s?.headers);s?.body!==void 0&&i.set("content-type","application/json");const r=await fetch(t,{...s,headers:i});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(hr(n)??r.statusText)}const o=await r.json();return e(o)}function hr(t){if(ur(t))return typeof t.error=="string"?t.error:void 0}function ur(t){return typeof t=="object"&&t!==null}function fr(t){return typeof t=="object"&&t!==null}function v(t){if(!fr(t))throw new Error("Expected object response");return t}function b(t,e){const s=t[e];if(typeof s!="string")throw new Error(`Expected string field: ${e}`);return s}function D(t,e){const s=t[e];if(s!==void 0){if(typeof s!="string")throw new Error(`Expected optional string field: ${e}`);return s}}function N(t,e){const s=t[e];if(typeof s!="number")throw new Error(`Expected number field: ${e}`);return s}function F(t,e){const s=t[e];if(typeof s!="boolean")throw new Error(`Expected boolean field: ${e}`);return s}function z(t){return e=>{if(!Array.isArray(e))throw new Error("Expected array response");return e.map(t)}}function gr(t){if(!Array.isArray(t))throw new Error("Expected array response");return t}function mr(t){if(Array.isArray(t))return{messages:t,start:0,total:t.length};const e=v(t);return{messages:gr(e.messages),start:N(e,"start"),total:N(e,"total")}}function ls(t){const e=v(t);return{id:b(e,"id"),name:b(e,"name"),path:b(e,"path"),createdAt:b(e,"createdAt")}}function br(t){const e=v(t),s=D(e,"branch");return{id:b(e,"id"),projectId:b(e,"projectId"),path:b(e,"path"),label:b(e,"label"),...s===void 0?{}:{branch:s},isMain:F(e,"isMain"),isGitRepo:F(e,"isGitRepo"),isGitWorktree:F(e,"isGitWorktree")}}function bt(t){const e=v(t),s=D(e,"name"),i=D(e,"parentSessionPath"),r=D(e,"archivedAt");return{id:b(e,"id"),path:b(e,"path"),cwd:b(e,"cwd"),...s===void 0?{}:{name:s},created:b(e,"created"),modified:b(e,"modified"),messageCount:N(e,"messageCount"),firstMessage:b(e,"firstMessage"),...i===void 0?{}:{parentSessionPath:i},...e.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ae(t){const e=v(t);return{sessionId:b(e,"sessionId"),isStreaming:F(e,"isStreaming"),isCompacting:F(e,"isCompacting"),isBashRunning:F(e,"isBashRunning"),pendingMessageCount:N(e,"pendingMessageCount"),queuedMessages:e.queuedMessages===void 0?[]:z(yr)(e.queuedMessages),tokens:wr(e.tokens),cost:N(e,"cost"),...xr(e.model),...$r(e.contextUsage),...E("thinkingLevel",D(e,"thinkingLevel"))}}function yr(t){const e=v(t),s=b(e,"kind");if(s!=="steer"&&s!=="followUp")throw new Error("Invalid queued message kind");return{kind:s,text:b(e,"text")}}function wr(t){const e=v(t);return{input:N(e,"input"),output:N(e,"output"),cacheRead:N(e,"cacheRead"),cacheWrite:N(e,"cacheWrite"),total:N(e,"total")}}function Vs(t){const e=v(t);return{...E("provider",D(e,"provider")),...E("id",D(e,"id")),...E("name",D(e,"name")),...E("contextWindow",qe(e,"contextWindow")),...E("reasoning",e.reasoning)}}function xr(t){return t===void 0?{}:{model:Vs(t)}}function kr(t){const e=v(t);return{models:z(Vs)(e.models)}}function vr(t){if(t!=="off"&&t!=="minimal"&&t!=="low"&&t!=="medium"&&t!=="high"&&t!=="xhigh")throw new Error("Invalid thinking level");return t}function Sr(t){const e=v(t);return{levels:z(vr)(e.levels)}}function $r(t){if(t===void 0)return{};const e=v(t);return{contextUsage:{tokens:us(e,"tokens"),contextWindow:N(e,"contextWindow"),percent:us(e,"percent")}}}function Pr(t){const e=v(t),s=b(e,"source");if(s!=="extension"&&s!=="prompt"&&s!=="skill"&&s!=="builtin")throw new Error("Invalid command source");return{name:b(e,"name"),source:s,...E("description",D(e,"description"))}}function Gs(t){const e=v(t),s=b(e,"kind");if(s!=="tracked"&&s!=="untracked"&&s!=="other")throw new Error("Invalid file kind");return{path:b(e,"path"),kind:s}}function Tr(t){const e=v(t);return{path:b(e,"path"),entries:z(Cr)(e.entries),scannedAt:b(e,"scannedAt"),truncated:F(e,"truncated")}}function Cr(t){const e=v(t),s=b(e,"type");if(s!=="file"&&s!=="directory"&&s!=="symlink")throw new Error("Invalid file tree entry type");return{name:b(e,"name"),path:b(e,"path"),type:s,...E("size",qe(e,"size")),...E("modifiedAt",D(e,"modifiedAt"))}}function Ar(t){const e=v(t),s=b(e,"encoding");if(s!=="utf8")throw new Error("Invalid file encoding");return{path:b(e,"path"),...E("language",D(e,"language")),encoding:s,size:N(e,"size"),modifiedAt:b(e,"modifiedAt"),content:b(e,"content"),truncated:F(e,"truncated"),binary:F(e,"binary")}}function Mr(t){const e=v(t);return{isGitRepo:F(e,"isGitRepo"),hash:b(e,"hash"),...E("branch",D(e,"branch")),...E("upstream",D(e,"upstream")),...E("ahead",qe(e,"ahead")),...E("behind",qe(e,"behind")),files:z(Er)(e.files)}}function Er(t){const e=v(t);return{path:b(e,"path"),...E("oldPath",D(e,"oldPath")),index:cs(e.index),workingTree:cs(e.workingTree)}}function cs(t){switch(t){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return t;default:throw new Error("Invalid git file state")}}function Ir(t){const e=v(t);return{...E("path",D(e,"path")),staged:F(e,"staged"),hash:b(e,"hash"),diff:b(e,"diff"),truncated:F(e,"truncated")}}function ds(t){const e=v(t);return{id:b(e,"id"),cwd:b(e,"cwd"),name:b(e,"name"),createdAt:b(e,"createdAt"),exited:F(e,"exited"),...E("exitCode",qe(e,"exitCode"))}}function ps(t){const e=v(t),s=b(e,"type");if(s==="unsupported")return{type:s,message:b(e,"message")};if(s==="select")return{type:s,requestId:b(e,"requestId"),title:b(e,"title"),options:z(Rr)(e.options)};if(s==="done")return{type:s,...E("message",D(e,"message")),..._r(e.session)};throw new Error("Invalid command result type")}function Rr(t){const e=v(t);return{value:b(e,"value"),label:b(e,"label"),...E("description",D(e,"description"))}}function _r(t){return t===void 0?{}:{session:bt(t)}}function hs(t){if(v(t).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Ks(t){if(v(t).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Dr(t){if(v(t).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Lr(t){if(v(t).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function jr(t){if(v(t).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function Or(t){if(v(t).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function qr(t){if(v(t).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function qe(t,e){const s=t[e];if(s!==void 0){if(typeof s!="number")throw new Error(`Expected optional number field: ${e}`);return s}}function us(t,e){const s=t[e];if(s===null)return null;if(typeof s!="number")throw new Error(`Expected number|null field: ${e}`);return s}function E(t,e){return e===void 0?{}:{[t]:e}}function Fr(t,e,s){const i=new URLSearchParams;s?.path!==void 0&&i.set("path",s.path),s?.staged===!0&&i.set("staged","true");const r=i.toString();return`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/diff${r?`?${r}`:""}`}function zr(t,e){const s=new URLSearchParams;e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.before!==void 0&&s.set("before",String(e.before));const i=s.toString();return`/api/sessions/${t}/messages${i?`?${i}`:""}`}const Wr={projects:()=>x("/api/projects",z(ls)),addProject:(t,e,s)=>x("/api/projects",ls,{method:"POST",body:JSON.stringify({path:t,name:e,create:s})}),closeProject:t=>x(`/api/projects/${encodeURIComponent(t)}`,Ks,{method:"DELETE"}),projectDirectories:t=>x(`/api/project-directories?q=${encodeURIComponent(t)}`,z(Gs))},Nr={workspaces:t=>x(`/api/projects/${t}/workspaces`,z(br)),workspaceTree:(t,e,s="")=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/tree?path=${encodeURIComponent(s)}`,Tr),workspaceFile:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/file?path=${encodeURIComponent(s)}`,Ar)},Ur={sessions:t=>x(`/api/sessions?cwd=${encodeURIComponent(t)}`,z(bt)),startSession:t=>x("/api/sessions",bt,{method:"POST",body:JSON.stringify({cwd:t})}),messages:(t,e)=>x(zr(t,e),mr),status:t=>x(`/api/sessions/${t}/status`,Ae),models:t=>x(`/api/sessions/${t}/models`,kr),setModel:(t,e,s)=>x(`/api/sessions/${t}/model`,Ae,{method:"POST",body:JSON.stringify({provider:e,modelId:s})}),cycleModel:(t,e)=>x(`/api/sessions/${t}/model/cycle`,Ae,{method:"POST",body:JSON.stringify({direction:e})}),thinkingLevels:t=>x(`/api/sessions/${t}/thinking-levels`,Sr),setThinkingLevel:(t,e)=>x(`/api/sessions/${t}/thinking-level`,Ae,{method:"POST",body:JSON.stringify({level:e})}),cycleThinkingLevel:t=>x(`/api/sessions/${t}/thinking-level/cycle`,Ae,{method:"POST"}),commands:t=>x(`/api/sessions/${t}/commands`,z(Pr)),prompt:(t,e,s)=>x(`/api/sessions/${t}/prompt`,hs,{method:"POST",body:JSON.stringify(s===void 0?{text:e}:{text:e,streamingBehavior:s})}),shell:(t,e)=>x(`/api/sessions/${t}/shell`,hs,{method:"POST",body:JSON.stringify({text:e})}),runCommand:(t,e)=>x(`/api/sessions/${t}/commands/run`,ps,{method:"POST",body:JSON.stringify({text:e})}),respondToCommand:(t,e,s)=>x(`/api/sessions/${t}/commands/respond`,ps,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),abort:t=>x(`/api/sessions/${t}/abort`,Dr,{method:"POST"}),stop:t=>x(`/api/sessions/${t}/stop`,Lr,{method:"POST"}),archive:t=>x(`/api/sessions/${t}/archive`,jr,{method:"POST"}),restore:t=>x(`/api/sessions/${t}/restore`,Or,{method:"POST"}),detachParent:t=>x(`/api/sessions/${t}/detach-parent`,qr,{method:"POST"})},Qs={terminals:(t,e)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,z(ds)),startTerminal:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,ds,{method:"POST",body:JSON.stringify(s??{})}),closeTerminal:(t,e,s)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}`,Ks,{method:"DELETE"})},Br={files:(t,e,s,i)=>x(`/api/files?cwd=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}${s!==void 0?`&kind=${encodeURIComponent(s)}`:""}${i!==void 0?`&mode=${encodeURIComponent(i)}`:""}`,z(Gs))},Hr={gitStatus:(t,e)=>x(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/status`,Mr),gitDiff:(t,e,s)=>x(Fr(t,e,s),Ir)},y={...Wr,...Nr,...Ur,...Qs,...Br,...Hr};function Vr(t){return new WebSocket(`${Mt()}/api/sessions/${t}/events`)}function lc(t,e,s,i){const r=i===void 0?"":`?cols=${encodeURIComponent(String(i.cols))}&rows=${encodeURIComponent(String(i.rows))}`;return new WebSocket(`${Mt()}/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}/socket${r}`)}function Gr(){return new WebSocket(`${Mt()}/api/events`)}function Mt(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Kr(){return{projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,error:""}}function Ze(t){return t.replaceAll(":",".")}function Qr(t){const e=new URLSearchParams(window.location.search),s=`${t}--`,i={};for(const[r,o]of e.entries()){if(!r.startsWith(s))continue;const n=r.slice(s.length),a=i[n];a===void 0?i[n]=o:Array.isArray(a)?a.push(o):i[n]=[a,o]}return i}function fs(t,e){const s=Qr(t)[e];return Array.isArray(s)?s[0]:s===""?void 0:s}function Je(t,e,s,i){const r=new URL(window.location.href),o=`${t}--${e}`;if(r.searchParams.delete(o),s!=null&&s!=="")if(Array.isArray(s))for(const n of s)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(s));Zr(r,i)}function Zr(t,e){const s=`${t.pathname}${t.search}${t.hash}`,i=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==i&&(e?.replace===!0?window.history.replaceState({},"",t):window.history.pushState({},"",t))}const gs=Ze("core:workspace.files");class Jr{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}async refreshFiles(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await y.workspaceTree(e.id,s.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await y.workspaceTree(e.id,s.id,o)).entries})),this.setState({fileTree:i.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(i){this.setState({error:String(i)})}}async expandDir(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:Xr(this.getState().expandedDirs,e)});return}try{const r=await y.workspaceTree(s.id,i.id,e);this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Je(gs,"file",e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{const r=await y.workspaceFile(s.id,i.id,e);this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==e)return;if(Yr(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Je(gs,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function Yr(t){const e=String(t);return e.includes("Path does not exist")||e.includes("ENOENT")||e.includes("no such file or directory")}function Xr(t,e){return Object.fromEntries(Object.entries(t).filter(([s])=>s!==e))}const ms=Ze("core:workspace.git");class eo{constructor(e,s,i){this.getState=e,this.setState=s,this.updateUrl=i}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const e=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(e===void 0||s===void 0))try{const i=await y.gitStatus(e.id,s.id);this.setState({gitStatus:i,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(i.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Je(ms,"diff",void 0,{replace:!0})))}catch(i){this.setState({error:String(i)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),Je(ms,"diff",e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){const s=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(s===void 0||i===void 0))try{const[r,o]=await Promise.all([y.gitDiff(s.id,i.id,{path:e}),y.gitDiff(s.id,i.id,{path:e,staged:!0})]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const e=this.getState();(e.workspaceTool==="core:workspace.git"||e.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class to{constructor(e,s,i){this.getState=e,this.setState=s,this.workspaces=i}async loadProjects(){this.setState({error:""});try{this.setState({projects:await y.projects()})}catch(e){this.setState({error:String(e)})}}async addProject(e,s){if(e.trim()!=="")try{const i=await y.addProject(e.trim(),void 0,s),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i)}catch(i){this.setState({error:String(i)})}}async closeProject(e){try{await y.closeProject(e),this.workspaces.forgetProject(e);const s=this.getState();this.setState({projects:s.projects.filter(i=>i.id!==e)}),s.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(s){this.setState({error:String(s)})}}}function me(t){return t.flatMap(lt).filter(e=>e.parts.length>0)}function Q(t,e){return{role:t,parts:[{type:"text",text:e}]}}function Ne(t,e){const s=lo(e);return s===void 0?t:{...t,meta:s}}function so(t,e,s){if(s==="")return t;const i=t.at(-1),r=i?.parts.at(-1);return i?.role===e&&r?.type==="text"?[...t.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...r,text:r.text+s}]}]:i?.role===e?[...t.slice(0,-1),{...i,parts:[...i.parts,{type:"text",text:s}]}]:[...t,Q(e,s)]}function io(t,e){if(e==="")return t;const s=t.at(-1),i=s?.parts.at(-1);return s?.role==="assistant"&&i?.type==="thinking"?[...t.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...i,text:i.text+e}]}]:s?.role==="assistant"?[...t.slice(0,-1),{...s,parts:[...s.parts,{type:"thinking",text:e}]}]:[...t,{role:"assistant",parts:[{type:"thinking",text:e}]}]}function lt(t){if(ro(t))return[t];if(M(t,"role")==="bashExecution")return[Ne(ho(t),t)];const e=uo(M(t,"role")),s=fo(ie(t,"content"),t),i=e==="user"?oo(s):void 0;if(i!==void 0)return i.map(a=>Ne(a,t));const r=ao(t);if(e==="tool")return[Ne({role:e,parts:s,...r===void 0?{}:{source:r}},t)];const o=s.filter(a=>a.type!=="empty"),n=e==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":e;return o.length>0?[Ne({role:n,parts:o,...r===void 0?{}:{source:r}},t)]:[]}function ro(t){const e=M(t,"role");return(e==="user"||e==="assistant"||e==="tool"||e==="system"||e==="bash"||e==="skill")&&Array.isArray(ie(t,"parts"))}function oo(t){if(t.length!==1||t[0]?.type!=="text")return;const e=no(t[0].text);if(e!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:e.name,location:e.location,content:e.content}]},...e.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:e.userMessage}]}]]}function no(t){const e=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(t);if(e===null)return;const s=e[4]?.trim();return{name:e[1]??"skill",location:e[2]??"",content:e[3]??"",...s===void 0||s===""?{}:{userMessage:s}}}function ao(t){const e=M(t,"source");if(e==="compaction"||e==="branch_summary")return e}function lo(t){const e=co(ie(t,"timestamp")),s=po(t);if(!(e===void 0&&s===void 0))return{...e===void 0?{}:{timestamp:e},...s===void 0?{}:{model:s}}}function co(t){if(typeof t=="number"&&Number.isFinite(t))return new Date(t).toISOString();if(typeof t!="string"||t==="")return;const e=Date.parse(t);return Number.isFinite(e)?new Date(e).toISOString():void 0}function po(t){if(M(t,"role")!=="assistant")return;const e=M(t,"provider"),s=M(t,"model"),i=M(t,"responseModel");if(!((e===void 0||e==="")&&(s===void 0||s==="")&&(i===void 0||i==="")))return{...e===void 0||e===""?{}:{provider:e},...s===void 0||s===""?{}:{id:s},...i===void 0||i===""?{}:{responseId:i}}}function ho(t){const e=M(t,"command")??"",s=Ge(t,"excludeFromContext")===!0?["excluded from context","",`$ ${e}`]:[`$ ${e}`],i=ie(t,"output");i!=null&&s.push("",Ye(i));const r=ie(t,"exitCode");r!=null&&s.push("",`exit ${Ye(r)}`),Ge(t,"cancelled")===!0&&s.push("","cancelled"),Ge(t,"truncated")===!0&&s.push("","output truncated");const o=M(t,"fullOutputPath");return o!==void 0&&o!==""&&s.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:s.join(`
|
|
5
5
|
`)}]}}function uo(t){return t==="assistant"?"assistant":t==="user"?"user":t==="toolResult"?"tool":"system"}function fo(t,e){return typeof t=="string"?t!==""?[{type:"text",text:t}]:[]:Array.isArray(t)?t.flatMap(s=>{const i=M(s,"type"),r=M(s,"text");if(i==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(i==="thinking"){const o=M(s,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(i==="toolCall"){const o=M(s,"name")??"tool",n=ie(s,"arguments"),a=o==="read"?go(M(n,"path")):void 0;return a!==void 0?[{type:"skillRead",...a}]:[{type:"toolCall",toolName:o,summary:Zs(n)}]}return i==="image"?[{type:"text",text:"[image]"}]:bs(s)}).map(s=>s.type==="text"&&M(e,"role")==="toolResult"?{type:"toolResult",toolName:M(e,"toolName")??"tool",text:s.text,isError:Ge(e,"isError")===!0}:s):bs(t)}function go(t){if(t===void 0||t==="")return;const e=t.replace(/\\/g,"/");if(!e.endsWith("/SKILL.md")&&e!=="SKILL.md")return;const s=e.split("/").at(-2);if(!(s===void 0||s===""))return{name:s,path:t}}function bs(t){return t==null?[]:typeof t=="object"?[{type:"text",text:Zs(t)}]:[{type:"text",text:Ye(t)}]}function Zs(t){if(!Js(t))return Ye(t);const e=M(t,"command");if(e!==void 0)return e;const s=M(t,"path");if(s!==void 0)return s;if(typeof t.oldText=="string"&&typeof t.newText=="string")return"edit text replacement";const i=t.edits;return Array.isArray(i)?`${String(i.length)} edit${i.length===1?"":"s"}`:Object.entries(t).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${mo(n)}`).join(" · ")}function mo(t){return typeof t=="string"?t.length>80?`${t.slice(0,77)}…`:t:typeof t=="number"||typeof t=="boolean"?String(t):Array.isArray(t)?`${String(t.length)} item${t.length===1?"":"s"}`:typeof t=="object"&&t!==null?"object":""}function Js(t){return typeof t=="object"&&t!==null}function ie(t,e){return Js(t)?t[e]:void 0}function M(t,e){const s=ie(t,e);return typeof s=="string"?s:void 0}function Ge(t,e){const s=ie(t,e);return typeof s=="boolean"?s:void 0}function Ye(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):""}const bo="pi-web:chat-history:v2:",yo=1800*1e3;function ys(t){try{const e=sessionStorage.getItem(yt(t));if(e===null||e==="")return;const s=JSON.parse(e);if(!So(s))return;if(Date.now()-s.savedAt>yo){sessionStorage.removeItem(yt(t));return}return{messages:s.messages,start:s.start,total:s.total}}catch{return}}function wo(t,e){try{sessionStorage.setItem(yt(t),JSON.stringify({...e,savedAt:Date.now()}))}catch{}}function xo(t,e){if(t===void 0||ko(t,e))return e;const s=Math.min(t.start,e.start),i=Math.max(t.start+t.messages.length,e.start+e.messages.length),r=new Array(i-s);return ws(r,s,t),ws(r,s,e),vo(r)?e:{start:s,total:Math.max(t.total,e.total),messages:r}}function ko(t,e){return t.total>e.total&&t.start===0&&e.start===0&&e.messages.length===e.total}function vo(t){for(let e=0;e<t.length;e+=1)if(!(e in t)||t[e]===void 0)return!0;return!1}function ws(t,e,s){s.messages.forEach((i,r)=>{t[s.start-e+r]=i})}function yt(t){return`${bo}${t}`}function So(t){return typeof t=="object"&&t!==null&&"messages"in t&&"start"in t&&"total"in t&&"savedAt"in t&&Array.isArray(t.messages)&&typeof t.start=="number"&&typeof t.total=="number"&&typeof t.savedAt=="number"}function $o(t,e){return Q("bash",`${e===!0?`excluded from context
|
|
6
6
|
|
|
7
7
|
`:""}$ ${t}`)}function Po(t,e){const s=t.at(-1),i=s?.parts.at(-1);if(s?.role!=="bash"||i?.type!=="text")return[...t,Q("bash",e)];const r=Co(i.text)?"":`
|
|
@@ -16,7 +16,7 @@ ${r.join(`
|
|
|
16
16
|
`),s=t.lastIndexOf("$ ");return e>s}function xs(t,e){if(e.type==="message.append")return Ro(t,e.message);if(e.type==="assistant.delta")return so(t,"assistant",e.text);if(e.type==="assistant.thinking.delta")return io(t,e.text);if(e.type==="tool.start")return Ss(t,{role:"assistant",content:[{type:"toolCall",name:e.toolName,arguments:e.args}]});if(e.type==="tool.end")return Ss(t,{role:"toolResult",toolName:e.toolName,content:e.content??[{type:"text",text:e.text}],isError:e.isError});if(e.type==="shell.start")return[...t,$o(e.command,e.excludeFromContext)];if(e.type==="shell.chunk")return Po(t,e.chunk);if(e.type==="shell.end")return To(t,e);if(e.type==="command.output")return[...t,Q(e.level==="error"?"system":"tool",e.message)];if(e.type==="session.error")return[...t,Q("system",e.message)];if(e.type==="message.end")return e.message===void 0?void 0:Ao(t,e.message)}function Ao(t,e){const s=lt(e)[0];if(s===void 0)return;const i=Mo(t,s);if(i>=0)return[...t.slice(0,i),s,...t.slice(i+1)];const r=t.at(-1);return r?.role!==s.role?[...t,s]:s.role==="assistant"||Io(r,s)?[...t.slice(0,-1),s]:[...t,s]}function Mo(t,e){const s=Xe(e);if(s.length===0)return-1;for(let i=t.length-1;i>=0;i--){const r=t[i];if(r?.role!=="skill")continue;const o=Xe(r);if(Ys(o,s))return i}return-1}function Xe(t){return t===void 0?[]:t.parts.filter(e=>e.type==="skillRead")}function Ys(t,e){return t.length===e.length&&t.every((s,i)=>Eo(s,e[i]))}function Eo(t,e){return e===void 0?!1:ks(t.path)===ks(e.path)||t.name===e.name}function ks(t){return t.replace(/\\/g,"/")}function Io(t,e){return vs(t)===vs(e)}function vs(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
17
17
|
|
|
18
18
|
`)}function Ro(t,e){const s=lt(e);return s.length===0?t:[...t,...s]}function Ss(t,e){return lt(e).reduce(_o,t)}function _o(t,e){const s=t.at(-1);return e.role==="skill"&&Ys(Xe(s),Xe(e))?t:s?.role===e.role&&e.role!=="skill"?[...t.slice(0,-1),{...s,parts:[...s.parts,...e.parts]}]:[...t,e]}function Xs(t){const e=t.trimStart();return e.startsWith("!")?{kind:"shell",excludeFromContext:e.startsWith("!!")}:ei(t).startsWith("/")?{kind:"command"}:Lo(t)?{kind:"file"}:{kind:"normal"}}function Do(t){return Xs(t).kind==="shell"}function ei(t){const e=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
|
|
19
|
-
`))+1;return t.slice(e)}function Lo(t){const e=ei(t);if(e.startsWith("@"))return!0;const s=t.length-e.length;if(t.slice(0,s).endsWith("@ "))return!0;const i=t.lastIndexOf('"');if(i===-1)return!1;const r=t.slice(0,i);return r.endsWith("@")||r.endsWith("@ ")}class jo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1}connect(e,s,i){this.close(),this.sessionId=e,this.onEvent=s,this.onReconnect=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),si(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const e=Vr(this.sessionId);this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await ti(e);qo(s)&&this.onEvent?.(s)}}class Oo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(e,s){this.close(),this.onEvent=e,this.onOpen=s,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),si(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const e=Gr();this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await ti(e);Fo(s)&&this.onEvent?.(s)}}function qo(t){const e=Et(t);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(e)}function zo(t){const e=Et(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function Fo(t){const e=Et(t);return zo(t)||e==="terminal.created"||e==="terminal.exited"||e==="terminal.closed"}function Et(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function ti(t){try{return typeof t=="string"?JSON.parse(t):t instanceof Blob?JSON.parse(await t.text()):t instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(t)):void 0}catch{return}}function si(t){if(t!==void 0){if(t.onmessage=null,t.onerror=null,t.onclose=null,t.readyState===WebSocket.CONNECTING){t.onopen=()=>{t.close()};return}t.close()}}class Wo{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}}function No(t,e){const s=e?.targetSessionId;if(s!==void 0&&s!=="")return Uo(t,s);const i=e?.latestSessionId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t.find(r=>r.archived!==!0):t.find(r=>r.archived!==!0)}function Uo(t,e){return t.find(s=>s.id===e||s.id.startsWith(e))}function Bo(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function Ho(t,e,s){if(e!==s)return{type:"unchanged"};const i=t.find(r=>r.id!==s&&r.archived!==!0);return i===void 0?{type:"clear"}:{type:"select",session:i}}const Me=100;class Vo{constructor(e,s,i,r=new Wo){this.getState=e,this.setState=s,this.updateUrl=i,this.sessionSelection=r,this.socket=new jo,this.selectionSeq=0,this.pendingTranscriptEvents=[]}applyGlobalEvent(e){e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):this.applySessionName(e.sessionId,e.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}async startSession(){const e=this.getState().selectedWorkspace;if(e)try{const s=await y.startSession(e.path);this.setState({sessions:[s,...this.getState().sessions]}),await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}preferredSession(e,s,i){return No(s,{targetSessionId:i,latestSessionId:this.sessionSelection.latestSessionId(e)})}async selectSession(e,s){this.sessionSelection.rememberSession(e);const i=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=ys(e.id);this.setState({selectedSession:e,messages:me(r?.messages??[]),messagePageStart:r?.start??0,messagePageTotal:r?.total??0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id]});try{if(e.archived===!0){const u=await y.messages(e.id,{limit:Me});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const d=this.mergeAndCacheHistory(e.id,u,this.currentHistoryPage());this.setState({messages:me(d.messages),messagePageStart:d.start,messagePageTotal:d.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),s?.updateUrl!==!1&&this.updateUrl();return}const o=[];this.socket.connect(e.id,u=>o.push(u),()=>{this.refreshSelectedSession(e.id)});const[n,a]=await Promise.all([y.messages(e.id,{limit:Me}),y.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const l=this.mergeAndCacheHistory(e.id,n,this.currentHistoryPage()),c=a.isStreaming;this.catchupStreamSessionId=c?e.id:void 0,this.setState({messages:me(l.messages),messagePageStart:l.start,messagePageTotal:l.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:c,status:a,activity:this.getState().sessionActivities[e.id]}),this.applyStatus(a);for(const u of o)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),s?.updateUrl!==!1&&this.updateUrl()}catch(o){i===this.selectionSeq&&this.setState({error:String(o)})}}async loadEarlierMessages(){const e=this.getState(),s=e.selectedSession;if(!(!s||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const i=this.currentHistoryPage(),r=await y.messages(s.id,{before:e.messagePageStart,limit:Me});if(this.getState().selectedSession?.id!==s.id)return;const o=this.mergeAndCacheHistory(s.id,r,i);this.setState({messages:me(o.messages),messagePageStart:o.start,messagePageTotal:o.total})}catch(i){this.setState({error:String(i)})}finally{this.getState().selectedSession?.id===s.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,s){if(e.trim().startsWith("/"))return this.runCommand(e);if(Do(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await y.prompt(r.id,e,s)}catch(o){this.setState({error:String(o)})}}async runShell(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,Q("user",e)]});try{await y.shell(s.id,e)}catch(i){this.setState({messages:[...this.getState().messages,Q("system",String(i))],error:String(i)})}}}async runCommand(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,Q("user",e)]});try{this.applyCommandResult(await y.runCommand(s.id,e))}catch(i){this.setState({messages:[...this.getState().messages,Q("system",String(i))],error:String(i)})}}}async respondToCommand(e,s){const i=this.getState().selectedSession;if(i){this.setState({commandDialog:void 0});try{this.applyCommandResult(await y.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async archiveSession(e=this.getState().selectedSession){if(e)try{await y.archive(e.id);const s=this.getState(),i=Bo(s.sessions,e.id,new Date().toISOString()),r=Ho(i,s.selectedSession?.id,e.id);this.setState({sessions:i}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&(this.clearActiveSession(),this.updateUrl())}catch(s){this.setState({error:String(s)})}}async restoreSession(e=this.getState().selectedSession){if(e)try{await y.restore(e.id);const s={...e};delete s.archived,delete s.archivedAt,this.replaceSession(s),this.getState().selectedSession?.id===s.id&&await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await y.detachParent(e.id);const s={...e};delete s.parentSessionPath,this.replaceSession(s)}catch(s){this.setState({error:String(s)})}}async listModels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await y.models(e.id)).models}catch(s){return this.setState({error:String(s)}),[]}}async setModel(e,s){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await y.setModel(i.id,e,s))}catch(r){this.setState({error:String(r)})}}async cycleModel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await y.cycleModel(s.id,e))}catch(i){this.setState({error:String(i)})}}async listThinkingLevels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await y.thinkingLevels(e.id)).levels}catch(s){return this.setState({error:String(s)}),[]}}async setThinkingLevel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await y.setThinkingLevel(s.id,e))}catch(i){this.setState({error:String(i)})}}async cycleThinkingLevel(){const e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await y.cycleThinkingLevel(e.id))}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await y.abort(e.id)}catch(s){this.setState({error:String(s)})}}async refreshSelectedSession(e=this.getState().selectedSession?.id){const s=this.getState().selectedSession;if(!(e===void 0||s?.id!==e||s.archived===!0))try{this.flushPendingTranscriptEvents();const i=this.currentHistoryPage(),[r,o]=await Promise.all([y.messages(e,{limit:Me}),y.status(e)]);if(this.getState().selectedSession?.id!==e)return;const n=this.mergeAndCacheHistory(e,r,i);this.setState({messages:me(n.messages),messagePageStart:n.start,messagePageTotal:n.total,status:o,activity:this.getState().sessionActivities[e],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(i){this.getState().selectedSession?.id===e&&this.setState({error:String(i)})}}replaceSession(e){const s=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i=>i.id===e.id?e:i),selectedSession:s?.id===e.id?e:s})}mergeAndCacheHistory(e,s,i=ys(e)){const r=xo(i,s);return wo(e,r),r}currentHistoryPage(){const e=this.getState();if(!(e.messages.length===0&&e.messagePageTotal===0))return{messages:e.messages,start:e.messagePageStart,total:e.messagePageTotal}}applyCommandResult(e){if(e.type==="select"){this.setState({commandDialog:e});return}const s=(e.type==="unsupported",e.message);if(s!==void 0&&s!==""&&this.setState({messages:[...this.getState().messages,Q(e.type==="unsupported"?"system":"tool",s)]}),e.type==="done"&&e.session){const i=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(o=>o.id!==e.session?.id)];this.setState({sessions:r,selectedSession:i?.id===e.session.id?e.session:i}),i?.id!==e.session.id&&this.selectSession(e.session)}}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){this.setState({sessionStatuses:{...this.getState().sessionStatuses,[e.sessionId]:e},status:this.getState().selectedSession?.id===e.sessionId?e:this.getState().status}),this.catchupStreamSessionId===e.sessionId&&!e.isStreaming&&this.finishStreamCatchup(e.sessionId)}applySessionName(e,s){const i=o=>{if(o.id!==e)return o;const n={...o};return s===void 0||s===""?delete n.name:n.name=s,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i),selectedSession:r===void 0?void 0:i(r)})}applyEvent(e){const s=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===s){if(e.type==="message.end"||e.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Go(e))return}if(Ko(e)){this.queueTranscriptEvent(e);return}this.flushPendingTranscriptEvents();const i=xs(this.getState().messages,e);i?this.setState({messages:i}):e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):e.type==="session.name"&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let s=this.getState().messages;for(const i of e)s=xs(s,i)??s;s!==this.getState().messages&&this.setState({messages:s})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(e){this.catchupStreamSessionId===e&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===e&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(e))}async refreshMessages(e){try{const s=this.currentHistoryPage(),i=await y.messages(e,{limit:Me});if(this.getState().selectedSession?.id!==e)return;const r=this.mergeAndCacheHistory(e,i,s);this.setState({messages:me(r.messages),messagePageStart:r.start,messagePageTotal:r.total})}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function Go(t){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(t.type)}function Ko(t){return t.type==="assistant.delta"||t.type==="assistant.thinking.delta"||t.type==="shell.chunk"}class Qo{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}}function Zo(t,e){const s=e?.targetWorkspaceId;if(s!==void 0&&s!=="")return t.find(r=>r.id===s);const i=e?.latestWorkspaceId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t[0]:t[0]}class Jo{constructor(e,s,i,r,o=new Qo){this.getState=e,this.setState=s,this.updateUrl=i,this.sessions=r,this.workspaceSelection=o}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(e)}async selectProject(e,s){this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await y.workspaces(e.id);this.setState({workspaces:i});const r=Zo(i,{targetWorkspaceId:s?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(e.id)});r?await this.selectWorkspace(r,{sessionId:s?.sessionId,updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}async selectWorkspace(e,s){this.workspaceSelection.rememberWorkspace(e),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await y.sessions(e.path);this.setState({sessions:i});const r=this.sessions.preferredSession(e.path,i,s?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}}const Yo=1200;class Xo{constructor(){this.pendingTokens=[]}handle(e,s){const i=tn(e);if(i===void 0||!$s(i))return!1;const r=s.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:ii(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!$s(i)?[...this.pendingTokens,i]:[i],n=r.find(l=>rn(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>ri(l.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Yo)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function en(t){return ii(t).map(e=>e.split("+").map(s=>s==="mod"?Ps()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?Ps()?"⌥":"Alt":s==="ctrl"?"Ctrl":s==="enter"?"Enter":s==="escape"?"Esc":s==="."?".":s.length===1?s.toUpperCase():`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join("+")).join(" ")}function tn(t){if(t.isComposing)return;const e=sn(t.key);if(e===void 0)return;const s=[];return(t.metaKey||t.ctrlKey)&&s.push("mod"),t.altKey&&s.push("alt"),t.shiftKey&&s.push("shift"),s.push(e),s.join("+")}function ii(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function sn(t){if(t===" ")return"space";if(t.length===1)return t.toLowerCase();const e=t.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(e))return e}function rn(t,e){return t.length===e.length&&ri(t,e)}function ri(t,e){return e.every((s,i)=>t[i]===s)}function $s(t){return t.includes("+")}function Ps(){return navigator.userAgent.toLowerCase().includes("mac")}function on(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:t=>{t.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",group:"General",enabled:t=>t.state.selectedSession!==void 0,run:t=>{t.focusPrompt()}},{id:"project.add",title:"Add Project",group:"Project",run:t=>t.addProject()},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:t=>{t.selectMainView("chat")}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Ue,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:Ts,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Ue,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:Ts,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Ue,run:t=>t.state.workspaceTool==="core:workspace.git"&&t.state.selectedWorkspace?.isGitRepo===!0?t.refreshGit():t.refreshFiles()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Ue,run:t=>t.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&t.state.selectedSession.archived!==!0,run:t=>t.archiveSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&nn(t.state.status),run:t=>t.stopActiveWork()}]}function Ue(t){return t.state.selectedWorkspace!==void 0}function Ts(t){return t.state.selectedWorkspace?.isGitRepo===!0}function nn(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const an="modulepreload",ln=function(t){return"/"+t},Cs={},oi=function(e,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=l(s.map(c=>{if(c=ln(c),c in Cs)return;Cs[c]=!0;const u=c.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":an,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function cn(){return[{id:"workspace.files",title:"Files",order:10,render:dn},{id:"workspace.git",title:"Git",order:20,visible:t=>t.isGitRepo,render:fn},{id:"workspace.terminal",title:"Terminal",order:30,badge:t=>t.activeTerminalCount>0?t.activeTerminalCount:void 0,render:un}]}function dn(t){return p`
|
|
19
|
+
`))+1;return t.slice(e)}function Lo(t){const e=ei(t);if(e.startsWith("@"))return!0;const s=t.length-e.length;if(t.slice(0,s).endsWith("@ "))return!0;const i=t.lastIndexOf('"');if(i===-1)return!1;const r=t.slice(0,i);return r.endsWith("@")||r.endsWith("@ ")}class jo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1}connect(e,s,i){this.close(),this.sessionId=e,this.onEvent=s,this.onReconnect=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),si(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const e=Vr(this.sessionId);this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await ti(e);qo(s)&&this.onEvent?.(s)}}class Oo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1}connect(e,s){this.close(),this.onEvent=e,this.onOpen=s,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),si(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const e=Gr();this.socket=e,e.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},e.onmessage=s=>{this.handleMessage(s.data)},e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e){const s=await ti(e);zo(s)&&this.onEvent?.(s)}}function qo(t){const e=Et(t);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","pi.event"].includes(e)}function Fo(t){const e=Et(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function zo(t){const e=Et(t);return Fo(t)||e==="terminal.created"||e==="terminal.exited"||e==="terminal.closed"}function Et(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function ti(t){try{return typeof t=="string"?JSON.parse(t):t instanceof Blob?JSON.parse(await t.text()):t instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(t)):void 0}catch{return}}function si(t){if(t!==void 0){if(t.onmessage=null,t.onerror=null,t.onclose=null,t.readyState===WebSocket.CONNECTING){t.onopen=()=>{t.close()};return}t.close()}}class Wo{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}}function No(t,e){const s=e?.targetSessionId;if(s!==void 0&&s!=="")return Uo(t,s);const i=e?.latestSessionId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t.find(r=>r.archived!==!0):t.find(r=>r.archived!==!0)}function Uo(t,e){return t.find(s=>s.id===e||s.id.startsWith(e))}function Bo(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function Ho(t,e,s){if(e!==s)return{type:"unchanged"};const i=t.find(r=>r.id!==s&&r.archived!==!0);return i===void 0?{type:"clear"}:{type:"select",session:i}}const Me=100;class Vo{constructor(e,s,i,r=new Wo){this.getState=e,this.setState=s,this.updateUrl=i,this.sessionSelection=r,this.socket=new jo,this.selectionSeq=0,this.pendingTranscriptEvents=[]}applyGlobalEvent(e){e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):this.applySessionName(e.sessionId,e.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}async startSession(){const e=this.getState().selectedWorkspace;if(e)try{const s=await y.startSession(e.path);this.setState({sessions:[s,...this.getState().sessions]}),await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}preferredSession(e,s,i){return No(s,{targetSessionId:i,latestSessionId:this.sessionSelection.latestSessionId(e)})}async selectSession(e,s){this.sessionSelection.rememberSession(e);const i=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=ys(e.id);this.setState({selectedSession:e,messages:me(r?.messages??[]),messagePageStart:r?.start??0,messagePageTotal:r?.total??0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id]});try{if(e.archived===!0){const u=await y.messages(e.id,{limit:Me});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const d=this.mergeAndCacheHistory(e.id,u,this.currentHistoryPage());this.setState({messages:me(d.messages),messagePageStart:d.start,messagePageTotal:d.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),s?.updateUrl!==!1&&this.updateUrl();return}const o=[];this.socket.connect(e.id,u=>o.push(u),()=>{this.refreshSelectedSession(e.id)});const[n,a]=await Promise.all([y.messages(e.id,{limit:Me}),y.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const l=this.mergeAndCacheHistory(e.id,n,this.currentHistoryPage()),c=a.isStreaming;this.catchupStreamSessionId=c?e.id:void 0,this.setState({messages:me(l.messages),messagePageStart:l.start,messagePageTotal:l.total,isLoadingEarlierMessages:!1,isReceivingPartialStream:c,status:a,activity:this.getState().sessionActivities[e.id]}),this.applyStatus(a);for(const u of o)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),s?.updateUrl!==!1&&this.updateUrl()}catch(o){i===this.selectionSeq&&this.setState({error:String(o)})}}async loadEarlierMessages(){const e=this.getState(),s=e.selectedSession;if(!(!s||e.isLoadingEarlierMessages||e.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const i=this.currentHistoryPage(),r=await y.messages(s.id,{before:e.messagePageStart,limit:Me});if(this.getState().selectedSession?.id!==s.id)return;const o=this.mergeAndCacheHistory(s.id,r,i);this.setState({messages:me(o.messages),messagePageStart:o.start,messagePageTotal:o.total})}catch(i){this.setState({error:String(i)})}finally{this.getState().selectedSession?.id===s.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(e,s){if(e.trim().startsWith("/"))return this.runCommand(e);if(Do(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await y.prompt(r.id,e,s)}catch(o){this.setState({error:String(o)})}}async runShell(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,Q("user",e)]});try{await y.shell(s.id,e)}catch(i){this.setState({messages:[...this.getState().messages,Q("system",String(i))],error:String(i)})}}}async runCommand(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0)){this.setState({messages:[...this.getState().messages,Q("user",e)]});try{this.applyCommandResult(await y.runCommand(s.id,e))}catch(i){this.setState({messages:[...this.getState().messages,Q("system",String(i))],error:String(i)})}}}async respondToCommand(e,s){const i=this.getState().selectedSession;if(i){this.setState({commandDialog:void 0});try{this.applyCommandResult(await y.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}async archiveSession(e=this.getState().selectedSession){if(e)try{await y.archive(e.id);const s=this.getState(),i=Bo(s.sessions,e.id,new Date().toISOString()),r=Ho(i,s.selectedSession?.id,e.id);this.setState({sessions:i}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&(this.clearActiveSession(),this.updateUrl())}catch(s){this.setState({error:String(s)})}}async restoreSession(e=this.getState().selectedSession){if(e)try{await y.restore(e.id);const s={...e};delete s.archived,delete s.archivedAt,this.replaceSession(s),this.getState().selectedSession?.id===s.id&&await this.selectSession(s)}catch(s){this.setState({error:String(s)})}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath!==void 0)try{await y.detachParent(e.id);const s={...e};delete s.parentSessionPath,this.replaceSession(s)}catch(s){this.setState({error:String(s)})}}async listModels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await y.models(e.id)).models}catch(s){return this.setState({error:String(s)}),[]}}async setModel(e,s){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await y.setModel(i.id,e,s))}catch(r){this.setState({error:String(r)})}}async cycleModel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await y.cycleModel(s.id,e))}catch(i){this.setState({error:String(i)})}}async listThinkingLevels(){const e=this.getState().selectedSession;if(!e||e.archived===!0)return[];try{return(await y.thinkingLevels(e.id)).levels}catch(s){return this.setState({error:String(s)}),[]}}async setThinkingLevel(e){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await y.setThinkingLevel(s.id,e))}catch(i){this.setState({error:String(i)})}}async cycleThinkingLevel(){const e=this.getState().selectedSession;if(!(!e||e.archived===!0))try{this.applyStatus(await y.cycleThinkingLevel(e.id))}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await y.abort(e.id)}catch(s){this.setState({error:String(s)})}}async refreshSelectedSession(e=this.getState().selectedSession?.id){const s=this.getState().selectedSession;if(!(e===void 0||s?.id!==e||s.archived===!0))try{this.flushPendingTranscriptEvents();const i=this.currentHistoryPage(),[r,o]=await Promise.all([y.messages(e,{limit:Me}),y.status(e)]);if(this.getState().selectedSession?.id!==e)return;const n=this.mergeAndCacheHistory(e,r,i);this.setState({messages:me(n.messages),messagePageStart:n.start,messagePageTotal:n.total,status:o,activity:this.getState().sessionActivities[e],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(i){this.getState().selectedSession?.id===e&&this.setState({error:String(i)})}}replaceSession(e){const s=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i=>i.id===e.id?e:i),selectedSession:s?.id===e.id?e:s})}mergeAndCacheHistory(e,s,i=ys(e)){const r=xo(i,s);return wo(e,r),r}currentHistoryPage(){const e=this.getState();if(!(e.messages.length===0&&e.messagePageTotal===0))return{messages:e.messages,start:e.messagePageStart,total:e.messagePageTotal}}applyCommandResult(e){if(e.type==="select"){this.setState({commandDialog:e});return}const s=(e.type==="unsupported",e.message);if(s!==void 0&&s!==""&&this.setState({messages:[...this.getState().messages,Q(e.type==="unsupported"?"system":"tool",s)]}),e.type==="done"&&e.session){const i=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(o=>o.id!==e.session?.id)];this.setState({sessions:r,selectedSession:i?.id===e.session.id?e.session:i}),i?.id!==e.session.id&&this.selectSession(e.session)}}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){this.setState({sessionStatuses:{...this.getState().sessionStatuses,[e.sessionId]:e},status:this.getState().selectedSession?.id===e.sessionId?e:this.getState().status}),this.catchupStreamSessionId===e.sessionId&&!e.isStreaming&&this.finishStreamCatchup(e.sessionId)}applySessionName(e,s){const i=o=>{if(o.id!==e)return o;const n={...o};return s===void 0||s===""?delete n.name:n.name=s,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(i),selectedSession:r===void 0?void 0:i(r)})}applyEvent(e){const s=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===s){if(e.type==="message.end"||e.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Go(e))return}if(Ko(e)){this.queueTranscriptEvent(e);return}this.flushPendingTranscriptEvents();const i=xs(this.getState().messages,e);i?this.setState({messages:i}):e.type==="status.update"?this.applyStatus(e.status):e.type==="activity.update"?this.applyActivity(e.activity):e.type==="session.name"&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let s=this.getState().messages;for(const i of e)s=xs(s,i)??s;s!==this.getState().messages&&this.setState({messages:s})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(e){this.catchupStreamSessionId===e&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===e&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(e))}async refreshMessages(e){try{const s=this.currentHistoryPage(),i=await y.messages(e,{limit:Me});if(this.getState().selectedSession?.id!==e)return;const r=this.mergeAndCacheHistory(e,i,s);this.setState({messages:me(r.messages),messagePageStart:r.start,messagePageTotal:r.total})}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function Go(t){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(t.type)}function Ko(t){return t.type==="assistant.delta"||t.type==="assistant.thinking.delta"||t.type==="shell.chunk"}class Qo{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}}function Zo(t,e){const s=e?.targetWorkspaceId;if(s!==void 0&&s!=="")return t.find(r=>r.id===s);const i=e?.latestWorkspaceId;return i!==void 0&&i!==""?t.find(r=>r.id===i)??t[0]:t[0]}class Jo{constructor(e,s,i,r,o=new Qo){this.getState=e,this.setState=s,this.updateUrl=i,this.sessions=r,this.workspaceSelection=o}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){this.workspaceSelection.forgetProject(e)}async selectProject(e,s){this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,sessions:[],workspaces:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await y.workspaces(e.id);this.setState({workspaces:i});const r=Zo(i,{targetWorkspaceId:s?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(e.id)});r?await this.selectWorkspace(r,{sessionId:s?.sessionId,updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}async selectWorkspace(e,s){this.workspaceSelection.rememberWorkspace(e),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,error:""});try{const i=await y.sessions(e.path);this.setState({sessions:i});const r=this.sessions.preferredSession(e.path,i,s?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:s?.updateUrl}):s?.updateUrl!==!1&&this.updateUrl()}catch(i){this.setState({error:String(i)})}}}const Yo=1200;class Xo{constructor(){this.pendingTokens=[]}handle(e,s){const i=tn(e);if(i===void 0||!$s(i))return!1;const r=s.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:ii(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!$s(i)?[...this.pendingTokens,i]:[i],n=r.find(l=>rn(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>ri(l.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Yo)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function en(t){return ii(t).map(e=>e.split("+").map(s=>s==="mod"?Ps()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?Ps()?"⌥":"Alt":s==="ctrl"?"Ctrl":s==="enter"?"Enter":s==="escape"?"Esc":s==="."?".":s.length===1?s.toUpperCase():`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join("+")).join(" ")}function tn(t){if(t.isComposing)return;const e=sn(t.key);if(e===void 0)return;const s=[];return(t.metaKey||t.ctrlKey)&&s.push("mod"),t.altKey&&s.push("alt"),t.shiftKey&&s.push("shift"),s.push(e),s.join("+")}function ii(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function sn(t){if(t===" ")return"space";if(t.length===1)return t.toLowerCase();const e=t.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(e))return e}function rn(t,e){return t.length===e.length&&ri(t,e)}function ri(t,e){return e.every((s,i)=>t[i]===s)}function $s(t){return t.includes("+")}function Ps(){return navigator.userAgent.toLowerCase().includes("mac")}function on(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:t=>{t.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",group:"General",enabled:t=>t.state.selectedSession!==void 0,run:t=>{t.focusPrompt()}},{id:"project.add",title:"Add Project",group:"Project",run:t=>t.addProject()},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:t=>{t.selectMainView("chat")}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Ue,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:Ts,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Ue,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:Ts,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Ue,run:t=>t.state.workspaceTool==="core:workspace.git"&&t.state.selectedWorkspace?.isGitRepo===!0?t.refreshGit():t.refreshFiles()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Ue,run:t=>t.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&t.state.selectedSession.archived!==!0,run:t=>t.archiveSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:t=>t.state.selectedSession!==void 0&&nn(t.state.status),run:t=>t.stopActiveWork()}]}function Ue(t){return t.state.selectedWorkspace!==void 0}function Ts(t){return t.state.selectedWorkspace?.isGitRepo===!0}function nn(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const an="modulepreload",ln=function(t){return"/"+t},Cs={},oi=function(e,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=l(s.map(c=>{if(c=ln(c),c in Cs)return;Cs[c]=!0;const u=c.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":an,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function cn(){return[{id:"workspace.files",title:"Files",order:10,render:dn},{id:"workspace.git",title:"Git",order:20,visible:t=>t.isGitRepo,render:fn},{id:"workspace.terminal",title:"Terminal",order:30,badge:t=>t.activeTerminalCount>0?t.activeTerminalCount:void 0,render:un}]}function dn(t){return p`
|
|
20
20
|
<section class="toolbar">
|
|
21
21
|
<strong>Files</strong>
|
|
22
22
|
${t.fileTreeStale?p`<span class="stale">stale</span>`:null}
|
|
@@ -70,7 +70,7 @@ ${r.join(`
|
|
|
70
70
|
<div class="viewer-header"><strong>${t.path??"diff"}</strong><small>${t.staged?"staged":"unstaged"}${t.truncated?" · truncated":""}</small></div>
|
|
71
71
|
<code-viewer .content=${t.diff} .language=${"diff"}></code-viewer>
|
|
72
72
|
</section>
|
|
73
|
-
`}function ai(){oi(()=>import("./CodeViewer-
|
|
73
|
+
`}function ai(){oi(()=>import("./CodeViewer-CbO-Cu6v.js"),__vite__mapDeps([0,1,2,3]))}function bn(){oi(()=>import("./TerminalPanel-D4bhXEax.js"),__vite__mapDeps([4,5,6,1,2]))}function yn(t){const e=t.branch??"detached",s=t.ahead??0,i=t.behind??0;return s===0&&i===0?e:`${e} · ↑${String(s)} ↓${String(i)}`}function wn(t,e){return(e!=="unmodified"?e:t).slice(0,1).toUpperCase()}const xn={id:"core",name:"Pi Web Core",activate:()=>({actions:on(),workspacePanels:cn()})};async function kn(t="/pi-web-plugins/manifest.json"){window.piWebPluginApi={apiVersion:1,html:p};const e=await vn(t);if(e===void 0)return[];const s=[];for(const i of e.plugins)try{const r=new URL(i.module,new URL(t,window.location.href)).toString(),o=await import(r),n=$n(o,r);n!==void 0&&s.push(n)}catch(r){console.warn(`Failed to load Pi Web plugin ${i.module}`,r)}return s}async function vn(t){const e=await fetch(t,{cache:"no-store"});if(e.status!==404){if(!e.ok)throw new Error(`Failed to load plugin manifest: ${e.statusText}`);return Sn(await e.json())}}function Sn(t){if(!et(t)||!Array.isArray(t.plugins))throw new Error("Invalid plugin manifest");return{plugins:t.plugins.map(e=>{if(!et(e)||typeof e.module!="string"||e.module==="")throw new Error("Invalid plugin manifest entry");return{module:e.module}})}}function $n(t,e){if(!et(t))throw new Error(`Plugin module ${e} did not export an object`);const s=t.default;if(!Pn(s))throw new Error(`Plugin module ${e} default export is not a PiWebPlugin`);return s}function Pn(t){return et(t)&&typeof t.id=="string"&&typeof t.name=="string"&&typeof t.activate=="function"}function et(t){return typeof t=="object"&&t!==null}const Tn=/^[a-z][a-z0-9.-]*$/u,Cn=/^[a-z][a-z0-9.-]*$/u;class An{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabelContributions=[],this.pluginIds=new Set,this.contributionIds=new Set}register(e){if(this.validatePluginId(e.id),this.pluginIds.has(e.id))throw new Error(`Duplicate plugin id: ${e.id}`);this.pluginIds.add(e.id);const s=e.activate({apiVersion:1});for(const i of s.actions??[])this.actions.push(this.qualifyAction(e.id,i));for(const i of s.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(e.id,i));for(const i of s.workspaceLabelContributions??[])this.workspaceLabelContributions.push(this.qualifyWorkspaceLabelContribution(e.id,i))}getActions(e){return this.actions.map(s=>{const i=typeof s.enabled=="function"?s.enabled(e):s.enabled,r={id:s.id,pluginId:s.pluginId,localId:s.localId,title:s.title,run:()=>s.run(e)};return s.description!==void 0&&(r.description=s.description),s.shortcut!==void 0&&(r.shortcut=s.shortcut),s.group!==void 0&&(r.group=s.group),i!==void 0&&(r.enabled=i),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,s)=>(e.order??1e3)-(s.order??1e3)||e.title.localeCompare(s.title))}getWorkspaceLabelItems(e,s){const i={state:e,workspace:s};return[...this.workspaceLabelContributions].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>{if(r.visible?.(i)===!1)return[];const o=r.items(i);return o===void 0?[]:Array.isArray(o)?o:[o]})}qualifyAction(e,s){const i=this.qualify(e,s.id);return{...s,id:i,pluginId:e,localId:s.id}}qualifyWorkspacePanel(e,s){const i=this.qualify(e,s.id);return{...s,id:i,pluginId:e,localId:s.id}}qualifyWorkspaceLabelContribution(e,s){const i=this.qualify(e,s.id);return{...s,id:i,pluginId:e,localId:s.id}}qualify(e,s){this.validateLocalId(s);const i=`${e}:${s}`;if(this.contributionIds.has(i))throw new Error(`Duplicate contribution id: ${i}`);return this.contributionIds.add(i),i}validatePluginId(e){if(!Tn.test(e))throw new Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Cn.test(e))throw new Error(`Invalid contribution id: ${e}`)}}function Mn(){const t=new URLSearchParams(window.location.search);return{projectId:t.get("project")??void 0,workspaceId:t.get("workspace")??void 0,sessionId:t.get("session")??void 0,tool:In(t.get("tool")),view:Rn(t.get("view"))}}function En(t,e){const s=new URL(window.location.href);s.searchParams.delete("project"),s.searchParams.delete("workspace"),s.searchParams.delete("session"),s.searchParams.delete("tool"),s.searchParams.delete("view"),t.projectId!==void 0&&t.projectId!==""&&s.searchParams.set("project",t.projectId),t.workspaceId!==void 0&&t.workspaceId!==""&&s.searchParams.set("workspace",t.workspaceId),t.sessionId!==void 0&&t.sessionId!==""&&s.searchParams.set("session",t.sessionId),t.tool!==void 0&&s.searchParams.set("tool",t.tool),t.view!==void 0&&s.searchParams.set("view",t.view);const i=`${s.pathname}${s.search}${s.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==r&&(e?.replace===!0?window.history.replaceState({},"",s):window.history.pushState({},"",s))}function In(t){return t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":li(t)?t:void 0}function Rn(t){return t==="chat"?"chat":t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":li(t)?t:void 0}function li(t){return t!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(t)}const _n=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ci(t){return t.composedPath().some(e=>Dn(e,_n))}function Dn(t,e){if(typeof Element<"u"&&t instanceof Element)return t.matches(e);if(!("matches"in t))return!1;const{matches:s}=t;return typeof s=="function"&&s.call(t,e)===!0}function It(t,e){ci(t)||e()}function Rt(t,e){t.key!=="Enter"&&t.key!==" "||ci(t)||(t.preventDefault(),e())}const Ln=G`
|
|
74
74
|
:host { display: block; height: 100dvh; box-sizing: border-box; padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); color: #e6edf3; background: #0d1117; font: 14px system-ui, sans-serif; }
|
|
75
75
|
.shell { display: grid; grid-template-columns: 340px minmax(420px, 1fr) minmax(360px, 42vw); height: 100%; min-height: 0; }
|
|
76
76
|
aside { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid #30363d; overflow: hidden; }
|
|
@@ -277,7 +277,7 @@ ${r.join(`
|
|
|
277
277
|
table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
|
|
278
278
|
th, td { border: 1px solid #30363d; padding: 4px 8px; }
|
|
279
279
|
th { background: #161b22; }
|
|
280
|
-
`,
|
|
280
|
+
`,Fn=G`
|
|
281
281
|
:host { display: block; color: #8b949e; font: 12px system-ui, sans-serif; }
|
|
282
282
|
.bar { display: flex; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid #30363d; background: #0d1117; white-space: nowrap; overflow: hidden; }
|
|
283
283
|
span { overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -293,7 +293,7 @@ ${r.join(`
|
|
|
293
293
|
.activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
294
294
|
.muted { color: #6e7681; }
|
|
295
295
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
296
|
-
`,
|
|
296
|
+
`,zn=G`
|
|
297
297
|
:host { display: block; }
|
|
298
298
|
.menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid #30363d; border-radius: 8px; background: #161b22; box-shadow: 0 10px 30px #0008; }
|
|
299
299
|
button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid #30363d; border-radius: 0; background: transparent; color: #e6edf3; padding: 8px 10px; text-align: left; cursor: pointer; }
|
|
@@ -399,7 +399,7 @@ This only removes it from Pi Web; it will not change the project folder.`)&&this
|
|
|
399
399
|
<span class="workspace-label-base" title=${s??t}>${t}</span>
|
|
400
400
|
${pi(e)}
|
|
401
401
|
</span>
|
|
402
|
-
`}function pi(t=[]){return t.map(e=>p`<span class="workspace-label-separator">·</span>${Vn(e)}`)}function Vn(t){if(t.type==="render")return p`<span class="workspace-label-render">${t.render()}</span>`;if(t.type==="link"&&Gn(t.href)){const e=t.target??"_blank",s=e==="_blank"?"noopener noreferrer":void 0;return p`<a class="workspace-label-item workspace-label-link" href=${t.href} title=${t.title??t.text} target=${e} rel=${s??void 0}>${t.text}</a>`}return p`<span class="workspace-label-item" title=${t.title??t.text}>${t.text}</span>`}function Gn(t){const e=t.trim().toLowerCase();return e!==""&&!e.startsWith("javascript:")&&!e.startsWith("data:")}var Kn=Object.defineProperty,Qn=Object.getOwnPropertyDescriptor,
|
|
402
|
+
`}function pi(t=[]){return t.map(e=>p`<span class="workspace-label-separator">·</span>${Vn(e)}`)}function Vn(t){if(t.type==="render")return p`<span class="workspace-label-render">${t.render()}</span>`;if(t.type==="link"&&Gn(t.href)){const e=t.target??"_blank",s=e==="_blank"?"noopener noreferrer":void 0;return p`<a class="workspace-label-item workspace-label-link" href=${t.href} title=${t.title??t.text} target=${e} rel=${s??void 0}>${t.text}</a>`}return p`<span class="workspace-label-item" title=${t.title??t.text}>${t.text}</span>`}function Gn(t){const e=t.trim().toLowerCase();return e!==""&&!e.startsWith("javascript:")&&!e.startsWith("data:")}var Kn=Object.defineProperty,Qn=Object.getOwnPropertyDescriptor,Fe=(t,e,s,i)=>{for(var r=i>1?void 0:i?Qn(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Kn(e,s,r),r};let ce=class extends _{constructor(){super(...arguments),this.workspaces=[],this.workspaceLabelItems=()=>[]}updated(t){(t.has("selected")||t.has("workspaces"))&&this.scrollSelectedIntoView()}render(){return p`
|
|
403
403
|
<section>
|
|
404
404
|
<h2>Workspaces</h2>
|
|
405
405
|
${this.workspaces.map(t=>{const e=`${t.label}${t.isMain?" · main":""}`;return p`
|
|
@@ -420,7 +420,7 @@ This only removes it from Pi Web; it will not change the project folder.`)&&this
|
|
|
420
420
|
</div>
|
|
421
421
|
`})}
|
|
422
422
|
</section>
|
|
423
|
-
`}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};ce.styles=_t;
|
|
423
|
+
`}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};ce.styles=_t;Fe([h({attribute:!1})],ce.prototype,"workspaces",2);Fe([h({attribute:!1})],ce.prototype,"selected",2);Fe([h({attribute:!1})],ce.prototype,"workspaceLabelItems",2);Fe([h({attribute:!1})],ce.prototype,"onSelect",2);ce=Fe([W("workspace-list")],ce);var Zn=Object.defineProperty,Jn=Object.getOwnPropertyDescriptor,q=(t,e,s,i)=>{for(var r=i>1?void 0:i?Jn(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Zn(e,s,r),r};function Yn(t){return t.name!==void 0&&t.name!==""?t.name:t.firstMessage!==""?t.firstMessage:t.id.slice(0,8)}let j=class extends _{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=t=>{t.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(t){if(t.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),t.has("sessions")&&!this.sessions.some(e=>e.archived===!0)&&(this.archivedExpanded=!1),this.selected?.archived===!0&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(t.has("selected")||t.has("sessions"))&&this.scrollSelectedIntoView()}render(){const t=Xn(this.sessions),e=new Set(t.map(i=>i.session.id)),s=hi(this.sessions.filter(i=>i.archived===!0&&!e.has(i.id)));return p`
|
|
424
424
|
<section>
|
|
425
425
|
<h2>Sessions <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>
|
|
426
426
|
${t.map(i=>this.renderSession(i))}
|
|
@@ -451,8 +451,8 @@ This only removes it from Pi Web; it will not change the project folder.`)&&this
|
|
|
451
451
|
`:null}
|
|
452
452
|
</div>
|
|
453
453
|
</div>
|
|
454
|
-
`}toggleMenu(t,e){if(this.openMenuSessionId===t){this.openMenuSessionId=void 0;return}if(e instanceof HTMLElement){const s=e.getBoundingClientRect();this.menuStyle=`top: ${String(s.bottom+4)}px; right: ${String(window.innerWidth-s.right)}px;`}this.openMenuSessionId=t}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0)}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(t){if(t.archived===!0)return"read-only · ";const e=this.statuses[t.id],s=this.activities[t.id];return s?.phase==="active"?`● ${s.label} · `:e===void 0?"":e.isStreaming?"● streaming · ":e.isBashRunning?"● bash · ":e.isCompacting?"● compacting · ":e.pendingMessageCount>0?`● ${String(e.pendingMessageCount)} pending · `:""}};j.styles=_t;q([h({attribute:!1})],j.prototype,"sessions",2);q([h({attribute:!1})],j.prototype,"statuses",2);q([h({attribute:!1})],j.prototype,"activities",2);q([h({attribute:!1})],j.prototype,"selected",2);q([h({type:Boolean})],j.prototype,"canStart",2);q([h({attribute:!1})],j.prototype,"onSelect",2);q([h({attribute:!1})],j.prototype,"onStart",2);q([$()],j.prototype,"openMenuSessionId",2);q([$()],j.prototype,"menuStyle",2);q([$()],j.prototype,"archivedExpanded",2);q([h({attribute:!1})],j.prototype,"onArchive",2);q([h({attribute:!1})],j.prototype,"onRestore",2);q([h({attribute:!1})],j.prototype,"onDetachParent",2);j=q([W("session-list")],j);function Xn(t){const e=new Map(t.map(i=>[i.path,i])),s=new Set;for(const i of t){if(i.archived===!0)continue;s.add(i.id);let r=i.parentSessionPath;const o=new Set([i.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=e.get(r);if(n===void 0)break;s.add(n.id),r=n.parentSessionPath}}return hi(t.filter(i=>s.has(i.id)))}function hi(t){const e=new Map(t.map(n=>[n.path,n])),s=new Map,i=[];for(const n of t){const a=n.parentSessionPath,l=a===void 0?void 0:e.get(a);if(l===void 0){i.push(n);continue}const c=s.get(l.path)??[];c.push(n),s.set(l.path,c)}const r=[],o=(n,a,l)=>{if(l.has(n.path))return;const c=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:c!==void 0&&!e.has(c)});const u=new Set(l);u.add(n.path);for(const d of s.get(n.path)??[])o(d,a+1,u)};for(const n of i)o(n,0,new Set);return r}const Dt={CHILD:2,ELEMENT:6},Lt=t=>(...e)=>({_$litDirective$:t,values:e});let jt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,s,i){this._$Ct=e,this._$AM=s,this._$Ci=i}_$AS(e,s){return this.update(e,s)}update(e,s){return this.render(...s)}};const{I:ea}=or,As=t=>t,Ms=()=>document.createComment(""),Ee=(t,e,s)=>{const i=t._$AA.parentNode,r=e===void 0?t._$AB:e._$AA;if(s===void 0){const o=i.insertBefore(Ms(),r),n=i.insertBefore(Ms(),r);s=new ea(o,n,t,t.options)}else{const o=s._$AB.nextSibling,n=s._$AM,a=n!==t;if(a){let l;s._$AQ?.(t),s._$AM=t,s._$AP!==void 0&&(l=t._$AU)!==n._$AU&&s._$AP(l)}if(o!==r||a){let l=s._$AA;for(;l!==o;){const c=As(l).nextSibling;As(i).insertBefore(l,r),l=c}}}return s},oe=(t,e,s=t)=>(t._$AI(e,s),t),ta={},sa=(t,e=ta)=>t._$AH=e,ia=t=>t._$AH,mt=t=>{t._$AR(),t._$AA.remove()};const Es=(t,e,s)=>{const i=new Map;for(let r=e;r<=s;r++)i.set(t[r],r);return i},ra=Lt(class extends jt{constructor(t){if(super(t),t.type!==Dt.CHILD)throw Error("repeat() can only be used in text expressions")}dt(t,e,s){let i;s===void 0?s=e:e!==void 0&&(i=e);const r=[],o=[];let n=0;for(const a of t)r[n]=i?i(a,n):n,o[n]=s(a,n),n++;return{values:o,keys:r}}render(t,e,s){return this.dt(t,e,s).values}update(t,[e,s,i]){const r=ia(t),{values:o,keys:n}=this.dt(e,s,i);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],l=[];let c,u,d=0,f=r.length-1,g=0,m=o.length-1;for(;d<=f&&g<=m;)if(r[d]===null)d++;else if(r[f]===null)f--;else if(a[d]===n[g])l[g]=oe(r[d],o[g]),d++,g++;else if(a[f]===n[m])l[m]=oe(r[f],o[m]),f--,m--;else if(a[d]===n[m])l[m]=oe(r[d],o[m]),Ee(t,l[m+1],r[d]),d++,m--;else if(a[f]===n[g])l[g]=oe(r[f],o[g]),Ee(t,r[d],r[f]),f--,g++;else if(c===void 0&&(c=Es(n,g,m),u=Es(a,d,f)),c.has(a[d]))if(c.has(a[f])){const A=u.get(n[g]),ge=A!==void 0?r[A]:null;if(ge===null){const $e=Ee(t,r[d]);oe($e,o[g]),l[g]=$e}else l[g]=oe(ge,o[g]),Ee(t,r[d],ge),r[A]=null;g++}else mt(r[f]),f--;else mt(r[d]),d++;for(;g<=m;){const A=Ee(t,l[m+1]);oe(A,o[g]),l[g++]=A}for(;d<=f;){const A=r[d++];A!==null&&mt(A)}return this.ut=n,sa(t,l),se}});function oa(t,e=0){const s=[];let i=[],r=0;const o=(a,l)=>{i.length||(r=l),i.push(a)},n=()=>{i.length&&(s.push({kind:"group",messages:i,startIndex:r,endIndex:r+i.length-1}),i=[])};return t.forEach((a,l)=>{const c=a.parts.filter(g=>Is(a,g)),u=a.parts.filter(g=>!Is(a,g)),d=e+l,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...f},d),c.length){n();const g=c.every(m=>m.type==="skillRead")?"skill":a.role;s.push({kind:"message",message:{role:g,parts:c,...f},index:d})}}),n(),s}function na(t){if(t.every(i=>i.source==="compaction"))return`${String(t.length)} history compaction ${t.length===1?"summary":"summaries"}`;if(t.every(i=>i.source==="branch_summary"))return`${String(t.length)} branch ${t.length===1?"summary":"summaries"}`;const e=t.reduce((i,r)=>(i[r.role]=(i[r.role]??0)+1,i),{}),s=Object.entries(e).map(([i,r])=>`${String(r)} ${i}`).join(" · ");return`${String(t.length)} ${t.length===1?"event":"events"}${s!==""?` · ${s}`:""}`}function Is(t,e){return t.source==="compaction"||t.source==="branch_summary"?!1:e.type==="skillInvocation"||e.type==="skillRead"?!0:e.type==="text"&&(t.role==="user"||t.role==="assistant"||t.role==="system"||t.role==="bash")}const aa=30;function la(t,e){const s=da(ua(t,e)),i={distanceFromBottom:t.scrollHeight-t.scrollTop};return s===void 0?i:{...i,markerId:s.id,markerOffset:s.offset}}function ca(t,e,s){if(s!==void 0&&e.markerOffset!==void 0){const i=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=pa(i,e.markerOffset);return}t.scrollTop=ha(t.scrollHeight,e.distanceFromBottom)}function da(t){let e,s=Number.NEGATIVE_INFINITY,i,r=Number.POSITIVE_INFINITY;for(const o of t)o.offset<=0&&o.offset>=s?(e=o,s=o.offset):o.offset>0&&o.offset<r&&(i=o,r=o.offset);return e??i}function pa(t,e){return t-e}function ha(t,e){return Math.max(0,t-e)}function ua(t,e){const s=t.getBoundingClientRect().top;return e.flatMap(i=>{const r=i.dataset.markerId;return r===void 0?[]:[{id:r,offset:i.getBoundingClientRect().top-s}]})}const fa=600,ga=1;function ma(t){return!t.hasMore||t.loadingMore||!t.canRequest||t.clientHeight<=0?!1:ba(t)||ya(t)}function ba(t){return t.scrollTop<(t.topThreshold??Math.max(fa,t.clientHeight))}function ya(t){return t.scrollHeight<=t.clientHeight+ga}class wt extends jt{constructor(e){if(super(e),this.it=C,e.type!==Dt.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===C||e==null)return this._t=void 0,this.it=e;if(e===se)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const s=[e];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}wt.directiveName="unsafeHTML",wt.resultType=1;const wa=Lt(wt);function Ot(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ue=Ot();function ui(t){ue=t}var ne={exec:()=>null};function w(t,e=""){let s=typeof t=="string"?t:t.source,i={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(L.caret,"$1"),s=s.replace(r,n),i},getRegex:()=>new RegExp(s,e)};return i}var xa=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),L={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},ka=/^(?:[ \t]*(?:\n|$))+/,va=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sa=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Fe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,$a=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,qt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,gi=w(fi).replace(/bull/g,qt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Pa=w(fi).replace(/bull/g,qt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),zt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ta=/^[^\n]+/,Ft=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ca=w(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ft).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Aa=w(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,qt).getRegex(),ct="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Wt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ma=w("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Wt).replace("tag",ct).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mi=w(zt).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex(),Ea=w(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mi).getRegex(),Nt={blockquote:Ea,code:va,def:Ca,fences:Sa,heading:$a,hr:Fe,html:Ma,lheading:gi,list:Aa,newline:ka,paragraph:mi,table:ne,text:Ta},Rs=w("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex(),Ia={...Nt,lheading:Pa,table:Rs,paragraph:w(zt).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Rs).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex()},Ra={...Nt,html:w(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Wt).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ne,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:w(zt).replace("hr",Fe).replace("heading",` *#{1,6} *[^
|
|
455
|
-
]`).replace("lheading",gi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_a=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Da=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,bi=/^( {2,}|\\)\n(?!\s*$)/,La=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Se=/[\p{P}\p{S}]/u,dt=/[\s\p{P}\p{S}]/u,Ut=/[^\s\p{P}\p{S}]/u,ja=w(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,dt).getRegex(),yi=/(?!~)[\p{P}\p{S}]/u,Oa=/(?!~)[\s\p{P}\p{S}]/u,qa=/(?:[^\s\p{P}\p{S}]|~)/u,
|
|
454
|
+
`}toggleMenu(t,e){if(this.openMenuSessionId===t){this.openMenuSessionId=void 0;return}if(e instanceof HTMLElement){const s=e.getBoundingClientRect();this.menuStyle=`top: ${String(s.bottom+4)}px; right: ${String(window.innerWidth-s.right)}px;`}this.openMenuSessionId=t}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0)}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(t){if(t.archived===!0)return"read-only · ";const e=this.statuses[t.id],s=this.activities[t.id];return s?.phase==="active"?`● ${s.label} · `:e===void 0?"":e.isStreaming?"● streaming · ":e.isBashRunning?"● bash · ":e.isCompacting?"● compacting · ":e.pendingMessageCount>0?`● ${String(e.pendingMessageCount)} pending · `:""}};j.styles=_t;q([h({attribute:!1})],j.prototype,"sessions",2);q([h({attribute:!1})],j.prototype,"statuses",2);q([h({attribute:!1})],j.prototype,"activities",2);q([h({attribute:!1})],j.prototype,"selected",2);q([h({type:Boolean})],j.prototype,"canStart",2);q([h({attribute:!1})],j.prototype,"onSelect",2);q([h({attribute:!1})],j.prototype,"onStart",2);q([$()],j.prototype,"openMenuSessionId",2);q([$()],j.prototype,"menuStyle",2);q([$()],j.prototype,"archivedExpanded",2);q([h({attribute:!1})],j.prototype,"onArchive",2);q([h({attribute:!1})],j.prototype,"onRestore",2);q([h({attribute:!1})],j.prototype,"onDetachParent",2);j=q([W("session-list")],j);function Xn(t){const e=new Map(t.map(i=>[i.path,i])),s=new Set;for(const i of t){if(i.archived===!0)continue;s.add(i.id);let r=i.parentSessionPath;const o=new Set([i.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=e.get(r);if(n===void 0)break;s.add(n.id),r=n.parentSessionPath}}return hi(t.filter(i=>s.has(i.id)))}function hi(t){const e=new Map(t.map(n=>[n.path,n])),s=new Map,i=[];for(const n of t){const a=n.parentSessionPath,l=a===void 0?void 0:e.get(a);if(l===void 0){i.push(n);continue}const c=s.get(l.path)??[];c.push(n),s.set(l.path,c)}const r=[],o=(n,a,l)=>{if(l.has(n.path))return;const c=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:c!==void 0&&!e.has(c)});const u=new Set(l);u.add(n.path);for(const d of s.get(n.path)??[])o(d,a+1,u)};for(const n of i)o(n,0,new Set);return r}const Dt={CHILD:2,ELEMENT:6},Lt=t=>(...e)=>({_$litDirective$:t,values:e});let jt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,s,i){this._$Ct=e,this._$AM=s,this._$Ci=i}_$AS(e,s){return this.update(e,s)}update(e,s){return this.render(...s)}};const{I:ea}=or,As=t=>t,Ms=()=>document.createComment(""),Ee=(t,e,s)=>{const i=t._$AA.parentNode,r=e===void 0?t._$AB:e._$AA;if(s===void 0){const o=i.insertBefore(Ms(),r),n=i.insertBefore(Ms(),r);s=new ea(o,n,t,t.options)}else{const o=s._$AB.nextSibling,n=s._$AM,a=n!==t;if(a){let l;s._$AQ?.(t),s._$AM=t,s._$AP!==void 0&&(l=t._$AU)!==n._$AU&&s._$AP(l)}if(o!==r||a){let l=s._$AA;for(;l!==o;){const c=As(l).nextSibling;As(i).insertBefore(l,r),l=c}}}return s},oe=(t,e,s=t)=>(t._$AI(e,s),t),ta={},sa=(t,e=ta)=>t._$AH=e,ia=t=>t._$AH,mt=t=>{t._$AR(),t._$AA.remove()};const Es=(t,e,s)=>{const i=new Map;for(let r=e;r<=s;r++)i.set(t[r],r);return i},ra=Lt(class extends jt{constructor(t){if(super(t),t.type!==Dt.CHILD)throw Error("repeat() can only be used in text expressions")}dt(t,e,s){let i;s===void 0?s=e:e!==void 0&&(i=e);const r=[],o=[];let n=0;for(const a of t)r[n]=i?i(a,n):n,o[n]=s(a,n),n++;return{values:o,keys:r}}render(t,e,s){return this.dt(t,e,s).values}update(t,[e,s,i]){const r=ia(t),{values:o,keys:n}=this.dt(e,s,i);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],l=[];let c,u,d=0,f=r.length-1,g=0,m=o.length-1;for(;d<=f&&g<=m;)if(r[d]===null)d++;else if(r[f]===null)f--;else if(a[d]===n[g])l[g]=oe(r[d],o[g]),d++,g++;else if(a[f]===n[m])l[m]=oe(r[f],o[m]),f--,m--;else if(a[d]===n[m])l[m]=oe(r[d],o[m]),Ee(t,l[m+1],r[d]),d++,m--;else if(a[f]===n[g])l[g]=oe(r[f],o[g]),Ee(t,r[d],r[f]),f--,g++;else if(c===void 0&&(c=Es(n,g,m),u=Es(a,d,f)),c.has(a[d]))if(c.has(a[f])){const A=u.get(n[g]),ge=A!==void 0?r[A]:null;if(ge===null){const $e=Ee(t,r[d]);oe($e,o[g]),l[g]=$e}else l[g]=oe(ge,o[g]),Ee(t,r[d],ge),r[A]=null;g++}else mt(r[f]),f--;else mt(r[d]),d++;for(;g<=m;){const A=Ee(t,l[m+1]);oe(A,o[g]),l[g++]=A}for(;d<=f;){const A=r[d++];A!==null&&mt(A)}return this.ut=n,sa(t,l),se}});function oa(t,e=0){const s=[];let i=[],r=0;const o=(a,l)=>{i.length||(r=l),i.push(a)},n=()=>{i.length&&(s.push({kind:"group",messages:i,startIndex:r,endIndex:r+i.length-1}),i=[])};return t.forEach((a,l)=>{const c=a.parts.filter(g=>Is(a,g)),u=a.parts.filter(g=>!Is(a,g)),d=e+l,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...f},d),c.length){n();const g=c.every(m=>m.type==="skillRead")?"skill":a.role;s.push({kind:"message",message:{role:g,parts:c,...f},index:d})}}),n(),s}function na(t){if(t.every(i=>i.source==="compaction"))return`${String(t.length)} history compaction ${t.length===1?"summary":"summaries"}`;if(t.every(i=>i.source==="branch_summary"))return`${String(t.length)} branch ${t.length===1?"summary":"summaries"}`;const e=t.reduce((i,r)=>(i[r.role]=(i[r.role]??0)+1,i),{}),s=Object.entries(e).map(([i,r])=>`${String(r)} ${i}`).join(" · ");return`${String(t.length)} ${t.length===1?"event":"events"}${s!==""?` · ${s}`:""}`}function Is(t,e){return t.source==="compaction"||t.source==="branch_summary"?!1:e.type==="skillInvocation"||e.type==="skillRead"?!0:e.type==="text"&&(t.role==="user"||t.role==="assistant"||t.role==="system"||t.role==="bash")}const aa=30;function la(t,e){const s=da(ua(t,e)),i={distanceFromBottom:t.scrollHeight-t.scrollTop};return s===void 0?i:{...i,markerId:s.id,markerOffset:s.offset}}function ca(t,e,s){if(s!==void 0&&e.markerOffset!==void 0){const i=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=pa(i,e.markerOffset);return}t.scrollTop=ha(t.scrollHeight,e.distanceFromBottom)}function da(t){let e,s=Number.NEGATIVE_INFINITY,i,r=Number.POSITIVE_INFINITY;for(const o of t)o.offset<=0&&o.offset>=s?(e=o,s=o.offset):o.offset>0&&o.offset<r&&(i=o,r=o.offset);return e??i}function pa(t,e){return t-e}function ha(t,e){return Math.max(0,t-e)}function ua(t,e){const s=t.getBoundingClientRect().top;return e.flatMap(i=>{const r=i.dataset.markerId;return r===void 0?[]:[{id:r,offset:i.getBoundingClientRect().top-s}]})}const fa=600,ga=1;function ma(t){return!t.hasMore||t.loadingMore||!t.canRequest||t.clientHeight<=0?!1:ba(t)||ya(t)}function ba(t){return t.scrollTop<(t.topThreshold??Math.max(fa,t.clientHeight))}function ya(t){return t.scrollHeight<=t.clientHeight+ga}class wt extends jt{constructor(e){if(super(e),this.it=C,e.type!==Dt.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===C||e==null)return this._t=void 0,this.it=e;if(e===se)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const s=[e];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}wt.directiveName="unsafeHTML",wt.resultType=1;const wa=Lt(wt);function Ot(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ue=Ot();function ui(t){ue=t}var ne={exec:()=>null};function w(t,e=""){let s=typeof t=="string"?t:t.source,i={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(L.caret,"$1"),s=s.replace(r,n),i},getRegex:()=>new RegExp(s,e)};return i}var xa=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),L={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},ka=/^(?:[ \t]*(?:\n|$))+/,va=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sa=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ze=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,$a=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,qt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,gi=w(fi).replace(/bull/g,qt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Pa=w(fi).replace(/bull/g,qt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ft=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ta=/^[^\n]+/,zt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ca=w(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",zt).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Aa=w(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,qt).getRegex(),ct="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Wt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ma=w("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Wt).replace("tag",ct).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mi=w(Ft).replace("hr",ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex(),Ea=w(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mi).getRegex(),Nt={blockquote:Ea,code:va,def:Ca,fences:Sa,heading:$a,hr:ze,html:Ma,lheading:gi,list:Aa,newline:ka,paragraph:mi,table:ne,text:Ta},Rs=w("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex(),Ia={...Nt,lheading:Pa,table:Rs,paragraph:w(Ft).replace("hr",ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Rs).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ct).getRegex()},Ra={...Nt,html:w(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Wt).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ne,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:w(Ft).replace("hr",ze).replace("heading",` *#{1,6} *[^
|
|
455
|
+
]`).replace("lheading",gi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_a=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Da=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,bi=/^( {2,}|\\)\n(?!\s*$)/,La=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Se=/[\p{P}\p{S}]/u,dt=/[\s\p{P}\p{S}]/u,Ut=/[^\s\p{P}\p{S}]/u,ja=w(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,dt).getRegex(),yi=/(?!~)[\p{P}\p{S}]/u,Oa=/(?!~)[\s\p{P}\p{S}]/u,qa=/(?:[^\s\p{P}\p{S}]|~)/u,Fa=w(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",xa?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),wi=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,za=w(wi,"u").replace(/punct/g,Se).getRegex(),Wa=w(wi,"u").replace(/punct/g,yi).getRegex(),xi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Na=w(xi,"gu").replace(/notPunctSpace/g,Ut).replace(/punctSpace/g,dt).replace(/punct/g,Se).getRegex(),Ua=w(xi,"gu").replace(/notPunctSpace/g,qa).replace(/punctSpace/g,Oa).replace(/punct/g,yi).getRegex(),Ba=w("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ut).replace(/punctSpace/g,dt).replace(/punct/g,Se).getRegex(),Ha=w(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Se).getRegex(),Va="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ga=w(Va,"gu").replace(/notPunctSpace/g,Ut).replace(/punctSpace/g,dt).replace(/punct/g,Se).getRegex(),Ka=w(/\\(punct)/,"gu").replace(/punct/g,Se).getRegex(),Qa=w(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Za=w(Wt).replace("(?:-->|$)","-->").getRegex(),Ja=w("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Za).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),tt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ya=w(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",tt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ki=w(/^!?\[(label)\]\[(ref)\]/).replace("label",tt).replace("ref",zt).getRegex(),vi=w(/^!?\[(ref)\](?:\[\])?/).replace("ref",zt).getRegex(),Xa=w("reflink|nolink(?!\\()","g").replace("reflink",ki).replace("nolink",vi).getRegex(),_s=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Bt={_backpedal:ne,anyPunctuation:Ka,autolink:Qa,blockSkip:Fa,br:bi,code:Da,del:ne,delLDelim:ne,delRDelim:ne,emStrongLDelim:za,emStrongRDelimAst:Na,emStrongRDelimUnd:Ba,escape:_a,link:Ya,nolink:vi,punctuation:ja,reflink:ki,reflinkSearch:Xa,tag:Ja,text:La,url:ne},el={...Bt,link:w(/^!?\[(label)\]\((.*?)\)/).replace("label",tt).getRegex(),reflink:w(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",tt).getRegex()},xt={...Bt,emStrongRDelimAst:Ua,emStrongLDelim:Wa,delLDelim:Ha,delRDelim:Ga,url:w(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",_s).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:w(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",_s).getRegex()},tl={...xt,br:w(bi).replace("{2,}","*").getRegex(),text:w(xt.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Be={normal:Nt,gfm:Ia,pedantic:Ra},Ie={normal:Bt,gfm:xt,breaks:tl,pedantic:el},sl={"&":"&","<":"<",">":">",'"':""","'":"'"},Ds=t=>sl[t];function K(t,e){if(e){if(L.escapeTest.test(t))return t.replace(L.escapeReplace,Ds)}else if(L.escapeTestNoEncode.test(t))return t.replace(L.escapeReplaceNoEncode,Ds);return t}function Ls(t){try{t=encodeURI(t).replace(L.percentDecode,"%")}catch{return null}return t}function js(t,e){let s=t.replace(L.findPipe,(o,n,a)=>{let l=!1,c=n;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),i=s.split(L.splitPipe),r=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;r<i.length;r++)i[r]=i[r].trim().replace(L.slashPipe,"|");return i}function ee(t,e,s){let i=t.length;if(i===0)return"";let r=0;for(;r<i&&t.charAt(i-r-1)===e;)r++;return t.slice(0,i-r)}function Os(t){let e=t.split(`
|
|
456
456
|
`),s=e.length-1;for(;s>=0&&L.blankLine.test(e[s]);)s--;return e.length-s<=2?t:e.slice(0,s+1).join(`
|
|
457
457
|
`)}function il(t,e){if(t.indexOf(e[1])===-1)return-1;let s=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])s++;else if(t[i]===e[1]&&(s--,s<0))return i;return s>0?-2:-1}function rl(t,e=0){let s=e,i="";for(let r of t)if(r===" "){let o=4-s%4;i+=" ".repeat(o),s+=o}else i+=r,s++;return i}function qs(t,e,s,i,r){let o=e.href,n=e.title||null,a=t[1].replace(r.other.outputLinkReplace,"$1");i.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:s,href:o,title:n,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,l}function ol(t,e,s){let i=t.match(s.other.indentCodeCompensation);if(i===null)return e;let r=i[1];return e.split(`
|
|
458
458
|
`).map(o=>{let n=o.match(s.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
|
|
@@ -628,7 +628,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
628
628
|
</button>
|
|
629
629
|
`)}
|
|
630
630
|
</div>
|
|
631
|
-
`:null}};we.styles=
|
|
631
|
+
`:null}};we.styles=zn;pt([h({attribute:!1})],we.prototype,"items",2);pt([h({type:Number})],we.prototype,"selectedIndex",2);pt([h({attribute:!1})],we.prototype,"onPick",2);we=pt([W("autocomplete-menu")],we);var Tl=Object.defineProperty,Cl=Object.getOwnPropertyDescriptor,O=(t,e,s,i)=>{for(var r=i>1?void 0:i?Cl(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Tl(e,s,r),r};let R=class extends _{constructor(){super(...arguments),this.disabled=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new Kt,this.readOnlyCompartment=new Kt}willUpdate(t){if(!t.has("sessionId"))return;const e=t.get("sessionId");e!==void 0&&e!==""&&Fs(e,this.draft),this.draft=this.sessionId!==void 0&&this.sessionId!==""?Rl(this.sessionId):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(t){t.has("disabled")&&this.updateEditorDisabledState(),(t.has("draft")||t.has("sessionId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const t=Xs(this.draft),e=t.kind==="shell",s=this.canSteer||this.isCompacting;return p`
|
|
632
632
|
<footer class=${e?"shell-mode":""}>
|
|
633
633
|
<div class="editor-wrap">
|
|
634
634
|
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
|
|
@@ -648,8 +648,8 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
648
648
|
<button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${s}${e}</button>
|
|
649
649
|
<button class="select-thinking" title="Select thinking level" @click=${()=>this.onSelectThinking?.()}>think ${t.thinkingLevel??"off"}</button>
|
|
650
650
|
</div>
|
|
651
|
-
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Te({parent:this.editorHost,state:ft.create({doc:this.draft,extensions:[Ci(),Oi(),Ai(),Mi.of(" "),Ei(ji,{fallback:!0}),Te.lineWrapping,Ii("Message pi... Use / for commands, @ for files"),this.editableCompartment.of(Te.editable.of(!this.disabled)),this.readOnlyCompartment.of(ft.readOnly.of(this.disabled)),Te.updateListener.of(t=>{t.docChanged&&this.updateDraft(t.state.doc.toString())}),Ri.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:t=>qi(t)||Li(t)},{key:"Tab",run:t=>this.handleEditorTab(t)},{key:"Shift-Tab",run:t=>Qt.shift?.(t)??!1},{key:"Backspace",run:t=>
|
|
652
|
-
`))+1,r=e.slice(i);if(e.slice(0,i).endsWith("@ "))return{kind:"file",query:r,from:i,to:t,fileMode:"path"};if(r.startsWith("/")&&i===0)return{kind:"command",query:r.slice(1),from:i,to:t};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:i,to:t}}currentQuotedTrigger(t,e){const s=t.lastIndexOf('"');if(s===-1)return;const i=t.slice(0,s);if(i.endsWith("@"))return{kind:"file",query:t.slice(s+1),from:i.length-1,to:e,quoted:!0};if(i.endsWith("@ "))return{kind:"file",query:t.slice(s+1),from:s,to:e,fileMode:"path",quoted:!0}}moveCompletion(t){return this.completions.length?(this.selectedIndex=(this.selectedIndex+t+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const t=this.completions[this.selectedIndex];return t!==void 0&&this.pick(t),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(t){if(this.completions.length){const s=this.completions[this.selectedIndex];return s!==void 0&&this.pick(s),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Qt.run?.(t)??!1}pick(t){const e=this.editor;if(!e)return;const s=t.kind==="file"&&(t.insertText.endsWith("/")||t.cursorOffset!==void 0)?"":" ",i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+s.length,r=t.insertText.endsWith('"')&&this.draft.slice(t.replaceTo).startsWith('"')?t.replaceTo+1:t.replaceTo;e.dispatch({changes:{from:t.replaceFrom,to:r,insert:`${t.insertText}${s}`},selection:Zt.cursor(i),scrollIntoView:!0}),this.completions=[]}send(t){const e=this.draft.trim();e===""||this.disabled||(this.draft="",this.sessionId!==void 0&&this.sessionId!==""&&_l(this.sessionId),this.completions=[],this.onSend?.(e,this.canSteer||this.isCompacting?t:void 0))}};R.styles=Un;O([h({type:Boolean})],R.prototype,"disabled",2);O([h()],R.prototype,"sessionId",2);O([h()],R.prototype,"cwd",2);O([h({type:Boolean})],R.prototype,"canSteer",2);O([h({type:Boolean})],R.prototype,"isCompacting",2);O([h({type:Boolean})],R.prototype,"canStop",2);O([h({attribute:!1})],R.prototype,"status",2);O([h({attribute:!1})],R.prototype,"onSend",2);O([h({attribute:!1})],R.prototype,"onStop",2);O([h({attribute:!1})],R.prototype,"onSelectModel",2);O([h({attribute:!1})],R.prototype,"onSelectThinking",2);O([ve(".markdown-editor")],R.prototype,"editorHost",2);O([$()],R.prototype,"draft",2);O([$()],R.prototype,"completions",2);O([$()],R.prototype,"selectedIndex",2);R=O([W("prompt-editor")],R);function Al(t,e,s){const i=e?"":"@";return!s&&!t.includes(" ")?`${i}${t}`:`${i}"${t}"`}function Ml(){return[]}function El(){return[]}const Il="pi-web:prompt-draft:";function ot(t){return`${Il}${t}`}function Rl(t){try{return localStorage.getItem(ot(t))??""}catch{return""}}function
|
|
651
|
+
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Te({parent:this.editorHost,state:ft.create({doc:this.draft,extensions:[Ci(),Oi(),Ai(),Mi.of(" "),Ei(ji,{fallback:!0}),Te.lineWrapping,Ii("Message pi... Use / for commands, @ for files"),this.editableCompartment.of(Te.editable.of(!this.disabled)),this.readOnlyCompartment.of(ft.readOnly.of(this.disabled)),Te.updateListener.of(t=>{t.docChanged&&this.updateDraft(t.state.doc.toString())}),Ri.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:t=>qi(t)||Li(t)},{key:"Tab",run:t=>this.handleEditorTab(t)},{key:"Shift-Tab",run:t=>Qt.shift?.(t)??!1},{key:"Backspace",run:t=>Fi(t)},..._i,...Di])]})}))}syncEditorDoc(){const t=this.editor;if(!t)return;const e=t.state.doc.toString();e!==this.draft&&t.dispatch({changes:{from:0,to:e.length,insert:this.draft},selection:Zt.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Te.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(ft.readOnly.of(this.disabled))]})}updateDraft(t){this.draft=t,this.sessionId!==void 0&&this.sessionId!==""&&Fs(this.sessionId,this.draft),this.refreshCompletions()}async refreshCompletions(){const t=this.currentTrigger(),e=++this.requestVersion;if(this.selectedIndex=0,t===void 0){this.completions=[];return}if(t.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const s=await y.commands(this.sessionId).catch(Ml);if(e!==this.requestVersion)return;this.completions=s.filter(i=>i.name.toLowerCase().includes(t.query.toLowerCase())).slice(0,12).map(i=>({kind:"command",replaceFrom:t.from,replaceTo:t.to,insertText:`/${i.name}`,detail:i.source,...i.description===void 0?{}:{description:i.description}}))}else if(t.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const s=await y.files(this.cwd,t.query,t.fileKind,t.fileMode).catch(El);if(e!==this.requestVersion)return;this.completions=s.slice(0,12).map(i=>{const r=Al(i.path,t.fileMode==="path",t.quoted===!0);return{kind:"file",replaceFrom:t.from,replaceTo:t.to,insertText:r,detail:i.kind,...i.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){const t=this.editor?.state.selection.main.head??this.draft.length,e=this.draft.slice(0,t),s=this.currentQuotedTrigger(e,t);if(s!==void 0)return s;const i=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
652
|
+
`))+1,r=e.slice(i);if(e.slice(0,i).endsWith("@ "))return{kind:"file",query:r,from:i,to:t,fileMode:"path"};if(r.startsWith("/")&&i===0)return{kind:"command",query:r.slice(1),from:i,to:t};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:i,to:t}}currentQuotedTrigger(t,e){const s=t.lastIndexOf('"');if(s===-1)return;const i=t.slice(0,s);if(i.endsWith("@"))return{kind:"file",query:t.slice(s+1),from:i.length-1,to:e,quoted:!0};if(i.endsWith("@ "))return{kind:"file",query:t.slice(s+1),from:s,to:e,fileMode:"path",quoted:!0}}moveCompletion(t){return this.completions.length?(this.selectedIndex=(this.selectedIndex+t+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const t=this.completions[this.selectedIndex];return t!==void 0&&this.pick(t),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(t){if(this.completions.length){const s=this.completions[this.selectedIndex];return s!==void 0&&this.pick(s),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Qt.run?.(t)??!1}pick(t){const e=this.editor;if(!e)return;const s=t.kind==="file"&&(t.insertText.endsWith("/")||t.cursorOffset!==void 0)?"":" ",i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+s.length,r=t.insertText.endsWith('"')&&this.draft.slice(t.replaceTo).startsWith('"')?t.replaceTo+1:t.replaceTo;e.dispatch({changes:{from:t.replaceFrom,to:r,insert:`${t.insertText}${s}`},selection:Zt.cursor(i),scrollIntoView:!0}),this.completions=[]}send(t){const e=this.draft.trim();e===""||this.disabled||(this.draft="",this.sessionId!==void 0&&this.sessionId!==""&&_l(this.sessionId),this.completions=[],this.onSend?.(e,this.canSteer||this.isCompacting?t:void 0))}};R.styles=Un;O([h({type:Boolean})],R.prototype,"disabled",2);O([h()],R.prototype,"sessionId",2);O([h()],R.prototype,"cwd",2);O([h({type:Boolean})],R.prototype,"canSteer",2);O([h({type:Boolean})],R.prototype,"isCompacting",2);O([h({type:Boolean})],R.prototype,"canStop",2);O([h({attribute:!1})],R.prototype,"status",2);O([h({attribute:!1})],R.prototype,"onSend",2);O([h({attribute:!1})],R.prototype,"onStop",2);O([h({attribute:!1})],R.prototype,"onSelectModel",2);O([h({attribute:!1})],R.prototype,"onSelectThinking",2);O([ve(".markdown-editor")],R.prototype,"editorHost",2);O([$()],R.prototype,"draft",2);O([$()],R.prototype,"completions",2);O([$()],R.prototype,"selectedIndex",2);R=O([W("prompt-editor")],R);function Al(t,e,s){const i=e?"":"@";return!s&&!t.includes(" ")?`${i}${t}`:`${i}"${t}"`}function Ml(){return[]}function El(){return[]}const Il="pi-web:prompt-draft:";function ot(t){return`${Il}${t}`}function Rl(t){try{return localStorage.getItem(ot(t))??""}catch{return""}}function Fs(t,e){try{e?localStorage.setItem(ot(t),e):localStorage.removeItem(ot(t))}catch{}}function _l(t){try{localStorage.removeItem(ot(t))}catch{}}function He(t){return Number.isFinite(t)?t<1e3?Math.round(t).toString():t<1e4?`${(t/1e3).toFixed(1)}k`:t<1e6?`${String(Math.round(t/1e3))}k`:t<1e7?`${(t/1e6).toFixed(1)}M`:`${String(Math.round(t/1e6))}M`:"0"}function Dl(t){return!Number.isFinite(t)||t===0?"$0":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}var Ll=Object.defineProperty,jl=Object.getOwnPropertyDescriptor,ht=(t,e,s,i)=>{for(var r=i>1?void 0:i?jl(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Ll(e,s,r),r};let xe=class extends _{constructor(){super(...arguments),this.workspaceLabelItems=[]}render(){const t=this.status;if(t===void 0)return p`<div class="bar muted">No session status yet</div>`;const e=t.contextUsage,s=e?e.percent==null?`context ${He(e.contextWindow)}`:`${e.percent.toFixed(1)}%/${He(e.contextWindow)}`:"context unknown",i=t.tokens;return p`
|
|
653
653
|
<div class="bar">
|
|
654
654
|
<span>${di(this.workspace?.label??"workspace",this.workspaceLabelItems,this.workspace?.path)}</span>
|
|
655
655
|
<span>↑${He(i.input)}</span>
|
|
@@ -658,7 +658,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
658
658
|
<span>${Dl(t.cost)}</span>
|
|
659
659
|
${t.pendingMessageCount>0?p`<span>${String(t.pendingMessageCount)} queued</span>`:null}
|
|
660
660
|
</div>
|
|
661
|
-
`}};xe.styles=
|
|
661
|
+
`}};xe.styles=Fn;ht([h({attribute:!1})],xe.prototype,"status",2);ht([h({attribute:!1})],xe.prototype,"workspace",2);ht([h({attribute:!1})],xe.prototype,"workspaceLabelItems",2);xe=ht([W("status-bar")],xe);var Ol=Object.defineProperty,ql=Object.getOwnPropertyDescriptor,Y=(t,e,s,i)=>{for(var r=i>1?void 0:i?ql(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Ol(e,s,r),r};let H=class extends _{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const t=this.filteredOptions();return p`
|
|
662
662
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
663
663
|
<section @mousedown=${e=>{e.stopPropagation()}}>
|
|
664
664
|
<header>
|
|
@@ -677,7 +677,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
677
677
|
</div>
|
|
678
678
|
</section>
|
|
679
679
|
</div>
|
|
680
|
-
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const t=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);t>=0&&(this.selectedIndex=t)}handleSearchInput(t){t.target instanceof HTMLInputElement&&(this.query=t.target.value,this.selectedIndex=0)}filteredOptions(){const t=this.query.trim().toLowerCase();return t===""?this.options:this.options.filter(e=>`${e.label} ${e.description??""} ${e.value}`.toLowerCase().includes(t))}handleKeyDown(t){const e=this.filteredOptions();if(t.key==="Escape")t.preventDefault(),this.onCancel?.();else if(t.key==="ArrowDown")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex+1)%e.length);else if(t.key==="ArrowUp")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex-1+e.length)%e.length);else if(t.key==="Enter"){t.preventDefault();const s=e[this.selectedIndex];s&&this.onPick?.(s.value)}}};H.styles=Wn;Y([h()],H.prototype,"title",2);Y([h({type:Boolean})],H.prototype,"searchable",2);Y([h({attribute:!1})],H.prototype,"options",2);Y([h({attribute:!1})],H.prototype,"selectedValue",2);Y([h({attribute:!1})],H.prototype,"onPick",2);Y([h({attribute:!1})],H.prototype,"onCancel",2);Y([$()],H.prototype,"selectedIndex",2);Y([$()],H.prototype,"query",2);H=Y([W("command-picker")],H);var
|
|
680
|
+
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const t=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);t>=0&&(this.selectedIndex=t)}handleSearchInput(t){t.target instanceof HTMLInputElement&&(this.query=t.target.value,this.selectedIndex=0)}filteredOptions(){const t=this.query.trim().toLowerCase();return t===""?this.options:this.options.filter(e=>`${e.label} ${e.description??""} ${e.value}`.toLowerCase().includes(t))}handleKeyDown(t){const e=this.filteredOptions();if(t.key==="Escape")t.preventDefault(),this.onCancel?.();else if(t.key==="ArrowDown")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex+1)%e.length);else if(t.key==="ArrowUp")t.preventDefault(),e.length>0&&(this.selectedIndex=(this.selectedIndex-1+e.length)%e.length);else if(t.key==="Enter"){t.preventDefault();const s=e[this.selectedIndex];s&&this.onPick?.(s.value)}}};H.styles=Wn;Y([h()],H.prototype,"title",2);Y([h({type:Boolean})],H.prototype,"searchable",2);Y([h({attribute:!1})],H.prototype,"options",2);Y([h({attribute:!1})],H.prototype,"selectedValue",2);Y([h({attribute:!1})],H.prototype,"onPick",2);Y([h({attribute:!1})],H.prototype,"onCancel",2);Y([$()],H.prototype,"selectedIndex",2);Y([$()],H.prototype,"query",2);H=Y([W("command-picker")],H);var Fl=Object.defineProperty,zl=Object.getOwnPropertyDescriptor,fe=(t,e,s,i)=>{for(var r=i>1?void 0:i?zl(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Fl(e,s,r),r};let J=class extends _{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const t=this.filteredActions();return p`
|
|
681
681
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
682
682
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
683
683
|
<header>
|
|
@@ -768,13 +768,13 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
768
768
|
${s.render(i)}
|
|
769
769
|
</div>
|
|
770
770
|
`}
|
|
771
|
-
`}renderPanelTitle(t,e){const s=t.badge?.(e);return s===void 0||s===""?p`${t.title}`:p`${t.title} <span class="tab-badge">${s}</span>`}createPanelContext(t){return{workspace:t,fileTree:this.fileTree,expandedDirs:this.expandedDirs,selectedFilePath:this.selectedFilePath,selectedFileContent:this.selectedFileContent,fileTreeStale:this.fileTreeStale,gitStatus:this.gitStatus,selectedDiffPath:this.selectedDiffPath,selectedDiff:this.selectedDiff,selectedStagedDiff:this.selectedStagedDiff,gitStale:this.gitStale,activeTerminalCount:this.activeTerminalCount,terminalAutoStart:this.terminalAutoStart,onRefreshFiles:this.onRefreshFiles,onExpandDir:this.onExpandDir,onSelectFile:this.onSelectFile,onRefreshGit:this.onRefreshGit,onSelectDiff:this.onSelectDiff}}};S.styles=jn;P([h({attribute:!1})],S.prototype,"workspace",2);P([h()],S.prototype,"tool",2);P([h({attribute:!1})],S.prototype,"panels",2);P([h({attribute:!1})],S.prototype,"workspaceLabelItems",2);P([h({type:Boolean})],S.prototype,"hideToolTabs",2);P([h({attribute:!1})],S.prototype,"fileTree",2);P([h({attribute:!1})],S.prototype,"expandedDirs",2);P([h({attribute:!1})],S.prototype,"selectedFilePath",2);P([h({attribute:!1})],S.prototype,"selectedFileContent",2);P([h({type:Boolean})],S.prototype,"fileTreeStale",2);P([h({attribute:!1})],S.prototype,"gitStatus",2);P([h({attribute:!1})],S.prototype,"selectedDiffPath",2);P([h({attribute:!1})],S.prototype,"selectedDiff",2);P([h({attribute:!1})],S.prototype,"selectedStagedDiff",2);P([h({type:Boolean})],S.prototype,"gitStale",2);P([h({attribute:!1})],S.prototype,"onSelectTool",2);P([h({attribute:!1})],S.prototype,"onRefreshFiles",2);P([h({attribute:!1})],S.prototype,"onExpandDir",2);P([h({attribute:!1})],S.prototype,"onSelectFile",2);P([h({attribute:!1})],S.prototype,"onRefreshGit",2);P([h({attribute:!1})],S.prototype,"onSelectDiff",2);P([h({type:Number})],S.prototype,"activeTerminalCount",2);P([h({type:Boolean})],S.prototype,"terminalAutoStart",2);S=P([W("workspace-panel")],S);var Hl=Object.defineProperty,Vl=Object.getOwnPropertyDescriptor,We=(t,e,s,i)=>{for(var r=i>1?void 0:i?Vl(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Hl(e,s,r),r};let pe=class extends _{constructor(){super(...arguments),this.state=Kr(),this.sessions=new Vo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.workspaces=new Jo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()},this.sessions),this.projects=new to(()=>this.state,t=>{this.setState(t)},this.workspaces),this.files=new Jr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.git=new eo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.keyboard=new Xo,this.realtime=new Oo,this.activeTerminalIds=new Set,this.mobileNavigationMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(max-width: 760px)"):void 0,this.plugins=Gl(),this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.onPopState=()=>{this.withChatScrollTransition(()=>this.restoreRoute(!1))},this.onFocus=()=>{this.sessions.refreshSelectedSession()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&this.sessions.refreshSelectedSession()},this.onMobileNavigationMediaChange=t=>{this.isMobileNavigationLayout=t.matches},this.onKeyDown=t=>{this.keyboard.handle(t,this.getActions())&&(t.preventDefault(),t.stopPropagation())}}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.connectRealtime(),this.loadExternalPlugins(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.keyboard.reset(),this.sessions.dispose(),this.realtime.close(),this.git.dispose(),super.disconnectedCallback()}setState(t){if(!Kl(this.state,t))return;const e=this.state;this.state={...this.state,...t},this.handleActivityTransition(e,this.state),this.handleWorkspaceChange(e,this.state)}async loadProjectsAndRestoreRoute(){await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRoute(!1))}async restoreRoute(t){const e=Mn(),s=fs(Ze("core:workspace.files"),"file"),i=fs(Ze("core:workspace.git"),"diff");if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:e.view??this.
|
|
771
|
+
`}renderPanelTitle(t,e){const s=t.badge?.(e);return s===void 0||s===""?p`${t.title}`:p`${t.title} <span class="tab-badge">${s}</span>`}createPanelContext(t){return{workspace:t,fileTree:this.fileTree,expandedDirs:this.expandedDirs,selectedFilePath:this.selectedFilePath,selectedFileContent:this.selectedFileContent,fileTreeStale:this.fileTreeStale,gitStatus:this.gitStatus,selectedDiffPath:this.selectedDiffPath,selectedDiff:this.selectedDiff,selectedStagedDiff:this.selectedStagedDiff,gitStale:this.gitStale,activeTerminalCount:this.activeTerminalCount,terminalAutoStart:this.terminalAutoStart,onRefreshFiles:this.onRefreshFiles,onExpandDir:this.onExpandDir,onSelectFile:this.onSelectFile,onRefreshGit:this.onRefreshGit,onSelectDiff:this.onSelectDiff}}};S.styles=jn;P([h({attribute:!1})],S.prototype,"workspace",2);P([h()],S.prototype,"tool",2);P([h({attribute:!1})],S.prototype,"panels",2);P([h({attribute:!1})],S.prototype,"workspaceLabelItems",2);P([h({type:Boolean})],S.prototype,"hideToolTabs",2);P([h({attribute:!1})],S.prototype,"fileTree",2);P([h({attribute:!1})],S.prototype,"expandedDirs",2);P([h({attribute:!1})],S.prototype,"selectedFilePath",2);P([h({attribute:!1})],S.prototype,"selectedFileContent",2);P([h({type:Boolean})],S.prototype,"fileTreeStale",2);P([h({attribute:!1})],S.prototype,"gitStatus",2);P([h({attribute:!1})],S.prototype,"selectedDiffPath",2);P([h({attribute:!1})],S.prototype,"selectedDiff",2);P([h({attribute:!1})],S.prototype,"selectedStagedDiff",2);P([h({type:Boolean})],S.prototype,"gitStale",2);P([h({attribute:!1})],S.prototype,"onSelectTool",2);P([h({attribute:!1})],S.prototype,"onRefreshFiles",2);P([h({attribute:!1})],S.prototype,"onExpandDir",2);P([h({attribute:!1})],S.prototype,"onSelectFile",2);P([h({attribute:!1})],S.prototype,"onRefreshGit",2);P([h({attribute:!1})],S.prototype,"onSelectDiff",2);P([h({type:Number})],S.prototype,"activeTerminalCount",2);P([h({type:Boolean})],S.prototype,"terminalAutoStart",2);S=P([W("workspace-panel")],S);var Hl=Object.defineProperty,Vl=Object.getOwnPropertyDescriptor,We=(t,e,s,i)=>{for(var r=i>1?void 0:i?Vl(e,s):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Hl(e,s,r),r};let pe=class extends _{constructor(){super(...arguments),this.state=Kr(),this.sessions=new Vo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.workspaces=new Jo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()},this.sessions),this.projects=new to(()=>this.state,t=>{this.setState(t)},this.workspaces),this.files=new Jr(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.git=new eo(()=>this.state,t=>{this.setState(t)},()=>{this.updateUrl()}),this.keyboard=new Xo,this.realtime=new Oo,this.activeTerminalIds=new Set,this.mobileNavigationMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(max-width: 760px)"):void 0,this.plugins=Gl(),this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.onPopState=()=>{this.withChatScrollTransition(()=>this.restoreRoute(!1))},this.onFocus=()=>{this.sessions.refreshSelectedSession()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&this.sessions.refreshSelectedSession()},this.onMobileNavigationMediaChange=t=>{this.isMobileNavigationLayout=t.matches},this.onKeyDown=t=>{this.keyboard.handle(t,this.getActions())&&(t.preventDefault(),t.stopPropagation())}}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.connectRealtime(),this.loadExternalPlugins(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown),this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.keyboard.reset(),this.sessions.dispose(),this.realtime.close(),this.git.dispose(),super.disconnectedCallback()}setState(t){if(!Kl(this.state,t))return;const e=this.state;this.state={...this.state,...t},this.handleActivityTransition(e,this.state),this.handleWorkspaceChange(e,this.state)}async loadProjectsAndRestoreRoute(){await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRoute(!1))}async restoreRoute(t){const e=Mn(),s=fs(Ze("core:workspace.files"),"file"),i=fs(Ze("core:workspace.git"),"diff");if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:e.view??this.defaultRouteView(),selectedFilePath:s,selectedDiffPath:i}),e.projectId===void 0||e.projectId==="")return;const r=this.state.projects.find(o=>o.id===e.projectId);r&&(await this.workspaces.selectProject(r,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:t}),this.setState({selectedFilePath:s,selectedDiffPath:i}),e.tool==="core:workspace.files"&&await this.files.refreshFiles(),e.tool==="core:workspace.files"&&s!==void 0&&await this.files.restoreFile(s),e.tool==="core:workspace.git"&&await this.git.refreshGit(),this.git.updatePolling())}async withChatScrollTransition(t){this.chatView?.saveScrollPosition(),await t(),await this.updateComplete,await this.chatView?.updateComplete,await Zl(),this.chatView?.restoreScrollPosition(),this.promptEditor?.focusInput()}async withChatPrependTransition(t){await t(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}updateUrl(t){En({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},t)}openWorkspaceTool(t){t==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:t,mainView:t}),this.updateUrl(),this.refreshSelectedWorkspaceTool(t),this.git.updatePolling()}selectMainView(t){if(t!=="navigation"&&t!=="chat"){this.openWorkspaceTool(t);return}this.setState({mainView:t}),this.updateUrl(),this.git.updatePolling()}handleWorkspaceChange(t,e){t.selectedWorkspace?.id!==e.selectedWorkspace?.id&&(this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear(),this.setState({activeTerminalCount:0}),e.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(e.selectedWorkspace),this.refreshSelectedWorkspaceTool(e.workspaceTool),this.git.updatePolling()))}connectRealtime(){this.realtime.connect(t=>{this.handleRealtimeEvent(t)},()=>{const t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)})}handleRealtimeEvent(t){Ql(t)?this.applyTerminalEvent(t):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(t){const e=this.state.selectedWorkspace;e===void 0||(t.type==="terminal.closed"?t.cwd:t.terminal.cwd)!==e.path||(t.type==="terminal.created"&&!t.terminal.exited?this.activeTerminalIds.add(t.terminal.id):this.activeTerminalIds.delete(t.type==="terminal.closed"?t.terminalId:t.terminal.id),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(t){try{const e=await Qs.terminals(t.projectId,t.id);if(this.state.selectedWorkspace?.id!==t.id)return;this.activeTerminalIds.clear();for(const s of e)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(t,e){const s=zs(t.status),i=zs(e.status);s&&!i&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}refreshSelectedWorkspaceTool(t){t==="core:workspace.files"&&this.files.refreshFiles(),t==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const t=this.state.selectedWorkspace===void 0?[]:this.plugins.getWorkspaceLabelItems(this.state,this.state.selectedWorkspace);return p`<workspace-panel .workspace=${this.state.selectedWorkspace} .tool=${this.state.workspaceTool} .panels=${this.visibleWorkspacePanels()} .workspaceLabelItems=${t} .fileTree=${this.state.fileTree} .expandedDirs=${this.state.expandedDirs} .selectedFilePath=${this.state.selectedFilePath} .selectedFileContent=${this.state.selectedFileContent} .fileTreeStale=${this.state.fileTreeStale} .gitStatus=${this.state.gitStatus} .selectedDiffPath=${this.state.selectedDiffPath} .selectedDiff=${this.state.selectedDiff} .selectedStagedDiff=${this.state.selectedStagedDiff} .gitStale=${this.state.gitStale} .activeTerminalCount=${this.state.activeTerminalCount} .terminalAutoStart=${this.terminalAutoStartWorkspaceId===this.state.selectedWorkspace?.id} .onSelectTool=${e=>{this.openWorkspaceTool(e)}} .onRefreshFiles=${()=>this.files.refreshFiles()} .onExpandDir=${e=>this.files.expandDir(e)} .onSelectFile=${e=>this.files.selectFile(e)} .onRefreshGit=${()=>this.git.refreshGit()} .onSelectDiff=${e=>this.git.selectDiff(e)}></workspace-panel>`}renderNavigationPanel(t){const e=s=>this.withChatScrollTransition(async()=>{await s(),t&&this.setState({mainView:"chat"}),t&&this.updateUrl()});return p`
|
|
772
772
|
<header>
|
|
773
773
|
<strong>Pi Web</strong>
|
|
774
774
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.setState({actionPaletteOpen:!0})}}>Actions</button>
|
|
775
775
|
</header>
|
|
776
776
|
<project-list .projects=${this.state.projects} .selected=${this.state.selectedProject} .onSelect=${s=>this.withChatScrollTransition(()=>this.workspaces.selectProject(s))} .onClose=${s=>this.projects.closeProject(s.id)}></project-list>
|
|
777
|
-
<workspace-list .workspaces=${this.state.workspaces} .selected=${this.state.selectedWorkspace} .workspaceLabelItems=${s=>this.plugins.getWorkspaceLabelItems(this.state,s)} .onSelect=${s=>
|
|
777
|
+
<workspace-list .workspaces=${this.state.workspaces} .selected=${this.state.selectedWorkspace} .workspaceLabelItems=${s=>this.plugins.getWorkspaceLabelItems(this.state,s)} .onSelect=${s=>this.withChatScrollTransition(()=>this.workspaces.selectWorkspace(s))}></workspace-list>
|
|
778
778
|
<session-list .sessions=${this.state.sessions} .statuses=${this.state.sessionStatuses} .activities=${this.state.sessionActivities} .selected=${this.state.selectedSession} .canStart=${!!this.state.selectedWorkspace} .onStart=${()=>e(()=>this.sessions.startSession())} .onSelect=${s=>e(()=>this.sessions.selectSession(s))} .onArchive=${s=>this.sessions.archiveSession(s)} .onRestore=${s=>e(()=>this.sessions.restoreSession(s))} .onDetachParent=${s=>this.sessions.detachParent(s)}></session-list>
|
|
779
779
|
`}visibleWorkspacePanels(){const t=this.state.selectedWorkspace;return this.plugins.getWorkspacePanels().filter(e=>t===void 0||(e.visible?.(t)??!0))}renderMobilePanelTitle(t){const e=this.state.selectedWorkspace;if(e===void 0)return t.title;const s=t.badge?.(this.createWorkspacePanelContext(e));return s===void 0||s===""?t.title:p`${t.title} <span class="tab-badge">${s}</span>`}createWorkspacePanelContext(t){return{workspace:t,fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,terminalAutoStart:this.terminalAutoStartWorkspaceId===t.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:e=>{this.git.selectDiff(e)}}}getActions(){return this.plugins.getActions(this.createPluginRuntimeContext())}async loadExternalPlugins(){try{for(const t of await kn())this.plugins.register(t);this.requestUpdate()}catch(t){console.warn("Failed to load external Pi Web plugins",t)}}createPluginRuntimeContext(){return{state:this.state,openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},selectMainView:t=>{this.selectMainView(t)},selectWorkspaceTool:t=>{this.openWorkspaceTool(t)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),stopActiveWork:()=>this.sessions.stopActiveWork()}}runAction(t){const e=this.getActions().find(s=>s.id===t&&s.enabled!==!1);e!==void 0&&e.run()}async openModelDialog(){const t=await this.sessions.listModels(),e=this.state.status?.model?.provider,s=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...e!==void 0&&s!==void 0?{selectedValue:`${e}/${s}`}:{},options:t.map(i=>{const r=i.provider??"",o=i.id??"",n=r===e&&o===s;return{value:`${r}/${o}`,label:`${o}${n?" ✓ current":""}`,description:r}})}})}async pickModel(t){this.setState({modelDialog:void 0});const e=t.indexOf("/");e<=0||await this.sessions.setModel(t.slice(0,e),t.slice(e+1))}async openThinkingDialog(){const t=await this.sessions.listThinkingLevels(),e=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:e,options:t.map(s=>({value:s,label:`${s}${s===e?" ✓ current":""}`,description:Yl(s)}))}})}async pickThinking(t){this.setState({thinkingDialog:void 0}),Jl(t)&&await this.sessions.setThinkingLevel(t)}render(){const t=this.state;return p`
|
|
780
780
|
<div class=${`shell ${t.mainView==="navigation"?"navigation-view":t.mainView==="chat"?"chat-view":"workspace-view"}`}>
|
|
@@ -802,4 +802,4 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
802
802
|
${t.actionPaletteOpen?p`<action-palette .actions=${this.getActions()} .onRun=${e=>{this.setState({actionPaletteOpen:!1}),this.runAction(e)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
|
|
803
803
|
${t.projectDialogOpen?p`<project-dialog .onSubmit=${(e,s)=>this.projects.addProject(e,s)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
|
|
804
804
|
</div>
|
|
805
|
-
`}};pe.styles=Ln;We([$()],pe.prototype,"state",2);We([ve("chat-view")],pe.prototype,"chatView",2);We([ve("prompt-editor")],pe.prototype,"promptEditor",2);We([$()],pe.prototype,"isMobileNavigationLayout",2);pe=We([W("pi-web-app")],pe);function Gl(){const t=new An;return t.register(xn),t}function Kl(t,e){return Object.entries(e).some(([s,i])=>Reflect.get(t,s)!==i)}function
|
|
805
|
+
`}};pe.styles=Ln;We([$()],pe.prototype,"state",2);We([ve("chat-view")],pe.prototype,"chatView",2);We([ve("prompt-editor")],pe.prototype,"promptEditor",2);We([$()],pe.prototype,"isMobileNavigationLayout",2);pe=We([W("pi-web-app")],pe);function Gl(){const t=new An;return t.register(xn),t}function Kl(t,e){return Object.entries(e).some(([s,i])=>Reflect.get(t,s)!==i)}function zs(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}function Ql(t){return t.type==="terminal.created"||t.type==="terminal.exited"||t.type==="terminal.closed"}function Zl(){return new Promise(t=>requestAnimationFrame(()=>{t()}))}function Jl(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="xhigh"}function Yl(t){switch(t){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)"}}export{G as a,p as b,Qs as c,lc as d,ve as e,_ as i,h as n,$ as r,W as t};
|
package/dist/client/index.html
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
html, body { margin: 0; height: 100%; overflow: hidden; }
|
|
9
9
|
body { min-height: 100dvh; }
|
|
10
10
|
</style>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-C0G9UyhD.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/vendor-editor-core-B4Sq6exx.js">
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/vendor-editor-languages-DznYbTkJ.js">
|
|
14
14
|
</head>
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { WebSocket } from "ws";
|
|
2
1
|
import { SessionDaemonClient } from "./sessiond/sessionDaemonClient.js";
|
|
3
2
|
import { resolveWorkspaceContext } from "./workspaces/workspaceContext.js";
|
|
3
|
+
import { terminalSizeQuery } from "./terminals/terminalSize.js";
|
|
4
|
+
import { bridgeSockets } from "./webSocketBridge.js";
|
|
4
5
|
export function registerTerminalProxyRoutes(app, projects, workspaces, daemon = new SessionDaemonClient()) {
|
|
5
6
|
app.get("/api/projects/:projectId/workspaces/:workspaceId/terminals", async (request, reply) => {
|
|
6
7
|
try {
|
|
@@ -35,7 +36,8 @@ export function registerTerminalProxyRoutes(app, projects, workspaces, daemon =
|
|
|
35
36
|
app.get("/api/projects/:projectId/workspaces/:workspaceId/terminals/:terminalId/socket", { websocket: true }, async (socket, request) => {
|
|
36
37
|
try {
|
|
37
38
|
await resolveWorkspaceContext(projects, workspaces, request.params.projectId, request.params.workspaceId);
|
|
38
|
-
|
|
39
|
+
const sizeQuery = terminalSizeQuery(request.query.cols, request.query.rows);
|
|
40
|
+
bridgeSockets(socket, daemon.connectWebSocket(`/terminals/${request.params.terminalId}/socket${sizeQuery}`));
|
|
39
41
|
}
|
|
40
42
|
catch (error) {
|
|
41
43
|
socket.send(JSON.stringify({ type: "error", message: error instanceof Error ? error.message : String(error) }));
|
|
@@ -55,16 +57,4 @@ async function proxyJson(daemon, method, path, body, reply) {
|
|
|
55
57
|
function requestFailed(reply, error) {
|
|
56
58
|
reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
|
|
57
59
|
}
|
|
58
|
-
function bridgeSockets(client, upstream) {
|
|
59
|
-
client.on("message", (data) => { sendIfOpen(upstream, data); });
|
|
60
|
-
upstream.on("message", (data) => { sendIfOpen(client, data); });
|
|
61
|
-
client.on("close", () => { upstream.close(); });
|
|
62
|
-
upstream.on("close", () => { client.close(); });
|
|
63
|
-
upstream.on("error", () => { client.close(); });
|
|
64
|
-
client.on("error", () => { upstream.close(); });
|
|
65
|
-
}
|
|
66
|
-
function sendIfOpen(socket, data) {
|
|
67
|
-
if (socket.readyState === WebSocket.OPEN)
|
|
68
|
-
socket.send(data);
|
|
69
|
-
}
|
|
70
60
|
//# sourceMappingURL=terminalProxyRoutes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminalProxyRoutes.js","sourceRoot":"","sources":["../../src/server/terminalProxyRoutes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"terminalProxyRoutes.js","sourceRoot":"","sources":["../../src/server/terminalProxyRoutes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAE3E,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,MAAM,UAAU,2BAA2B,CAAC,GAAoB,EAAE,QAAwB,EAAE,UAA4B,EAAE,MAAM,GAAG,IAAI,mBAAmB,EAAE;IAC1J,GAAG,CAAC,GAAG,CAAyD,4DAA4D,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QACrJ,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC1H,OAAO,MAAM,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,kBAAkB,kBAAkB,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAChH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YAC5B,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,IAAI,CAAgH,4DAA4D,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QAC7M,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC1H,OAAO,MAAM,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;QACtG,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YAC5B,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,MAAM,CAA6E,wEAAwE,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QACxL,IAAI,CAAC;YACH,MAAM,uBAAuB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC1G,OAAO,MAAM,SAAS,CAAC,MAAM,EAAE,QAAQ,EAAE,cAAc,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAC5H,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YAC5B,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,GAAG,CAA4H,+EAA+E,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;QACjQ,IAAI,CAAC;YACH,MAAM,uBAAuB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC1G,MAAM,SAAS,GAAG,iBAAiB,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC5E,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,cAAc,OAAO,CAAC,MAAM,CAAC,UAAU,UAAU,SAAS,EAAE,CAAC,CAAC,CAAC;QAC/G,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;YAChH,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,MAA2B,EAAE,MAAc,EAAE,IAAY,EAAE,IAAa,EAAE,KAAmB;IACpH,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC1D,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAChC,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IACrD,IAAI,WAAW,KAAK,SAAS,IAAI,WAAW,KAAK,EAAE;QAAE,KAAK,CAAC,MAAM,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IAC/F,MAAM,KAAK,GAAY,QAAQ,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpF,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,aAAa,CAAC,KAAmB,EAAE,KAAc;IACxD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC1F,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseTerminalSize } from "./terminalSize.js";
|
|
1
2
|
export function registerTerminalRoutes(app, terminals, prefix = "") {
|
|
2
3
|
app.get(`${prefix}/terminals`, (request, reply) => {
|
|
3
4
|
if (request.query.cwd === undefined || request.query.cwd === "")
|
|
@@ -19,6 +20,9 @@ export function registerTerminalRoutes(app, terminals, prefix = "") {
|
|
|
19
20
|
app.get(`${prefix}/terminals/:terminalId/socket`, { websocket: true }, (socket, request) => {
|
|
20
21
|
let detach;
|
|
21
22
|
try {
|
|
23
|
+
const initialSize = parseTerminalSize(request.query.cols, request.query.rows);
|
|
24
|
+
if (initialSize !== undefined)
|
|
25
|
+
terminals.resize(request.params.terminalId, initialSize.cols, initialSize.rows);
|
|
22
26
|
detach = terminals.attach(request.params.terminalId, {
|
|
23
27
|
output: (data, replay) => { socket.send(JSON.stringify({ type: "output", data, replay })); },
|
|
24
28
|
exit: (exitCode) => { socket.send(JSON.stringify({ type: "exit", exitCode })); },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminalRoutes.js","sourceRoot":"","sources":["../../../src/server/terminals/terminalRoutes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"terminalRoutes.js","sourceRoot":"","sources":["../../../src/server/terminals/terminalRoutes.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAWtD,MAAM,UAAU,sBAAsB,CAAC,GAAoB,EAAE,SAA+B,EAAE,MAAM,GAAG,EAAE;IACvG,GAAG,CAAC,GAAG,CAAoC,GAAG,MAAM,YAAY,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;QACnF,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,SAAS,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,EAAE;YAAE,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,iCAAiC,EAAE,CAAC,CAAC;QAC3I,OAAO,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,IAAI,CAAyE,GAAG,MAAM,YAAY,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;QACzH,IAAI,CAAC;YACH,OAAO,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACxC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACjG,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,MAAM,CAAqC,GAAG,MAAM,wBAAwB,EAAE,CAAC,OAAO,EAAE,EAAE;QAC5F,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,GAAG,CAAoF,GAAG,MAAM,+BAA+B,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE;QAC5K,IAAI,MAAgC,CAAC;QACrC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,iBAAiB,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC9E,IAAI,WAAW,KAAK,SAAS;gBAAE,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC;YAC/G,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE;gBACnD,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC5F,IAAI,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;aACjF,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;YAChH,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,OAAO;QACT,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,EAAE;YAC5B,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;gBACzC,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO;oBAAE,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;gBACvF,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ;oBAAE,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;YACzG,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;YAClH,CAAC;QACH,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACxC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1C,CAAC,CAAC,CAAC;AACL,CAAC;AAMD,SAAS,kBAAkB,CAAC,IAAa;IACvC,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;IACzD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IACvG,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,OAAO,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;IAClH,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;IAC9K,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;AAC9C,CAAC;AAED,SAAS,eAAe,CAAC,IAAa;IACpC,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,IAAI,YAAY,WAAW;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC3E,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrE,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACrD,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function parseTerminalSize(cols, rows) {
|
|
2
|
+
const parsedCols = Number(cols);
|
|
3
|
+
const parsedRows = Number(rows);
|
|
4
|
+
if (!isValidTerminalSize(parsedCols, parsedRows))
|
|
5
|
+
return undefined;
|
|
6
|
+
return { cols: Math.floor(parsedCols), rows: Math.floor(parsedRows) };
|
|
7
|
+
}
|
|
8
|
+
export function terminalSizeQuery(cols, rows) {
|
|
9
|
+
const size = parseTerminalSize(cols, rows);
|
|
10
|
+
if (size === undefined)
|
|
11
|
+
return "";
|
|
12
|
+
return `?cols=${encodeURIComponent(String(size.cols))}&rows=${encodeURIComponent(String(size.rows))}`;
|
|
13
|
+
}
|
|
14
|
+
export function isValidTerminalSize(cols, rows) {
|
|
15
|
+
return Number.isFinite(cols) && Number.isFinite(rows) && cols > 0 && rows > 0;
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=terminalSize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminalSize.js","sourceRoot":"","sources":["../../../src/server/terminals/terminalSize.ts"],"names":[],"mappings":"AAKA,MAAM,UAAU,iBAAiB,CAAC,IAAiC,EAAE,IAAiC;IACpG,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,IAAI,CAAC,mBAAmB,CAAC,UAAU,EAAE,UAAU,CAAC;QAAE,OAAO,SAAS,CAAC;IACnE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,IAAiC,EAAE,IAAiC;IACpG,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC3C,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IAClC,OAAO,SAAS,kBAAkB,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,SAAS,kBAAkB,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;AACxG,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAAE,IAAY;IAC5D,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;AAChF,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { WebSocket } from "ws";
|
|
2
|
+
export function bridgeSockets(client, upstream) {
|
|
3
|
+
const sendToClient = createBufferedSender(client);
|
|
4
|
+
const sendToUpstream = createBufferedSender(upstream);
|
|
5
|
+
client.on("message", (data) => { sendToUpstream(data); });
|
|
6
|
+
upstream.on("message", (data) => { sendToClient(data); });
|
|
7
|
+
client.on("close", () => { upstream.close(); });
|
|
8
|
+
upstream.on("close", () => { client.close(); });
|
|
9
|
+
upstream.on("error", () => { client.close(); });
|
|
10
|
+
client.on("error", () => { upstream.close(); });
|
|
11
|
+
}
|
|
12
|
+
export function createBufferedSender(socket) {
|
|
13
|
+
const queue = [];
|
|
14
|
+
const flush = () => {
|
|
15
|
+
while (socket.readyState === WebSocket.OPEN) {
|
|
16
|
+
const data = queue.shift();
|
|
17
|
+
if (data === undefined)
|
|
18
|
+
return;
|
|
19
|
+
socket.send(data);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
socket.on("open", flush);
|
|
23
|
+
return (data) => {
|
|
24
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
25
|
+
socket.send(data);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (socket.readyState === WebSocket.CONNECTING)
|
|
29
|
+
queue.push(data);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=webSocketBridge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webSocketBridge.js","sourceRoot":"","sources":["../../src/server/webSocketBridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAa,MAAM,IAAI,CAAC;AAE1C,MAAM,UAAU,aAAa,CAAC,MAAiB,EAAE,QAAmB;IAClE,MAAM,YAAY,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC;IAClD,MAAM,cAAc,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IACtD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,EAAE,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,MAAiB;IACpD,MAAM,KAAK,GAAW,EAAE,CAAC;IACzB,MAAM,KAAK,GAAG,GAAG,EAAE;QACjB,OAAO,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EAAE,CAAC;YAC5C,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;YAC3B,IAAI,IAAI,KAAK,SAAS;gBAAE,OAAO;YAC/B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;IACH,CAAC,CAAC;IACF,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACzB,OAAO,CAAC,IAAI,EAAE,EAAE;QACd,IAAI,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EAAE,CAAC;YACzC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClB,OAAO;QACT,CAAC;QACD,IAAI,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,UAAU;YAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC,CAAC;AACJ,CAAC"}
|
package/extensions/pi-web.ts
CHANGED
|
@@ -6,8 +6,6 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
6
6
|
|
|
7
7
|
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
8
8
|
const cliPath = join(packageRoot, "dist", "cli.js");
|
|
9
|
-
const serverPath = join(packageRoot, "dist", "server", "index.js");
|
|
10
|
-
const sessiondPath = join(packageRoot, "dist", "server", "sessiond.js");
|
|
11
9
|
const serviceNames = ["pi-web-sessiond.service", "pi-web.service"];
|
|
12
10
|
|
|
13
11
|
const subcommands = [
|
|
@@ -25,14 +23,6 @@ const subcommands = [
|
|
|
25
23
|
|
|
26
24
|
type Subcommand = (typeof subcommands)[number];
|
|
27
25
|
|
|
28
|
-
function shellSingleQuote(value: string): string {
|
|
29
|
-
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function nodeCommand(scriptPath: string): string {
|
|
33
|
-
return `${shellSingleQuote(process.execPath)} ${shellSingleQuote(scriptPath)}`;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
26
|
function parseArgs(args: string): string[] {
|
|
37
27
|
return args.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map((part) => {
|
|
38
28
|
if ((part.startsWith('"') && part.endsWith('"')) || (part.startsWith("'") && part.endsWith("'"))) {
|
|
@@ -85,14 +75,6 @@ function isSubcommand(value: string): value is Subcommand {
|
|
|
85
75
|
return subcommands.some((command) => command === value);
|
|
86
76
|
}
|
|
87
77
|
|
|
88
|
-
function installEnv(): NodeJS.ProcessEnv {
|
|
89
|
-
if (!existsSync(serverPath) || !existsSync(sessiondPath)) return {};
|
|
90
|
-
return {
|
|
91
|
-
PI_WEB_SERVER_EXEC: nodeCommand(serverPath),
|
|
92
|
-
PI_WEB_SESSIOND_EXEC: nodeCommand(sessiondPath),
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
|
|
96
78
|
async function boundedLogs(): Promise<{ code: number; output: string }> {
|
|
97
79
|
return run("journalctl", ["--user", "-u", serviceNames[0] ?? "", "-u", serviceNames[1] ?? "", "-n", "100", "--no-pager"]);
|
|
98
80
|
}
|
|
@@ -137,8 +119,7 @@ export default function piWebExtension(pi: ExtensionAPI): void {
|
|
|
137
119
|
return;
|
|
138
120
|
}
|
|
139
121
|
|
|
140
|
-
|
|
141
|
-
showResult(ctx, `pi-web ${subcommand}`, await runPiWeb([subcommand, ...rest], env));
|
|
122
|
+
showResult(ctx, `pi-web ${subcommand}`, await runPiWeb([subcommand, ...rest]));
|
|
142
123
|
},
|
|
143
124
|
});
|
|
144
125
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jmfederico/pi-web",
|
|
3
|
-
"version": "1.202605.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.202605.6",
|
|
4
|
+
"description": "Remote web UI and browser control plane for persistent Pi Coding Agent sessions.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Federico Jaramillo Martinez",
|
|
7
7
|
"type": "module",
|
|
@@ -103,7 +103,14 @@
|
|
|
103
103
|
"pi-coding-agent",
|
|
104
104
|
"coding-agent",
|
|
105
105
|
"agent",
|
|
106
|
-
"web"
|
|
106
|
+
"web",
|
|
107
|
+
"ui",
|
|
108
|
+
"web-ui",
|
|
109
|
+
"webui",
|
|
110
|
+
"remote",
|
|
111
|
+
"browser",
|
|
112
|
+
"control-plane",
|
|
113
|
+
"persistent-sessions"
|
|
107
114
|
],
|
|
108
115
|
"pi": {
|
|
109
116
|
"extensions": [
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import{i as m,c as p,d as u,b as d,a as f,n as h,e as b,r as l,t as v}from"./index-JYhVnrMr.js";import{D as w,o as g}from"./vendor-terminal-DjQ08hXu.js";import"./vendor-editor-core-B4Sq6exx.js";import"./vendor-editor-languages-DznYbTkJ.js";var x=Object.defineProperty,y=Object.getOwnPropertyDescriptor,n=(e,i,t,r)=>{for(var s=r>1?void 0:r?y(i,t):i,a=e.length-1,c;a>=0;a--)(c=e[a])&&(s=(r?c(i,t,s):c(s))||s);return r&&s&&x(i,t,s),s};let o=class extends m{constructor(){super(...arguments),this.autoStart=!1,this.terminals=[],this.loading=!1,this.visible=!1,this.suppressTerminalInput=!1}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.disposeTerminalView(),super.disconnectedCallback()}willUpdate(){const e=this.workspace?.path;e!==this.observedCwd&&(this.observedCwd=e,this.loadedCwd=void 0,this.terminals=[],this.selectedId=void 0,this.disposeTerminalView())}updated(){this.loadVisibleWorkspaceTerminals(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){const e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{if(this.workspace===void 0)return;const e=await p.terminals(this.workspace.projectId,this.workspace.id);this.terminals=e,this.selectedId=e.find(i=>!i.exited)?.id??e[0]?.id,e.length===0&&this.autoStart&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}async startTerminal(){if(this.workspace!==void 0){this.error=void 0;try{const e=await p.startTerminal(this.workspace.projectId,this.workspace.id,{cols:100,rows:30});this.terminals=[...this.terminals,e],this.selectTerminal(e.id)}catch(e){this.error=e instanceof Error?e.message:String(e)}}}async closeTerminal(e,i){i.stopPropagation();try{if(this.workspace===void 0)return;await p.closeTerminal(this.workspace.projectId,this.workspace.id,e);const t=this.terminals.filter(r=>r.id!==e);this.terminals=t,this.selectedId===e&&(this.selectedId=t[0]?.id,this.disposeTerminalView())}catch(t){this.error=t instanceof Error?t.message:String(t)}}selectTerminal(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}ensureTerminalView(){const e=this.workspace;if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||this.terminalHost===void 0||e===void 0)return;const i=new w({cursorBlink:!0,convertEol:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:13,theme:{background:"#05070a",foreground:"#e6edf3",cursor:"#58a6ff",selectionBackground:"#264f78"}}),t=new g;i.loadAddon(t),i.open(this.terminalHost),this.terminal=i,this.fitAddon=t,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(this.terminalHost),i.onData(r=>{if(this.suppressTerminalInput)return;const s=T(r);s!==""&&this.send({type:"input",data:s})}),this.connectSocket(e.projectId,e.id,this.selectedId,i),requestAnimationFrame(()=>{this.fitAndNotify()}),i.focus()}connectSocket(e,i,t,r){const s=u(e,i,t);s.binaryType="arraybuffer",this.socket=s,s.addEventListener("open",()=>{this.fitAndNotify()}),s.addEventListener("message",a=>{this.handleSocketMessage(a.data,t,r)}),s.addEventListener("close",()=>{this.socket===s&&(this.socket=void 0)})}async handleSocketMessage(e,i,t){try{const r=k(await I(e));r.type==="output"&&this.writeTerminalOutput(t,r.data,r.replay===!0),r.type==="exit"&&(t.writeln(`\r
|
|
2
|
-
[process exited${r.exitCode===void 0?"":` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(s=>s.id===i?{...s,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:s)),r.type==="error"&&t.writeln(`\r
|
|
3
|
-
[terminal error: ${r.message}]`)}catch(r){t.writeln(`\r
|
|
4
|
-
[terminal error: ${r instanceof Error?r.message:String(r)}]`)}}writeTerminalOutput(e,i,t){if(!t){e.write(i);return}this.suppressTerminalInput=!0,e.write(i,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){this.fitAddon===void 0||this.terminal===void 0||(this.fitAddon.fit(),this.send({type:"resize",cols:this.terminal.cols,rows:this.terminal.rows}))}send(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0}render(){return d`
|
|
5
|
-
<section class="terminal-shell">
|
|
6
|
-
<div class="terminal-tabs">
|
|
7
|
-
${this.terminals.map(e=>d`
|
|
8
|
-
<button class=${this.selectedId===e.id?"selected":""} @click=${()=>{this.selectTerminal(e.id)}}>
|
|
9
|
-
<span>${e.name}${e.exited?" · exited":""}</span>
|
|
10
|
-
<small @click=${i=>{this.closeTerminal(e.id,i)}}>×</small>
|
|
11
|
-
</button>
|
|
12
|
-
`)}
|
|
13
|
-
<button class="new" ?disabled=${this.workspace===void 0} @click=${()=>{this.startTerminal()}}>+ Shell</button>
|
|
14
|
-
</div>
|
|
15
|
-
${this.error===void 0?null:d`<p class="error">${this.error}</p>`}
|
|
16
|
-
${this.loading?d`<p class="muted">Loading terminals…</p>`:null}
|
|
17
|
-
<div class="terminal-host"></div>
|
|
18
|
-
</section>
|
|
19
|
-
`}};o.styles=f`
|
|
20
|
-
:host { flex: 1 1 auto; min-height: 0; display: flex; }
|
|
21
|
-
.terminal-shell { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: #05070a; }
|
|
22
|
-
.terminal-tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; padding: 6px; border-bottom: 1px solid #21262d; background: #0d1117; overflow: auto; }
|
|
23
|
-
button { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 180px; border: 1px solid #30363d; border-radius: 7px; background: #161b22; color: #e6edf3; padding: 5px 7px; cursor: pointer; }
|
|
24
|
-
button.selected { border-color: #58a6ff; background: #0d2847; }
|
|
25
|
-
button.new { flex: 0 0 auto; color: #8b949e; }
|
|
26
|
-
button span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
27
|
-
button small { color: #8b949e; font-size: 14px; line-height: 1; }
|
|
28
|
-
button small:hover { color: #ff7b72; }
|
|
29
|
-
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
30
|
-
.terminal-host { flex: 1 1 auto; min-height: 0; padding: 6px; box-sizing: border-box; overflow: hidden; }
|
|
31
|
-
.terminal-host .xterm { height: 100%; cursor: text; position: relative; user-select: none; }
|
|
32
|
-
.terminal-host .xterm.focus, .terminal-host .xterm:focus { outline: none; }
|
|
33
|
-
.terminal-host .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
34
|
-
.terminal-host .xterm-helper-textarea { position: absolute !important; left: -9999em !important; top: 0 !important; width: 0 !important; height: 0 !important; min-width: 0 !important; min-height: 0 !important; padding: 0 !important; border: 0 !important; margin: 0 !important; opacity: 0 !important; z-index: -5 !important; white-space: nowrap !important; overflow: hidden !important; resize: none !important; outline: 0 !important; appearance: none !important; }
|
|
35
|
-
.terminal-host .xterm-viewport { position: absolute; inset: 0; overflow-y: scroll; cursor: default; background-color: #05070a; }
|
|
36
|
-
.terminal-host .xterm-screen { position: relative; }
|
|
37
|
-
.terminal-host .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
38
|
-
.terminal-host .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
39
|
-
.terminal-host .xterm-accessibility:not(.debug), .terminal-host .xterm-message { position: absolute; inset: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
40
|
-
.terminal-host .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
41
|
-
.terminal-host .xterm-accessibility-tree { font-family: monospace; user-select: text; white-space: pre; }
|
|
42
|
-
.terminal-host .xterm-accessibility-tree > div { transform-origin: left; width: fit-content; }
|
|
43
|
-
.terminal-host .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
44
|
-
.error { flex: 0 0 auto; margin: 0; padding: 8px; color: #ff7b72; border-bottom: 1px solid #30363d; background: #161b22; }
|
|
45
|
-
.muted { margin: 10px; color: #8b949e; }
|
|
46
|
-
.xterm { height: 100%; }
|
|
47
|
-
`;n([h({attribute:!1})],o.prototype,"workspace",2);n([h({type:Boolean})],o.prototype,"autoStart",2);n([b(".terminal-host")],o.prototype,"terminalHost",2);n([l()],o.prototype,"terminals",2);n([l()],o.prototype,"selectedId",2);n([l()],o.prototype,"loading",2);n([l()],o.prototype,"error",2);n([l()],o.prototype,"visible",2);o=n([v("terminal-panel")],o);function k(e){const i=JSON.parse(e);if(!S(i))return{type:"error",message:"Invalid terminal message"};const t=i;return t.type==="output"&&typeof t.data=="string"?{type:"output",data:t.data,...typeof t.replay=="boolean"?{replay:t.replay}:{}}:t.type==="exit"?{type:"exit",...typeof t.exitCode=="number"?{exitCode:t.exitCode}:{}}:t.type==="error"&&typeof t.message=="string"?{type:"error",message:t.message}:{type:"error",message:"Invalid terminal message"}}function T(e){return e.replaceAll("\x1B[I","").replaceAll("\x1B[O","")}async function I(e){return typeof e=="string"?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function S(e){return typeof e=="object"&&e!==null}export{o as TerminalPanel,T as filterTerminalInput};
|