@jmfederico/pi-web 1.202605.7 → 1.202605.8

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 CHANGED
@@ -6,7 +6,7 @@
6
6
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
7
  [![Pi Coding Agent](https://img.shields.io/badge/Pi-Coding%20Agent-6f42c1)](https://github.com/earendil-works/pi/tree/main/packages/coding-agent)
8
8
 
9
- Website: <https://jmfederico.github.io/pi-web/>
9
+ Website: <https://pi-web.dev/>
10
10
 
11
11
  ![Pi Web](docs/assets/pi-web-banner.png)
12
12
 
@@ -97,6 +97,30 @@ Pi Web keeps its own state intentionally small:
97
97
  - Sessions and chat history: Pi's default JSONL session storage
98
98
  - Active session runtimes and WebSockets: memory in the session daemon
99
99
 
100
+ ## Plugins
101
+
102
+ Pi Web production installs can load trusted local UI plugins without rebuilding Pi Web. Plugins are browser-side ES modules that can add action-palette actions, workspace panels, and workspace-label metadata. They do not run in the session daemon and are not sandboxed.
103
+
104
+ The supported package shape is intentionally singular: `piWeb.plugins` entries with explicit `id` and `module`, plus a browser module that exports `{ apiVersion: 1, name, activate }`. The bundled `pi-web-plugins/info` plugin is the canonical real example.
105
+
106
+ A useful prompt for AI agents:
107
+
108
+ ```text
109
+ Build a Pi Web plugin for this project. Goal: <describe the UI behavior>.
110
+ Before coding, read https://pi-web.dev/plugins.html and https://pi-web.dev/plugins.md.
111
+ Create it under ~/.pi-web/plugins/<plugin-id> using the documented Pi Web v1 plugin API.
112
+ Validate with /pi-web-plugins/manifest.json and explain reload/debug steps.
113
+ Do not modify Pi Web itself.
114
+ ```
115
+
116
+ Reload the browser tab after adding or editing a plugin. If `PI_WEB_DATA_DIR` is set, use `$PI_WEB_DATA_DIR/plugins` instead of `~/.pi-web/plugins`. Check discovery with:
117
+
118
+ ```bash
119
+ curl http://127.0.0.1:8504/pi-web-plugins/manifest.json
120
+ ```
121
+
122
+ See the full [Plugin API](docs/plugins.md) for contribution types, package metadata, and troubleshooting.
123
+
100
124
  ## Install
101
125
 
102
126
  Recommended install uses npm plus systemd user services:
@@ -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-BaavvH-H.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`
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-b1ytby08.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};
@@ -1,4 +1,4 @@
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-BaavvH-H.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
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-b1ytby08.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
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
3
  [terminal error: ${r.message}]`)}catch(r){i.writeln(`\r
4
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`
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Bblh2Nfs.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-CovbxLyI.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Cp0QKepT.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-C7TcN1cv.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
2
  import{Q as ls,w as Ie,J as xt,R as Hi,S as Vi,G as Ki,U as Gi,V as Qi,A as Zi,W as Ji,X as Yi,Y as Xi,Z as cs,x as ds,_ as er}from"./vendor-editor-core-B4Sq6exx.js";import{m as tr,i as sr,d as ir}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 Ye=globalThis,Dt=Ye.ShadowRoot&&(Ye.ShadyCSS===void 0||Ye.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ot=Symbol(),ps=new WeakMap;let si=class{constructor(e,s,i){if(this._$cssResult$=!0,i!==Ot)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(Dt&&e===void 0){const i=s!==void 0&&s.length===1;i&&(e=ps.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&ps.set(s,e))}return e}toString(){return this.cssText}};const rr=t=>new si(typeof t=="string"?t:t+"",void 0,Ot),B=(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 si(s,t,Ot)},or=(t,e)=>{if(Dt)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const i=document.createElement("style"),r=Ye.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=s.cssText,t.appendChild(i)}},hs=Dt?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const i of e.cssRules)s+=i.cssText;return rr(s)})(t):t;const{is:nr,defineProperty:ar,getOwnPropertyDescriptor:lr,getOwnPropertyNames:cr,getOwnPropertySymbols:dr,getPrototypeOf:pr}=Object,ht=globalThis,us=ht.trustedTypes,hr=us?us.emptyScript:"",ur=ht.reactiveElementPolyfillSupport,je=(t,e)=>t,et={toAttribute(t,e){switch(e){case Boolean:t=t?hr: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}},Lt=(t,e)=>!nr(t,e),fs={attribute:!0,type:String,converter:et,reflect:!1,useDefault:!1,hasChanged:Lt};Symbol.metadata??=Symbol("metadata"),ht.litPropertyMetadata??=new WeakMap;let ve=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=fs){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&&ar(this.prototype,e,r)}}static getPropertyDescriptor(e,s,i){const{get:r,set:o}=lr(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)??fs}static _$Ei(){if(this.hasOwnProperty(je("elementProperties")))return;const e=pr(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(je("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(je("properties"))){const s=this.properties,i=[...cr(s),...dr(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(hs(r))}else e!==void 0&&s.push(hs(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 or(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:et).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:et;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??Lt)(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){}};ve.elementStyles=[],ve.shadowRootOptions={mode:"open"},ve[je("elementProperties")]=new Map,ve[je("finalized")]=new Map,ur?.({ReactiveElement:ve}),(ht.reactiveElementVersions??=[]).push("2.1.2");const jt=globalThis,gs=t=>t,tt=jt.trustedTypes,ms=tt?tt.createPolicy("lit-html",{createHTML:t=>t}):void 0,ii="$lit$",ie=`lit$${Math.random().toFixed(9).slice(2)}$`,ri="?"+ie,fr=`<${ri}>`,de=document,Ne=()=>de.createComment(""),qe=t=>t===null||typeof t!="object"&&typeof t!="function",Nt=Array.isArray,gr=t=>Nt(t)||typeof t?.[Symbol.iterator]=="function",St=`[
3
3
  \f\r]`,Me=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,bs=/-->/g,ys=/>/g,ne=RegExp(`>|${St}(?:([^\\s"'>=/]+)(${St}*=${St}*(?:[^
4
4
  \f\r"'\`<>=]|("|')|))|$)`,"g"),ws=/'/g,vs=/"/g,oi=/^(?:script|style|textarea|title)$/i,mr=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),d=mr(1),re=Symbol.for("lit-noChange"),A=Symbol.for("lit-nothing"),xs=new WeakMap,ce=de.createTreeWalker(de,129);function ni(t,e){if(!Nt(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return ms!==void 0?ms.createHTML(e):e}const br=(t,e)=>{const s=t.length-1,i=[];let r,o=e===2?"<svg>":e===3?"<math>":"",n=Me;for(let a=0;a<s;a++){const l=t[a];let c,u,p=-1,f=0;for(;f<l.length&&(n.lastIndex=f,u=n.exec(l),u!==null);)f=n.lastIndex,n===Me?u[1]==="!--"?n=bs:u[1]!==void 0?n=ys:u[2]!==void 0?(oi.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ne):u[3]!==void 0&&(n=ne):n===ne?u[0]===">"?(n=r??Me,p=-1):u[1]===void 0?p=-2:(p=n.lastIndex-u[2].length,c=u[1],n=u[3]===void 0?ne:u[3]==='"'?vs:ws):n===vs||n===ws?n=ne:n===bs||n===ys?n=Me:(n=ne,r=void 0);const g=n===ne&&t[a+1].startsWith("/>")?" ":"";o+=n===Me?l+fr:p>=0?(i.push(c),l.slice(0,p)+ii+l.slice(p)+ie+g):l+ie+(p===-2?a:g)}return[ni(t,o+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class Fe{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]=br(e,s);if(this.el=Fe.createElement(c,i),ce.currentNode=this.el.content,s===2||s===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(r=ce.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const p of r.getAttributeNames())if(p.endsWith(ii)){const f=u[n++],g=r.getAttribute(p).split(ie),b=/([.?@])?(.*)/.exec(f);l.push({type:1,index:o,name:b[2],strings:g,ctor:b[1]==="."?wr:b[1]==="?"?vr:b[1]==="@"?xr:ut}),r.removeAttribute(p)}else p.startsWith(ie)&&(l.push({type:6,index:o}),r.removeAttribute(p));if(oi.test(r.tagName)){const p=r.textContent.split(ie),f=p.length-1;if(f>0){r.textContent=tt?tt.emptyScript:"";for(let g=0;g<f;g++)r.append(p[g],Ne()),ce.nextNode(),l.push({type:2,index:++o});r.append(p[f],Ne())}}}else if(r.nodeType===8)if(r.data===ri)l.push({type:2,index:o});else{let p=-1;for(;(p=r.data.indexOf(ie,p+1))!==-1;)l.push({type:7,index:o}),p+=ie.length-1}o++}}static createElement(e,s){const i=de.createElement("template");return i.innerHTML=e,i}}function Se(t,e,s=t,i){if(e===re)return e;let r=i!==void 0?s._$Co?.[i]:s._$Cl;const o=qe(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=Se(t,r._$AS(t,e.values),r,i)),e}class yr{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??de).importNode(s,!0);ce.currentNode=r;let o=ce.nextNode(),n=0,a=0,l=i[0];for(;l!==void 0;){if(n===l.index){let c;l.type===2?c=new Pe(o,o.nextSibling,this,e):l.type===1?c=new l.ctor(o,l.name,l.strings,this,e):l.type===6&&(c=new Sr(o,this,e)),this._$AV.push(c),l=i[++a]}n!==l?.index&&(o=ce.nextNode(),n++)}return ce.currentNode=de,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 Pe{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,i,r){this.type=2,this._$AH=A,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=Se(this,e,s),qe(e)?e===A||e==null||e===""?(this._$AH!==A&&this._$AR(),this._$AH=A):e!==this._$AH&&e!==re&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):gr(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!==A&&qe(this._$AH)?this._$AA.nextSibling.data=e:this.T(de.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=Fe.createElement(ni(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(s);else{const o=new yr(r,this),n=o.u(this.options);o.p(s),this.T(n),this._$AH=o}}_$AC(e){let s=xs.get(e.strings);return s===void 0&&xs.set(e.strings,s=new Fe(e)),s}k(e){Nt(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 Pe(this.O(Ne()),this.O(Ne()),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=gs(e).nextSibling;gs(e).remove(),e=i}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}let ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,i,r,o){this.type=1,this._$AH=A,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=A}_$AI(e,s=this,i,r){const o=this.strings;let n=!1;if(o===void 0)e=Se(this,e,s,0),n=!qe(e)||e!==this._$AH&&e!==re,n&&(this._$AH=e);else{const a=e;let l,c;for(e=o[0],l=0;l<o.length-1;l++)c=Se(this,a[i+l],s,l),c===re&&(c=this._$AH[l]),n||=!qe(c)||c!==this._$AH[l],c===A?e=A:e!==A&&(e+=(c??"")+o[l+1]),this._$AH[l]=c}n&&!r&&this.j(e)}j(e){e===A?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},wr=class extends ut{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===A?void 0:e}},vr=class extends ut{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==A)}},xr=class extends ut{constructor(e,s,i,r,o){super(e,s,i,r,o),this.type=5}_$AI(e,s=this){if((e=Se(this,e,s,0)??A)===re)return;const i=this._$AH,r=e===A&&i!==A||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,o=e!==A&&(i===A||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 Sr{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){Se(this,e)}}const kr={I:Pe},$r=jt.litHtmlPolyfillSupport;$r?.(Fe,Pe),(jt.litHtmlVersions??=[]).push("3.3.2");const Pr=(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 Pe(e.insertBefore(Ne(),o),o,void 0,s??{})}return r._$AI(t),r};const qt=globalThis;let R=class extends ve{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=Pr(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return re}};R._$litElement$=!0,R.finalized=!0,qt.litElementHydrateSupport?.({LitElement:R});const Cr=qt.litElementPolyfillSupport;Cr?.({LitElement:R});(qt.litElementVersions??=[]).push("4.2.2");const W=t=>(e,s)=>{s!==void 0?s.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};const Tr={attribute:!0,type:String,converter:et,reflect:!1,hasChanged:Lt},Ar=(t=Tr,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"?Ar(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 Ir=(t,e,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(t,e,s),s);function fe(t,e){return(s,i,r)=>{const o=n=>n.renderRoot?.querySelector(t)??null;return Ir(s,i,{get(){return o(this)}})}}async function y(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(Mr(n)??r.statusText)}const o=await r.json();return e(o)}function Mr(t){if(Er(t))return typeof t.error=="string"?t.error:void 0}function Er(t){return typeof t=="object"&&t!==null}function Rr(t){return typeof t=="object"&&t!==null}function w(t){if(!Rr(t))throw new Error("Expected object response");return t}function m(t,e){const s=t[e];if(typeof s!="string")throw new Error(`Expected string field: ${e}`);return s}function C(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 U(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 j(t){return e=>{if(!Array.isArray(e))throw new Error("Expected array response");return e.map(t)}}function _r(t){if(!Array.isArray(t))throw new Error("Expected array response");return t}function Dr(t){if(Array.isArray(t))return{messages:t,start:0,total:t.length};const e=w(t);return{messages:_r(e.messages),start:U(e,"start"),total:U(e,"total")}}function Ss(t){const e=w(t);return{id:m(e,"id"),name:m(e,"name"),path:m(e,"path"),createdAt:m(e,"createdAt")}}function Or(t){const e=w(t),s=C(e,"branch");return{id:m(e,"id"),projectId:m(e,"projectId"),path:m(e,"path"),label:m(e,"label"),...s===void 0?{}:{branch:s},isMain:F(e,"isMain"),isGitRepo:F(e,"isGitRepo"),isGitWorktree:F(e,"isGitWorktree")}}function $t(t){const e=w(t),s=C(e,"name"),i=C(e,"parentSessionPath"),r=C(e,"archivedAt");return{id:m(e,"id"),path:m(e,"path"),cwd:m(e,"cwd"),...s===void 0?{}:{name:s},created:m(e,"created"),modified:m(e,"modified"),messageCount:U(e,"messageCount"),firstMessage:m(e,"firstMessage"),...i===void 0?{}:{parentSessionPath:i},...e.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ee(t){const e=w(t);return{sessionId:m(e,"sessionId"),isStreaming:F(e,"isStreaming"),isCompacting:F(e,"isCompacting"),isBashRunning:F(e,"isBashRunning"),pendingMessageCount:U(e,"pendingMessageCount"),queuedMessages:e.queuedMessages===void 0?[]:j(Lr)(e.queuedMessages),tokens:jr(e.tokens),cost:U(e,"cost"),...Nr(e.model),...Jr(e.contextUsage),...S("thinkingLevel",C(e,"thinkingLevel"))}}function Lr(t){const e=w(t),s=m(e,"kind");if(s!=="steer"&&s!=="followUp")throw new Error("Invalid queued message kind");return{kind:s,text:m(e,"text")}}function jr(t){const e=w(t);return{input:U(e,"input"),output:U(e,"output"),cacheRead:U(e,"cacheRead"),cacheWrite:U(e,"cacheWrite"),total:U(e,"total")}}function ai(t){const e=w(t);return{...S("provider",C(e,"provider")),...S("id",C(e,"id")),...S("name",C(e,"name")),...S("contextWindow",ze(e,"contextWindow")),...S("reasoning",e.reasoning)}}function Nr(t){return t===void 0?{}:{model:ai(t)}}function qr(t){const e=w(t);return{models:j(ai)(e.models)}}function Fr(t){if(t!=="off"&&t!=="minimal"&&t!=="low"&&t!=="medium"&&t!=="high"&&t!=="xhigh")throw new Error("Invalid thinking level");return t}function zr(t){const e=w(t);return{levels:j(Fr)(e.levels)}}function Wr(t){if(t!=="oauth"&&t!=="api_key")throw new Error("Invalid auth type");return t}function Ur(t){if(t!=="stored"&&t!=="runtime"&&t!=="environment"&&t!=="fallback"&&t!=="models_json_key"&&t!=="models_json_command")throw new Error("Invalid auth status source");return t}function Br(t){const e=w(t),s=e.source===void 0?void 0:Ur(e.source);return{configured:F(e,"configured"),...S("source",s),...S("label",C(e,"label"))}}function Hr(t){const e=w(t);return{id:m(e,"id"),name:m(e,"name"),authType:Wr(e.authType),status:Br(e.status)}}function Vr(t){const e=w(t);return{providers:j(Hr)(e.providers)}}function Ve(t){const e=w(t);return{flowId:m(e,"flowId"),providerId:m(e,"providerId"),providerName:m(e,"providerName"),status:Kr(e.status),progress:j(i=>{if(typeof i!="string")throw new Error("Expected progress item string");return i})(e.progress),...S("error",C(e,"error")),...S("auth",Gr(e.auth)),...S("prompt",Qr(e.prompt)),...S("select",Zr(e.select))}}function Kr(t){if(t!=="running"&&t!=="complete"&&t!=="error"&&t!=="cancelled")throw new Error("Invalid OAuth flow status");return t}function Gr(t){if(t===void 0)return;const e=w(t);return{url:m(e,"url"),...S("instructions",C(e,"instructions"))}}function Qr(t){if(t===void 0)return;const e=w(t),s=m(e,"kind");if(s!=="prompt"&&s!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(e,"requestId"),message:m(e,"message"),kind:s,...S("placeholder",C(e,"placeholder")),...e.allowEmpty===!0?{allowEmpty:!0}:{}}}function Zr(t){if(t===void 0)return;const e=w(t);return{requestId:m(e,"requestId"),message:m(e,"message"),options:j(ci)(e.options)}}function Jr(t){if(t===void 0)return{};const e=w(t);return{contextUsage:{tokens:Cs(e,"tokens"),contextWindow:U(e,"contextWindow"),percent:Cs(e,"percent")}}}function Yr(t){const e=w(t),s=m(e,"source");if(s!=="extension"&&s!=="prompt"&&s!=="skill"&&s!=="builtin")throw new Error("Invalid command source");return{name:m(e,"name"),source:s,...S("description",C(e,"description"))}}function li(t){const e=w(t),s=m(e,"kind");if(s!=="tracked"&&s!=="untracked"&&s!=="other")throw new Error("Invalid file kind");return{path:m(e,"path"),kind:s}}function Xr(t){const e=w(t);return{path:m(e,"path"),entries:j(eo)(e.entries),scannedAt:m(e,"scannedAt"),truncated:F(e,"truncated")}}function eo(t){const e=w(t),s=m(e,"type");if(s!=="file"&&s!=="directory"&&s!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(e,"name"),path:m(e,"path"),type:s,...S("size",ze(e,"size")),...S("modifiedAt",C(e,"modifiedAt"))}}function to(t){const e=w(t),s=m(e,"encoding");if(s!=="utf8")throw new Error("Invalid file encoding");return{path:m(e,"path"),...S("language",C(e,"language")),encoding:s,size:U(e,"size"),modifiedAt:m(e,"modifiedAt"),content:m(e,"content"),truncated:F(e,"truncated"),binary:F(e,"binary")}}function so(t){const e=w(t);return{isGitRepo:F(e,"isGitRepo"),hash:m(e,"hash"),...S("branch",C(e,"branch")),...S("upstream",C(e,"upstream")),...S("ahead",ze(e,"ahead")),...S("behind",ze(e,"behind")),files:j(io)(e.files)}}function io(t){const e=w(t);return{path:m(e,"path"),...S("oldPath",C(e,"oldPath")),index:ks(e.index),workingTree:ks(e.workingTree)}}function ks(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 ro(t){const e=w(t);return{...S("path",C(e,"path")),staged:F(e,"staged"),hash:m(e,"hash"),diff:m(e,"diff"),truncated:F(e,"truncated")}}function $s(t){const e=w(t);return{id:m(e,"id"),cwd:m(e,"cwd"),name:m(e,"name"),createdAt:m(e,"createdAt"),exited:F(e,"exited"),...S("exitCode",ze(e,"exitCode"))}}function Ps(t){const e=w(t),s=m(e,"type");if(s==="unsupported")return{type:s,message:m(e,"message")};if(s==="select")return{type:s,requestId:m(e,"requestId"),title:m(e,"title"),options:j(ci)(e.options)};if(s==="done")return{type:s,...S("message",C(e,"message")),...oo(e.session)};throw new Error("Invalid command result type")}function ci(t){const e=w(t);return{value:m(e,"value"),label:m(e,"label"),...S("description",C(e,"description"))}}function oo(t){return t===void 0?{}:{session:$t(t)}}function Ke(t){if(w(t).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function di(t){if(w(t).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function no(t){if(w(t).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function ao(t){if(w(t).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function lo(t){if(w(t).archived!==!0)throw new Error("Expected archived response");return{archived:!0}}function co(t){if(w(t).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function po(t){if(w(t).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function ze(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 Cs(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 S(t,e){return e===void 0?{}:{[t]:e}}function ho(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 uo(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 fo={projects:()=>y("/api/projects",j(Ss)),addProject:(t,e,s)=>y("/api/projects",Ss,{method:"POST",body:JSON.stringify({path:t,name:e,create:s})}),closeProject:t=>y(`/api/projects/${encodeURIComponent(t)}`,di,{method:"DELETE"}),projectDirectories:t=>y(`/api/project-directories?q=${encodeURIComponent(t)}`,j(li))},go={workspaces:t=>y(`/api/projects/${t}/workspaces`,j(Or)),workspaceTree:(t,e,s="")=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/tree?path=${encodeURIComponent(s)}`,Xr),workspaceFile:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/file?path=${encodeURIComponent(s)}`,to)},mo={sessions:t=>y(`/api/sessions?cwd=${encodeURIComponent(t)}`,j($t)),startSession:t=>y("/api/sessions",$t,{method:"POST",body:JSON.stringify({cwd:t})}),messages:(t,e)=>y(uo(t,e),Dr),status:t=>y(`/api/sessions/${t}/status`,Ee),models:t=>y(`/api/sessions/${t}/models`,qr),setModel:(t,e,s)=>y(`/api/sessions/${t}/model`,Ee,{method:"POST",body:JSON.stringify({provider:e,modelId:s})}),cycleModel:(t,e)=>y(`/api/sessions/${t}/model/cycle`,Ee,{method:"POST",body:JSON.stringify({direction:e})}),thinkingLevels:t=>y(`/api/sessions/${t}/thinking-levels`,zr),setThinkingLevel:(t,e)=>y(`/api/sessions/${t}/thinking-level`,Ee,{method:"POST",body:JSON.stringify({level:e})}),cycleThinkingLevel:t=>y(`/api/sessions/${t}/thinking-level/cycle`,Ee,{method:"POST"}),commands:t=>y(`/api/sessions/${t}/commands`,j(Yr)),prompt:(t,e,s)=>y(`/api/sessions/${t}/prompt`,Ke,{method:"POST",body:JSON.stringify(s===void 0?{text:e}:{text:e,streamingBehavior:s})}),shell:(t,e)=>y(`/api/sessions/${t}/shell`,Ke,{method:"POST",body:JSON.stringify({text:e})}),runCommand:(t,e)=>y(`/api/sessions/${t}/commands/run`,Ps,{method:"POST",body:JSON.stringify({text:e})}),respondToCommand:(t,e,s)=>y(`/api/sessions/${t}/commands/respond`,Ps,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),abort:t=>y(`/api/sessions/${t}/abort`,no,{method:"POST"}),stop:t=>y(`/api/sessions/${t}/stop`,ao,{method:"POST"}),archive:t=>y(`/api/sessions/${t}/archive`,lo,{method:"POST"}),restore:t=>y(`/api/sessions/${t}/restore`,co,{method:"POST"}),detachParent:t=>y(`/api/sessions/${t}/detach-parent`,po,{method:"POST"}),authProviders:t=>{const e=new URLSearchParams;t?.mode!==void 0&&e.set("mode",t.mode),t?.authType!==void 0&&e.set("authType",t.authType);const s=e.toString();return y(`/api/auth/providers${s===""?"":`?${s}`}`,Vr)},saveApiKey:(t,e)=>y("/api/auth/api-key",Ke,{method:"POST",body:JSON.stringify({providerId:t,key:e})}),logoutProvider:t=>y("/api/auth/logout",Ke,{method:"POST",body:JSON.stringify({providerId:t})}),startOAuthLogin:t=>y("/api/auth/oauth",Ve,{method:"POST",body:JSON.stringify({providerId:t})}),oauthFlow:t=>y(`/api/auth/oauth/${encodeURIComponent(t)}`,Ve),respondOAuthFlow:(t,e,s)=>y(`/api/auth/oauth/${encodeURIComponent(t)}/respond`,Ve,{method:"POST",body:JSON.stringify({requestId:e,value:s})}),cancelOAuthFlow:t=>y(`/api/auth/oauth/${encodeURIComponent(t)}/cancel`,Ve,{method:"POST"})},pi={terminals:(t,e)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,j($s)),startTerminal:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals`,$s,{method:"POST",body:JSON.stringify(s??{})}),closeTerminal:(t,e,s)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}`,di,{method:"DELETE"})},bo={files:(t,e,s,i)=>y(`/api/files?cwd=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}${s!==void 0?`&kind=${encodeURIComponent(s)}`:""}${i!==void 0?`&mode=${encodeURIComponent(i)}`:""}`,j(li))},yo={gitStatus:(t,e)=>y(`/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/git/status`,so),gitDiff:(t,e,s)=>y(ho(t,e,s),ro)},D={...fo,...go,...mo,...pi,...bo,...yo};function wo(t){return new WebSocket(`${Ft()}/api/sessions/${t}/events`)}function Yc(t,e,s,i){const r=i===void 0?"":`?cols=${encodeURIComponent(String(i.cols))}&rows=${encodeURIComponent(String(i.rows))}`;return new WebSocket(`${Ft()}/api/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(e)}/terminals/${encodeURIComponent(s)}/socket${r}`)}function vo(){return new WebSocket(`${Ft()}/api/events`)}function Ft(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function xo(){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,authDialog: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:""}}class So{constructor(e,s,i,r={}){this.getState=e,this.setState=s,this.applyStatus=i,this.api=r.api??D,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(e){const s=ko(e);return s===void 0?!1:(s.command==="login"?this.openLogin(s.providerId):this.openLogout(s.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==""){await this.openLoginProvider(e);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(e){try{const{providers:s}=await this.api.authProviders({mode:"login",authType:e});this.setState({authDialog:{step:"providers",mode:"login",authType:e,providers:s}})}catch(s){this.setState({error:String(s)})}}async selectLoginProvider(e,s){const i=this.getState().authDialog;if(i?.step!=="providers")return;const r=i.providers.find(o=>o.id===e&&(s===void 0||o.authType===s));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(e){const s=this.getState().authDialog;if(s?.step!=="apiKey")return;const i={...s};delete i.error,this.setState({authDialog:{...i,value:e}})}async saveApiKey(){const e=this.getState().authDialog;if(e?.step!=="apiKey")return;const s=e.value.trim();if(s===""){this.setState({authDialog:{...e,error:"API key is required"}});return}const i={...e};delete i.error,this.setState({authDialog:{...i,saving:!0}});try{await this.api.saveApiKey(e.provider.id,s),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...e,saving:!1,error:String(r)}})}}async openLogout(e){try{const{providers:s}=await this.api.authProviders({mode:"logout"});if(e!==void 0&&e!==""){const i=s.find(r=>r.id===e);i!==void 0?await this.logoutProvider(i.id):this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:"logout",providers:s}})}catch(s){this.setState({error:String(s)})}}async logoutProvider(e){try{await this.api.logoutProvider(e),this.closeDialog(),this.refreshStatus()}catch(s){this.setState({error:String(s)})}}updateOAuthInput(e){const s=this.getState().authDialog;if(s?.step!=="oauth")return;const i={...s};delete i.error,this.setState({authDialog:{...i,inputValue:e}})}async respondOAuth(e){const s=this.getState().authDialog;if(s?.step!=="oauth")return;const i=s.flow.prompt??s.flow.select;if(i===void 0)return;const r=e??s.inputValue??"",o={...s};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(s.flow.flowId,i.requestId,r);this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...s,responding:!1,error:String(n)}})}}async cancelOAuth(){const e=this.getState().authDialog;if(e?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(e.flow.flowId)}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{const{providers:s}=await this.api.authProviders({mode:"login"}),i=s.filter(o=>o.id===e);if(i.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(i.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:i}});return}const r=i[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(s){this.setState({error:String(s)})}}async startOAuth(e){try{const s=await this.api.startOAuthLogin(e.id);this.updateOAuthFlow(s),this.startPolling(s.flowId)}catch(s){this.setState({error:String(s)})}}updateOAuthFlow(e){if(e.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(e.status==="error"||e.status==="cancelled")&&this.stopPolling();const s=this.getState().authDialog,i=s?.step==="oauth"&&s.flow.flowId===e.flowId?s.inputValue??"":"",r=s?.step==="oauth"?s.flow.prompt?.requestId??s.flow.select?.requestId:void 0,o=e.prompt?.requestId??e.select?.requestId,n=r!==void 0&&r===o,a=n?i:"",l=n&&s?.step==="oauth"?s.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:e,inputValue:a,responding:l}})}startPolling(e){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(e)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e){const s=this.getState().authDialog;if(s?.step!=="oauth"||s.flow.flowId!==e){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(e))}catch(i){this.stopPolling(),this.setState({authDialog:{...s,error:String(i)}})}}async refreshStatus(){const e=this.sessionId();if(e!==void 0)try{this.applyStatus(await this.api.status(e))}catch{}}sessionId(){const e=this.getState().selectedSession;if(!(e===void 0||e.archived===!0))return e.id}}function ko(t){const e=t.trim(),s=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(e);if(s===null)return;const i=s[1];if(i!=="login"&&i!=="logout")return;const r=s[2];return r===void 0||r===""?{command:i}:{command:i,providerId:r}}function st(t){return t.replaceAll(":",".")}function $o(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 Ts(t,e){const s=$o(t)[e];return Array.isArray(s)?s[0]:s===""?void 0:s}function it(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));Po(r,i)}function Po(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 As=st("core:workspace.files");class Co{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 D.workspaceTree(e.id,s.id),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async o=>{r[o]=(await D.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:Ao(this.getState().expandedDirs,e)});return}try{const r=await D.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"}),it(As,"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 D.workspaceFile(s.id,i.id,e);this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==e)return;if(To(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),it(As,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function To(t){const e=String(t);return e.includes("Path does not exist")||e.includes("ENOENT")||e.includes("no such file or directory")}function Ao(t,e){return Object.fromEntries(Object.entries(t).filter(([s])=>s!==e))}const Is=st("core:workspace.git");class Io{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 D.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}),it(Is,"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"}),it(Is,"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([D.gitDiff(s.id,i.id,{path:e}),D.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 Mo{constructor(e,s,i){this.getState=e,this.setState=s,this.workspaces=i}async loadProjects(){this.setState({error:""});try{this.setState({projects:await D.projects()})}catch(e){this.setState({error:String(e)})}}async addProject(e,s){if(e.trim()!=="")try{const i=await D.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 D.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)})}}}const Pt="pi-web:cached-new-sessions:v1",Eo="browserCachedNew";function We(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ms(t,e=We()){if(t.messageCount!==0||t.archived===!0)return;const s=zt(e).filter(i=>i.id!==t.id);Wt([Ct(t),...s],e)}function Ct(t){return{...t,browserCachedNew:!0}}function Es(t,e=We()){const s=zt(e).filter(i=>i.id!==t);Wt(s,e)}function Ro(t,e,s=We()){const i=new Set(e.map(a=>a.id)),r=zt(s),o=r.filter(a=>!i.has(a.id));return o.length!==r.length&&Wt(o,s),[...o.filter(a=>a.cwd===t),...e]}function xe(t){return t===void 0?!1:Oo(t)&&t.browserCachedNew===!0}function _o(t){return{id:t.id,path:t.path,cwd:t.cwd,...t.name===void 0?{}:{name:t.name},created:t.created,modified:t.modified,messageCount:t.messageCount,firstMessage:t.firstMessage,...t.parentSessionPath===void 0?{}:{parentSessionPath:t.parentSessionPath},...t.archived===!0?{archived:!0}:{},...t.archivedAt===void 0?{}:{archivedAt:t.archivedAt}}}function zt(t=We()){try{const e=t?.getItem(Pt);if(e==null||e==="")return[];const s=JSON.parse(e);return Array.isArray(s)?s.flatMap(i=>Do(i)):[]}catch{return[]}}function Wt(t,e=We()){try{t.length===0?e?.removeItem(Pt):e?.setItem(Pt,JSON.stringify(t))}catch{}}function Do(t){if(!Lo(t))return[];const e=we(t,"id"),s=we(t,"path"),i=we(t,"cwd"),r=we(t,"created"),o=we(t,"modified"),n=we(t,"firstMessage"),a=jo(t,"messageCount");if(e===void 0||s===void 0||i===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const l=Rs(t,"name"),c=Rs(t,"parentSessionPath");return[{id:e,path:s,cwd:i,...l===void 0?{}:{name:l},created:r,modified:o,messageCount:a,firstMessage:n,...c===void 0?{}:{parentSessionPath:c},browserCachedNew:!0}]}function Oo(t){return Eo in t}function Lo(t){return typeof t=="object"&&t!==null}function we(t,e){const s=t[e];return typeof s=="string"?s:void 0}function Rs(t,e){const s=t[e];return s===void 0||typeof s!="string"?void 0:s}function jo(t,e){const s=t[e];return typeof s=="number"?s:void 0}function No(t){return t.flatMap(ft).filter(e=>e.parts.length>0)}function J(t,e){return{role:t,parts:[{type:"text",text:e}]}}function Ge(t,e){const s=Ho(e);return s===void 0?t:{...t,meta:s}}function qo(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,J(e,s)]}function Fo(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 ft(t){if(zo(t))return[t];if(M(t,"role")==="bashExecution")return[Ge(Go(t),t)];const e=Qo(M(t,"role")),s=Zo(oe(t,"content"),t),i=e==="user"?Wo(s):void 0;if(i!==void 0)return i.map(a=>Ge(a,t));const r=Bo(t);if(e==="tool")return[Ge({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?[Ge({role:n,parts:o,...r===void 0?{}:{source:r}},t)]:[]}function zo(t){const e=M(t,"role");return(e==="user"||e==="assistant"||e==="tool"||e==="system"||e==="bash"||e==="skill")&&Array.isArray(oe(t,"parts"))}function Wo(t){if(t.length!==1||t[0]?.type!=="text")return;const e=Uo(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 Uo(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 Bo(t){const e=M(t,"source");if(e==="compaction"||e==="branch_summary")return e}function Ho(t){const e=Vo(oe(t,"timestamp")),s=Ko(t);if(!(e===void 0&&s===void 0))return{...e===void 0?{}:{timestamp:e},...s===void 0?{}:{model:s}}}function Vo(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 Ko(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 Go(t){const e=M(t,"command")??"",s=Xe(t,"excludeFromContext")===!0?["excluded from context","",`$ ${e}`]:[`$ ${e}`],i=oe(t,"output");i!=null&&s.push("",rt(i));const r=oe(t,"exitCode");r!=null&&s.push("",`exit ${rt(r)}`),Xe(t,"cancelled")===!0&&s.push("","cancelled"),Xe(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(`
@@ -16,7 +16,7 @@ ${r.join(`
16
16
  `),s=t.lastIndexOf("$ ");return e>s}function nn(t,e){if(e.type==="message.append")return pn(t,e.message);if(e.type==="assistant.delta")return qo(t,"assistant",e.text);if(e.type==="assistant.thinking.delta")return Fo(t,e.text);if(e.type==="tool.start")return Ls(t,{role:"assistant",content:[{type:"toolCall",name:e.toolName,arguments:e.args}]});if(e.type==="tool.end")return Ls(t,{role:"toolResult",toolName:e.toolName,content:e.content??[{type:"text",text:e.text}],isError:e.isError});if(e.type==="shell.start")return[...t,tn(e.command,e.excludeFromContext)];if(e.type==="shell.chunk")return sn(t,e.chunk);if(e.type==="shell.end")return rn(t,e);if(e.type==="command.output")return[...t,J(e.level==="error"?"system":"tool",e.message)];if(e.type==="session.error")return[...t,J("system",e.message)];if(e.type==="message.end")return e.message===void 0?void 0:an(t,e.message)}function an(t,e){const s=ft(e)[0];if(s===void 0)return;const i=ln(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"||dn(r,s)?[...t.slice(0,-1),s]:[...t,s]}function ln(t,e){const s=nt(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=nt(r);if(gi(o,s))return i}return-1}function nt(t){return t===void 0?[]:t.parts.filter(e=>e.type==="skillRead")}function gi(t,e){return t.length===e.length&&t.every((s,i)=>cn(s,e[i]))}function cn(t,e){return e===void 0?!1:Ds(t.path)===Ds(e.path)||t.name===e.name}function Ds(t){return t.replace(/\\/g,"/")}function dn(t,e){return Os(t)===Os(e)}function Os(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join(`
17
17
 
18
18
  `)}function pn(t,e){const s=ft(e);return s.length===0?t:[...t,...s]}function Ls(t,e){return ft(e).reduce(hn,t)}function hn(t,e){const s=t.at(-1);return e.role==="skill"&&gi(nt(s),nt(e))?t:s?.role===e.role&&e.role!=="skill"?[...t.slice(0,-1),{...s,parts:[...s.parts,...e.parts]}]:[...t,e]}const un="pi-web:chat-history:v2:",fn=1800*1e3;function gn(t){try{const e=sessionStorage.getItem(At(t));if(e===null||e==="")return;const s=JSON.parse(e);if(!vn(s))return;if(Date.now()-s.savedAt>fn){sessionStorage.removeItem(At(t));return}return{messages:s.messages,start:s.start,total:s.total}}catch{return}}function mn(t,e){try{sessionStorage.setItem(At(t),JSON.stringify({...e,savedAt:Date.now()}))}catch{}}function bn(t,e){if(t===void 0||!It(t))return e;if(!It(e))return t;if(yn(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 js(r,s,t),js(r,s,e),wn(r)?e:{start:s,total:Math.max(t.total,e.total),messages:r}}function yn(t,e){return t.total>e.total&&t.start===0&&e.start===0&&e.messages.length===e.total}function wn(t){for(let e=0;e<t.length;e+=1)if(!(e in t)||t[e]===void 0)return!0;return!1}function js(t,e,s){s.messages.forEach((i,r)=>{t[s.start-e+r]=i})}function At(t){return`${un}${t}`}function vn(t){if(typeof t!="object"||t===null||!("messages"in t)||!("start"in t)||!("total"in t)||!("savedAt"in t))return!1;const{messages:e,start:s,total:i,savedAt:r}=t;return Array.isArray(e)&&typeof s=="number"&&typeof i=="number"&&typeof r=="number"&&It({messages:e,start:s,total:i})}function It(t){return Number.isInteger(t.start)&&Number.isInteger(t.total)&&t.start>=0&&t.total>=t.start&&t.messages.length<=t.total-t.start&&!t.messages.some(xn)}function xn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&!("content"in t)&&typeof t.role=="string"&&Array.isArray(t.parts)}const Sn={read:gn,write:mn};class kn{constructor(e=Sn){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return Ns(this.rawHistoryPage(e))}mergeHistory(e,s){const i=bn(this.rawHistoryPage(e),s);return this.rawHistoryPages.set(e,i),this.cache.write(e,i),Ns(i)}applyLiveEvent(e,s){return nn(e,s)}rawHistoryPage(e){const s=this.rawHistoryPages.get(e)??this.cache.read(e);return s!==void 0&&this.rawHistoryPages.set(e,s),s}}function Ns(t){return{messages:No(t?.messages??[]),messagePageStart:t?.start??0,messagePageTotal:t?.total??0}}function mi(t){const e=t.trimStart();return e.startsWith("!")?{kind:"shell",excludeFromContext:e.startsWith("!!")}:bi(t).startsWith("/")?{kind:"command"}:Pn(t)?{kind:"file"}:{kind:"normal"}}function $n(t){return mi(t).kind==="shell"}function bi(t){const e=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
19
- `))+1;return t.slice(e)}function Pn(t){const e=bi(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 Cn{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),wi(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=wo(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 yi(e);An(s)&&this.onEvent?.(s)}}class Tn{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),wi(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const e=vo();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 yi(e);Mn(s)&&this.onEvent?.(s)}}function An(t){const e=Bt(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 In(t){const e=Bt(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function Mn(t){const e=Bt(t);return In(t)||e==="terminal.created"||e==="terminal.exited"||e==="terminal.closed"}function Bt(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function yi(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 wi(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 En{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 Rn(t,e){const s=e?.targetSessionId;if(s!==void 0&&s!=="")return _n(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 _n(t,e){return t.find(s=>s.id===e||s.id.startsWith(e))}function Dn(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function On(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 Re=100;class Ln{constructor(e,s,i,r=new En,o={}){this.getState=e,this.setState=s,this.updateUrl=i,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Cn,this.api=o.api??D,this.transcripts=o.transcripts??new kn}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 this.api.startSession(e.path);Ms(s);const i=Ct(s);this.setState({sessions:[i,...this.getState().sessions]}),await this.selectSession(i)}catch(s){this.setState({error:String(s)})}}preferredSession(e,s,i){return Rn(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=this.transcripts.cachedView(e.id);this.setState({selectedSession:e,...r,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 this.api.messages(e.id,{limit:Re});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const p=this.transcripts.mergeHistory(e.id,u);this.setState({...p,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([this.api.messages(e.id,{limit:Re}),this.api.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const l=this.transcripts.mergeHistory(e.id,n),c=a.isStreaming;this.catchupStreamSessionId=c?e.id:void 0,this.setState({...l,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){if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;if(xe(e)&&qn(o)){await this.recreateCachedNewSession(e,s);return}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=await this.api.messages(s.id,{before:e.messagePageStart,limit:Re});if(this.getState().selectedSession?.id!==s.id)return;const r=this.transcripts.mergeHistory(s.id,i);this.setState(r)}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($n(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,e,s),this.markCachedNewSessionPersisted(r)}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,J("user",e)]});try{await this.api.shell(s.id,e),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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,J("user",e)]});try{this.applyCommandResult(await this.api.runCommand(s.id,e)),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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 this.api.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(e){if(xe(e)){await this.deleteCachedNewSession(e);return}try{await this.api.archive(e.id);const s=this.getState(),i=Dn(s.sessions,e.id,new Date().toISOString()),r=On(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 deleteCachedNewSession(e=this.getState().selectedSession){if(!xe(e))return;this.api.stop(e.id).catch(()=>{}),Es(e.id),Ut(e.id);const s=this.getState().sessions.filter(r=>r.id!==e.id);if(this.setState({sessions:s}),this.getState().selectedSession?.id!==e.id)return;const i=s.find(r=>r.archived!==!0)??s[0];i!==void 0?await this.selectSession(i):(this.clearActiveSession(),this.updateUrl())}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.cycleThinkingLevel(e.id))}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await this.api.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,r]=await Promise.all([this.api.messages(e,{limit:Re}),this.api.status(e)]);if(this.getState().selectedSession?.id!==e)return;const o=this.transcripts.mergeHistory(e,i);this.setState({...o,status:r,activity:this.getState().sessionActivities[e],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}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})}async recreateCachedNewSession(e,s){try{const i=await this.api.startSession(e.cwd);Ms(i),en(e.id,i.id),Es(e.id);const r=Ct(i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==e.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(s?.updateUrl===!1?{replace:!0}:void 0)}catch(i){this.setState({error:String(i)})}}markCachedNewSessionPersisted(e){xe(e)&&this.replaceSession(_o(e))}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,J(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(jn(e))return}if(Nn(e)){this.queueTranscriptEvent(e);return}this.flushPendingTranscriptEvents();const i=this.transcripts.applyLiveEvent(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=this.transcripts.applyLiveEvent(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=await this.api.messages(e,{limit:Re});if(this.getState().selectedSession?.id!==e)return;this.setState(this.transcripts.mergeHistory(e,s))}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function jn(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 Nn(t){return t.type==="assistant.delta"||t.type==="assistant.thinking.delta"||t.type==="shell.chunk"}function qn(t){return t instanceof Error&&t.message.toLowerCase().includes("session not found")}class Fn{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 zn(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 Wn{constructor(e,s,i,r,o=new Fn){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 D.workspaces(e.id);this.setState({workspaces:i});const r=zn(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=Ro(e.path,await D.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 Un=1200;class Bn{constructor(){this.pendingTokens=[]}handle(e,s){const i=Vn(e);if(i===void 0||!qs(i))return!1;const r=s.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:vi(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!qs(i)?[...this.pendingTokens,i]:[i],n=r.find(l=>Gn(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>xi(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},Un)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Hn(t){return vi(t).map(e=>e.split("+").map(s=>s==="mod"?Fs()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?Fs()?"⌥":"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 Vn(t){if(t.isComposing)return;const e=Kn(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 vi(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function Kn(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 Gn(t,e){return t.length===e.length&&xi(t,e)}function xi(t,e){return e.every((s,i)=>t[i]===s)}function qs(t){return t.includes("+")}function Fs(){return navigator.userAgent.toLowerCase().includes("mac")}function Qn(){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:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:t=>t.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:t=>t.logoutAuth()},{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:Qe,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:zs,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Qe,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:zs,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Qe,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:Qe,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&&Zn(t.state.status),run:t=>t.stopActiveWork()}]}function Qe(t){return t.state.selectedWorkspace!==void 0}function zs(t){return t.state.selectedWorkspace?.isGitRepo===!0}function Zn(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const Jn="modulepreload",Yn=function(t){return"/"+t},Ws={},Si=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(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=l(s.map(c=>{if(c=Yn(c),c in Ws)return;Ws[c]=!0;const u=c.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Jn,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((g,b)=>{f.addEventListener("load",g),f.addEventListener("error",()=>b(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 Xn(){return[{id:"workspace.files",title:"Files",order:10,render:ea},{id:"workspace.git",title:"Git",order:20,visible:t=>t.isGitRepo,render:ra},{id:"workspace.terminal",title:"Terminal",order:30,badge:t=>t.activeTerminalCount>0?t.activeTerminalCount:void 0,render:ia}]}function ea(t){return d`
19
+ `))+1;return t.slice(e)}function Pn(t){const e=bi(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 Cn{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),wi(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=wo(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 yi(e);An(s)&&this.onEvent?.(s)}}class Tn{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),wi(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0}open(){if(!this.shouldReconnect)return;const e=vo();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 yi(e);Mn(s)&&this.onEvent?.(s)}}function An(t){const e=Bt(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 In(t){const e=Bt(t);return e==="status.update"||e==="activity.update"||e==="session.name"}function Mn(t){const e=Bt(t);return In(t)||e==="terminal.created"||e==="terminal.exited"||e==="terminal.closed"}function Bt(t){if(typeof t!="object"||t===null||!("type"in t))return"";const e=t.type;return typeof e=="string"?e:""}async function yi(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 wi(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 En{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 Rn(t,e){const s=e?.targetSessionId;if(s!==void 0&&s!=="")return _n(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 _n(t,e){return t.find(s=>s.id===e||s.id.startsWith(e))}function Dn(t,e,s){return t.map(i=>i.id===e?{...i,archived:!0,archivedAt:s}:i)}function On(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 Re=100;class Ln{constructor(e,s,i,r=new En,o={}){this.getState=e,this.setState=s,this.updateUrl=i,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Cn,this.api=o.api??D,this.transcripts=o.transcripts??new kn}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 this.api.startSession(e.path);Ms(s);const i=Ct(s);this.setState({sessions:[i,...this.getState().sessions]}),await this.selectSession(i)}catch(s){this.setState({error:String(s)})}}preferredSession(e,s,i){return Rn(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=this.transcripts.cachedView(e.id);this.setState({selectedSession:e,...r,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 this.api.messages(e.id,{limit:Re});if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const p=this.transcripts.mergeHistory(e.id,u);this.setState({...p,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([this.api.messages(e.id,{limit:Re}),this.api.status(e.id)]);if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;const l=this.transcripts.mergeHistory(e.id,n),c=a.isStreaming;this.catchupStreamSessionId=c?e.id:void 0,this.setState({...l,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){if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;if(xe(e)&&qn(o)){await this.recreateCachedNewSession(e,s);return}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=await this.api.messages(s.id,{before:e.messagePageStart,limit:Re});if(this.getState().selectedSession?.id!==s.id)return;const r=this.transcripts.mergeHistory(s.id,i);this.setState(r)}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($n(e))return this.runShell(e);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,e,s),this.markCachedNewSessionPersisted(r)}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,J("user",e)]});try{await this.api.shell(s.id,e),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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,J("user",e)]});try{this.applyCommandResult(await this.api.runCommand(s.id,e)),this.markCachedNewSessionPersisted(s)}catch(i){this.setState({messages:[...this.getState().messages,J("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 this.api.respondToCommand(i.id,e,s))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}async archiveSession(e=this.getState().selectedSession){if(e){if(xe(e)){await this.deleteCachedNewSession(e);return}try{await this.api.archive(e.id);const s=this.getState(),i=Dn(s.sessions,e.id,new Date().toISOString()),r=On(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 deleteCachedNewSession(e=this.getState().selectedSession){if(!xe(e))return;this.api.stop(e.id).catch(()=>{}),Es(e.id),Ut(e.id);const s=this.getState().sessions.filter(r=>r.id!==e.id);if(this.setState({sessions:s}),this.getState().selectedSession?.id!==e.id)return;const i=s.find(r=>r.archived!==!0)??s[0];i!==void 0?await this.selectSession(i):(this.clearActiveSession(),this.updateUrl())}async restoreSession(e=this.getState().selectedSession){if(e)try{await this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.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 this.api.cycleThinkingLevel(e.id))}catch(s){this.setState({error:String(s)})}}async stopActiveWork(){const e=this.getState().selectedSession;if(e)try{await this.api.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,r]=await Promise.all([this.api.messages(e,{limit:Re}),this.api.status(e)]);if(this.getState().selectedSession?.id!==e)return;const o=this.transcripts.mergeHistory(e,i);this.setState({...o,status:r,activity:this.getState().sessionActivities[e],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}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})}async recreateCachedNewSession(e,s){try{const i=await this.api.startSession(e.cwd);Ms(i),en(e.id,i.id),Es(e.id);const r=Ct(i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==e.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(s?.updateUrl===!1?{replace:!0}:void 0)}catch(i){this.setState({error:String(i)})}}markCachedNewSessionPersisted(e){xe(e)&&this.replaceSession(_o(e))}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,J(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(jn(e))return}if(Nn(e)){this.queueTranscriptEvent(e);return}this.flushPendingTranscriptEvents();const i=this.transcripts.applyLiveEvent(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=this.transcripts.applyLiveEvent(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=await this.api.messages(e,{limit:Re});if(this.getState().selectedSession?.id!==e)return;this.setState(this.transcripts.mergeHistory(e,s))}catch(s){this.getState().selectedSession?.id===e&&this.setState({error:String(s)})}}}function jn(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 Nn(t){return t.type==="assistant.delta"||t.type==="assistant.thinking.delta"||t.type==="shell.chunk"}function qn(t){return t instanceof Error&&t.message.toLowerCase().includes("session not found")}class Fn{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 zn(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 Wn{constructor(e,s,i,r,o=new Fn){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 D.workspaces(e.id);this.setState({workspaces:i});const r=zn(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=Ro(e.path,await D.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 Un=1200;class Bn{constructor(){this.pendingTokens=[]}handle(e,s){const i=Vn(e);if(i===void 0||!qs(i))return!1;const r=s.filter(l=>l.shortcut!==void 0&&l.enabled!==!1).map(l=>({action:l,tokens:vi(l.shortcut??"")})).filter(l=>l.tokens.length>0),o=this.pendingTokens.length>0&&!qs(i)?[...this.pendingTokens,i]:[i],n=r.find(l=>Gn(l.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(l=>xi(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},Un)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Hn(t){return vi(t).map(e=>e.split("+").map(s=>s==="mod"?Fs()?"⌘":"Ctrl":s==="shift"?"Shift":s==="alt"?Fs()?"⌥":"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 Vn(t){if(t.isComposing)return;const e=Kn(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 vi(t){return t.trim().toLowerCase().split(/\s+/u).filter(e=>e!=="").map(e=>e.split("+").filter(s=>s!=="").join("+"))}function Kn(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 Gn(t,e){return t.length===e.length&&xi(t,e)}function xi(t,e){return e.every((s,i)=>t[i]===s)}function qs(t){return t.includes("+")}function Fs(){return navigator.userAgent.toLowerCase().includes("mac")}function Qn(){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:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:t=>t.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:t=>t.logoutAuth()},{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:Qe,run:t=>{t.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:zs,run:t=>{t.selectMainView("core:workspace.git")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Qe,run:t=>t.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:zs,run:t=>t.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Qe,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:Qe,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&&Zn(t.state.status),run:t=>t.stopActiveWork()}]}function Qe(t){return t.state.selectedWorkspace!==void 0}function zs(t){return t.state.selectedWorkspace?.isGitRepo===!0}function Zn(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}const Jn="modulepreload",Yn=function(t){return"/"+t},Ws={},Si=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(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=l(s.map(c=>{if(c=Yn(c),c in Ws)return;Ws[c]=!0;const u=c.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Jn,u||(f.as="script"),f.crossOrigin="",f.href=c,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((g,b)=>{f.addEventListener("load",g),f.addEventListener("error",()=>b(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 Xn(){return[{id:"workspace.files",title:"Files",order:10,render:ea},{id:"workspace.git",title:"Git",order:20,visible:({workspace:t})=>t.isGitRepo,render:ra},{id:"workspace.terminal",title:"Terminal",order:30,badge:t=>t.activeTerminalCount>0?t.activeTerminalCount:void 0,render:ia}]}function ea(t){return d`
20
20
  <section class="toolbar">
21
21
  <strong>Files</strong>
22
22
  ${t.fileTreeStale?d`<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 $i(){Si(()=>import("./CodeViewer-Bblh2Nfs.js"),__vite__mapDeps([0,1,2,3]))}function aa(){Si(()=>import("./TerminalPanel-CovbxLyI.js"),__vite__mapDeps([4,5,6,1,2]))}function la(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 ca(t,e){return(e!=="unmodified"?e:t).slice(0,1).toUpperCase()}const da={id:"core",name:"Pi Web Core",activate:()=>({actions:Qn(),workspacePanels:Xn()})};async function pa(t="/pi-web-plugins/manifest.json"){window.piWebPluginApi={apiVersion:1,html:d};const e=await ha(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=fa(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 ha(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 ua(await e.json())}}function ua(t){if(!at(t)||!Array.isArray(t.plugins))throw new Error("Invalid plugin manifest");return{plugins:t.plugins.map(e=>{if(!at(e)||typeof e.module!="string"||e.module==="")throw new Error("Invalid plugin manifest entry");return{module:e.module}})}}function fa(t,e){if(!at(t))throw new Error(`Plugin module ${e} did not export an object`);const s=t.default;if(!ga(s))throw new Error(`Plugin module ${e} default export is not a PiWebPlugin`);return s}function ga(t){return at(t)&&typeof t.id=="string"&&typeof t.name=="string"&&typeof t.activate=="function"}function at(t){return typeof t=="object"&&t!==null}const ma=/^[a-z][a-z0-9.-]*$/u,ba=/^[a-z][a-z0-9.-]*$/u;class ya{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(!ma.test(e))throw new Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!ba.test(e))throw new Error(`Invalid contribution id: ${e}`)}}function wa(){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:xa(t.get("tool")),view:Sa(t.get("view"))}}function va(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 xa(t){return t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Sa(t){return t==="chat"?"chat":t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Pi(t){return t!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(t)}const ka=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Ci(t){return t.composedPath().some(e=>$a(e,ka))}function $a(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 Ht(t,e){Ci(t)||e()}function Vt(t,e){t.key!=="Enter"&&t.key!==" "||Ci(t)||(t.preventDefault(),e())}const Pa=B`
73
+ `}function $i(){Si(()=>import("./CodeViewer-Cp0QKepT.js"),__vite__mapDeps([0,1,2,3]))}function aa(){Si(()=>import("./TerminalPanel-C7TcN1cv.js"),__vite__mapDeps([4,5,6,1,2]))}function la(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 ca(t,e){return(e!=="unmodified"?e:t).slice(0,1).toUpperCase()}const da={apiVersion:1,name:"Pi Web Core",activate:()=>({contributions:{actions:Qn(),workspacePanels:Xn()}})};async function pa(t="/pi-web-plugins/manifest.json"){const e=await ha(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=fa(o,r);s.push({id:i.id,plugin:n})}catch(r){console.warn(`Failed to load Pi Web plugin ${i.module}`,r)}return s}async function ha(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 ua(await e.json())}}function ua(t){if(!at(t)||!Array.isArray(t.plugins))throw new Error("Invalid plugin manifest");return{plugins:t.plugins.map(e=>{if(!at(e)||typeof e.id!="string"||e.id===""||typeof e.module!="string"||e.module==="")throw new Error("Invalid plugin manifest entry");return{id:e.id,module:e.module}})}}function fa(t,e){if(!at(t))throw new Error(`Plugin module ${e} did not export an object`);const s=t.default;if(!ga(s))throw new Error(`Plugin module ${e} default export is not a PiWebPlugin`);return s}function ga(t){return at(t)&&t.apiVersion===1&&typeof t.name=="string"&&typeof t.activate=="function"}function at(t){return typeof t=="object"&&t!==null}const ma=/^[a-z][a-z0-9.-]*$/u,ba=/^[a-z][a-z0-9.-]*$/u;class ya{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.pluginIds=new Set,this.contributionIds=new Set}register(e){const{id:s,plugin:i}=e;if(this.validatePluginId(s),this.pluginIds.has(s))throw new Error(`Duplicate plugin id: ${s}`);this.pluginIds.add(s);const r=i.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${s}: ${String(r)}`);const n=i.activate({apiVersion:1,pluginId:s,html:d}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(s,a));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(s,a));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(s,a))}getActions(e){return this.actions.map(s=>{const i=s.enabled?.(e),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.workspaceLabels].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>r.visible?.(i)===!1?[]:r.items(i))}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(!ma.test(e))throw new Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!ba.test(e))throw new Error(`Invalid contribution id: ${e}`)}}function wa(){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:xa(t.get("tool")),view:Sa(t.get("view"))}}function va(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 xa(t){return t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Sa(t){return t==="chat"?"chat":t==="files"?"core:workspace.files":t==="git"?"core:workspace.git":Pi(t)?t:void 0}function Pi(t){return t!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(t)}const ka=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Ci(t){return t.composedPath().some(e=>$a(e,ka))}function $a(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 Ht(t,e){Ci(t)||e()}function Vt(t,e){t.key!=="Enter"&&t.key!==" "||Ci(t)||(t.preventDefault(),e())}const Pa=B`
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; }
@@ -817,7 +817,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
817
817
  header button { border: 0; background: transparent; color: #8b949e; font-size: 22px; padding: 0 8px; }
818
818
  .primary { border-color: #238636; background: #238636; }
819
819
  button:disabled { opacity: .5; cursor: not-allowed; }
820
- `;te([h({attribute:!1})],Q.prototype,"onSubmit",2);te([h({attribute:!1})],Q.prototype,"onCancel",2);te([$()],Q.prototype,"path",2);te([$()],Q.prototype,"createMissing",2);te([$()],Q.prototype,"suggestions",2);te([$()],Q.prototype,"selected",2);te([$()],Q.prototype,"loading",2);te([fe("input")],Q.prototype,"pathInput",2);Q=te([W("project-dialog")],Q);var _c=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor,P=(t,e,s,i)=>{for(var r=i>1?void 0:i?Dc(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&&_c(e,s,r),r};let k=class extends R{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],this.hideToolTabs=!1,this.fileTree=[],this.expandedDirs={},this.fileTreeStale=!1,this.gitStale=!1,this.onSelectTool=()=>{},this.onRefreshFiles=()=>{},this.onExpandDir=()=>{},this.onSelectFile=()=>{},this.onRefreshGit=()=>{},this.onSelectDiff=()=>{},this.activeTerminalCount=0,this.terminalAutoStart=!1}render(){const t=this.workspace;if(t===void 0)return d`<section class="empty">Select a workspace.</section>`;const e=this.panels.filter(r=>r.visible?.(t)??!0),s=e.find(r=>r.id===this.tool)??e[0],i=this.createPanelContext(t);return d`
820
+ `;te([h({attribute:!1})],Q.prototype,"onSubmit",2);te([h({attribute:!1})],Q.prototype,"onCancel",2);te([$()],Q.prototype,"path",2);te([$()],Q.prototype,"createMissing",2);te([$()],Q.prototype,"suggestions",2);te([$()],Q.prototype,"selected",2);te([$()],Q.prototype,"loading",2);te([fe("input")],Q.prototype,"pathInput",2);Q=te([W("project-dialog")],Q);var _c=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor,P=(t,e,s,i)=>{for(var r=i>1?void 0:i?Dc(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&&_c(e,s,r),r};let k=class extends R{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],this.hideToolTabs=!1,this.fileTree=[],this.expandedDirs={},this.fileTreeStale=!1,this.gitStale=!1,this.onSelectTool=()=>{},this.onRefreshFiles=()=>{},this.onExpandDir=()=>{},this.onSelectFile=()=>{},this.onRefreshGit=()=>{},this.onSelectDiff=()=>{},this.activeTerminalCount=0,this.terminalAutoStart=!1}render(){const t=this.workspace;if(t===void 0)return d`<section class="empty">Select a workspace.</section>`;const e=this.panels,s=e.find(r=>r.id===this.tool)??e[0],i=this.createPanelContext(t);return d`
821
821
  <header>
822
822
  ${this.hideToolTabs?null:d`
823
823
  <div class="tabs">
@@ -841,7 +841,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
841
841
  <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>
842
842
  <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>
843
843
  <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))} .onDelete=${s=>this.sessions.deleteCachedNewSession(s)} .onDetachParent=${s=>this.sessions.detachParent(s)}></session-list>
844
- `}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:d`${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 pa())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})},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),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:Wc(s)}))}})}async pickThinking(t){this.setState({thinkingDialog:void 0}),zc(t)&&await this.sessions.setThinkingLevel(t)}sendPrompt(t,e){e===void 0&&this.auth.handleSlashCommand(t)||this.sessions.send(t,e)}render(){const t=this.state;return d`
844
+ `}visibleWorkspacePanels(){const t=this.state.selectedWorkspace;return this.plugins.getWorkspacePanels().filter(e=>t===void 0||(e.visible?.({workspace:t,state:this.state})??!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:d`${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 pa())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})},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),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:Wc(s)}))}})}async pickThinking(t){this.setState({thinkingDialog:void 0}),zc(t)&&await this.sessions.setThinkingLevel(t)}sendPrompt(t,e){e===void 0&&this.auth.handleSlashCommand(t)||this.sessions.send(t,e)}render(){const t=this.state;return d`
845
845
  <div class=${`shell ${t.mainView==="navigation"?"navigation-view":t.mainView==="chat"?"chat-view":"workspace-view"}`}>
846
846
  <aside>${this.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
847
847
  <main class=${t.mainView==="chat"?"chat-view":t.mainView==="navigation"?"navigation-view":"workspace-view"}>
@@ -868,4 +868,4 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
868
868
  ${t.actionPaletteOpen?d`<action-palette .actions=${this.getActions()} .onRun=${e=>{this.setState({actionPaletteOpen:!1}),this.runAction(e)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
869
869
  ${t.projectDialogOpen?d`<project-dialog .onSubmit=${(e,s)=>this.projects.addProject(e,s)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
870
870
  </div>
871
- `}};ue.styles=Pa;He([$()],ue.prototype,"state",2);He([fe("chat-view")],ue.prototype,"chatView",2);He([fe("prompt-editor")],ue.prototype,"promptEditor",2);He([$()],ue.prototype,"isMobileNavigationLayout",2);ue=He([W("pi-web-app")],ue);function jc(){const t=new ya;return t.register(da),t}function Nc(t,e){return Object.entries(e).some(([s,i])=>Reflect.get(t,s)!==i)}function ti(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}function qc(t){return t.type==="terminal.created"||t.type==="terminal.exited"||t.type==="terminal.closed"}function Fc(){return new Promise(t=>requestAnimationFrame(()=>{t()}))}function zc(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="xhigh"}function Wc(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{B as a,d as b,pi as c,Yc as d,fe as e,R as i,h as n,$ as r,W as t};
871
+ `}};ue.styles=Pa;He([$()],ue.prototype,"state",2);He([fe("chat-view")],ue.prototype,"chatView",2);He([fe("prompt-editor")],ue.prototype,"promptEditor",2);He([$()],ue.prototype,"isMobileNavigationLayout",2);ue=He([W("pi-web-app")],ue);function jc(){const t=new ya;return t.register({id:"core",plugin:da}),t}function Nc(t,e){return Object.entries(e).some(([s,i])=>Reflect.get(t,s)!==i)}function ti(t){return t?.isStreaming===!0||t?.isBashRunning===!0||t?.isCompacting===!0}function qc(t){return t.type==="terminal.created"||t.type==="terminal.exited"||t.type==="terminal.closed"}function Fc(){return new Promise(t=>requestAnimationFrame(()=>{t()}))}function zc(t){return t==="off"||t==="minimal"||t==="low"||t==="medium"||t==="high"||t==="xhigh"}function Wc(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{B as a,d as b,pi as c,Yc as d,fe as e,R as i,h as n,$ as r,W as t};
@@ -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-BaavvH-H.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-b1ytby08.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>