@jmfederico/pi-web 1.202606.3 → 1.202606.5
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 +37 -13
- package/dist/cli.js +6 -4
- package/dist/cli.js.map +1 -1
- package/dist/client/assets/{CodeViewer-iYSv2-dg.js → CodeViewer-Bv8l_MFi.js} +1 -1
- package/dist/client/assets/{TerminalPanel-BpFW6j27.js → TerminalPanel-BZKsaE9s.js} +12 -8
- package/dist/client/assets/{index-D4dbiKXF.js → index-C9oPLpm7.js} +399 -201
- package/dist/client/assets/{vendor-editor-core-B4Sq6exx.js → vendor-editor-core-Bc1A7SO7.js} +4 -4
- package/dist/client/assets/{vendor-editor-languages-DznYbTkJ.js → vendor-editor-languages-D0CnB2js.js} +3 -3
- package/dist/client/index.html +3 -3
- package/dist/config.js +91 -3
- package/dist/config.js.map +1 -1
- package/dist/pi-web-plugins/updates/pi-web-plugin.js +52 -56
- package/dist/pi-web-plugins/updates/updatesLogic.js +65 -0
- package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +1 -5
- package/dist/server/app.js +15 -11
- package/dist/server/app.js.map +1 -1
- package/dist/server/configRoutes.js +42 -0
- package/dist/server/configRoutes.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/piWebStatus.js +15 -6
- package/dist/server/piWebStatus.js.map +1 -1
- package/dist/server/sessiond.js +17 -2
- package/dist/server/sessiond.js.map +1 -1
- package/dist/server/sessions/attachmentService.js +61 -0
- package/dist/server/sessions/attachmentService.js.map +1 -0
- package/dist/server/sessions/piSessionManagerGateway.js +2 -2
- package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
- package/dist/server/sessions/piSessionService.js +294 -20
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/sessions/sessionCommandService.js +5 -1
- package/dist/server/sessions/sessionCommandService.js.map +1 -1
- package/dist/server/sessions/sessionRoutes.js +28 -4
- package/dist/server/sessions/sessionRoutes.js.map +1 -1
- package/dist/server/sessions/spawnSessionTool.js +36 -0
- package/dist/server/sessions/spawnSessionTool.js.map +1 -0
- package/dist/server/sessions/spawnSubsessionTool.js +166 -0
- package/dist/server/sessions/spawnSubsessionTool.js.map +1 -0
- package/dist/server/sessions/spawnTargetResolver.js +36 -0
- package/dist/server/sessions/spawnTargetResolver.js.map +1 -0
- package/dist/server/sessions/subsessionTranscript.js +235 -0
- package/dist/server/sessions/subsessionTranscript.js.map +1 -0
- package/dist/server/workspaceExplorerRoutes.js +19 -4
- package/dist/server/workspaceExplorerRoutes.js.map +1 -1
- package/dist/server/workspaces/effectivePathAccess.js +27 -0
- package/dist/server/workspaces/effectivePathAccess.js.map +1 -0
- package/dist/server/workspaces/fileContentService.js +6 -6
- package/dist/server/workspaces/fileContentService.js.map +1 -1
- package/dist/server/workspaces/fileSuggestions.js +311 -23
- package/dist/server/workspaces/fileSuggestions.js.map +1 -1
- package/dist/server/workspaces/fileTreeService.js +16 -7
- package/dist/server/workspaces/fileTreeService.js.map +1 -1
- package/dist/server/workspaces/imagePreviewService.js +5 -5
- package/dist/server/workspaces/imagePreviewService.js.map +1 -1
- package/dist/server/workspaces/pathAccessPolicy.js +90 -0
- package/dist/server/workspaces/pathAccessPolicy.js.map +1 -0
- package/dist/server/workspaces/pathSafety.js +0 -15
- package/dist/server/workspaces/pathSafety.js.map +1 -1
- package/dist/server/workspaces/projectPiWebConfig.js +56 -0
- package/dist/server/workspaces/projectPiWebConfig.js.map +1 -0
- package/dist/shared/apiTypes.d.ts +55 -3
- package/dist/shared/apiTypes.js +3 -0
- package/dist/shared/apiTypes.js.map +1 -1
- package/dist/shared/capabilities.js +5 -2
- package/dist/shared/capabilities.js.map +1 -1
- package/dist/shared/federatedRoutes.js +3 -0
- package/dist/shared/federatedRoutes.js.map +1 -1
- package/dist/shared/piWebStatusParsing.js +0 -15
- package/dist/shared/piWebStatusParsing.js.map +1 -1
- package/dist/shared/promptAttachments.js +73 -0
- package/dist/shared/promptAttachments.js.map +1 -0
- package/dist/shared/thinkingLevels.d.ts +27 -0
- package/dist/shared/thinkingLevels.js +31 -0
- package/dist/shared/thinkingLevels.js.map +1 -0
- package/dist/shared/workspaceDeletion.js +1 -1
- package/dist/shared/workspaceDeletion.js.map +1 -1
- package/docs/assets/pi-web-desktop.png +0 -0
- package/docs/assets/pi-web-mobile.png +0 -0
- package/docs/assets/pi-web-tablet.png +0 -0
- package/docs/config.md +166 -0
- package/docs/plugins.md +3 -3
- package/package.json +27 -14
- package/docs/assets/pi-web-demo.gif +0 -0
- package/docs/assets/pi-web-demo.webm +0 -0
|
@@ -1,25 +1,27 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-
|
|
2
|
-
import{Q as
|
|
3
|
-
\f\r]`,
|
|
4
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Co=/'/g,Io=/"/g,Xr=/^(?:script|style|textarea|title)$/i,Yr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Yr(1),rt=Yr(2),Fe=Symbol.for("lit-noChange"),L=Symbol.for("lit-nothing"),Mo=new WeakMap,Ke=Ge.createTreeWalker(Ge,129);function en(e,t){if(!Ws(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return $o!==void 0?$o.createHTML(t):t}const Qa=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ft;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===ft?u[1]==="!--"?n=Po:u[1]!==void 0?n=Ro:u[2]!==void 0?(Xr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Be):u[3]!==void 0&&(n=Be):n===Be?u[0]===">"?(n=o??ft,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Be:u[3]==='"'?Io:Co):n===Io||n===Co?n=Be:n===Po||n===Ro?n=ft:(n=Be,o=void 0);const v=n===Be&&e[a+1].startsWith("/>")?" ":"";r+=n===ft?c+Va:h>=0?(s.push(p),c.slice(0,h)+Zr+c.slice(h)+ze+v):c+ze+(h===-2?a:v)}return[en(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Tt{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Qa(t,i);if(this.el=Tt.createElement(p,s),Ke.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Ke.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Zr)){const f=u[n++],v=o.getAttribute(h).split(ze),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?Ja:P[1]==="?"?Xa:P[1]==="@"?Ya:Ri}),o.removeAttribute(h)}else h.startsWith(ze)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Xr.test(o.tagName)){const h=o.textContent.split(ze),f=h.length-1;if(f>0){o.textContent=ri?ri.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],It()),Ke.nextNode(),c.push({type:2,index:++r});o.append(h[f],It())}}}else if(o.nodeType===8)if(o.data===Jr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(ze,h+1))!==-1;)c.push({type:7,index:r}),h+=ze.length-1}r++}}static createElement(t,i){const s=Ge.createElement("template");return s.innerHTML=t,s}}function at(e,t,i=e,s){if(t===Fe)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Mt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=at(e,o._$AS(e,t.values),o,s)),t}class Za{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ge).importNode(i,!0);Ke.currentNode=o;let r=Ke.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ct(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new el(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Ke.nextNode(),n++)}return Ke.currentNode=Ge,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class ct{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=L,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=at(this,t,i),Mt(t)?t===L||t==null||t===""?(this._$AH!==L&&this._$AR(),this._$AH=L):t!==this._$AH&&t!==Fe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Ga(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==L&&Mt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ge.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Tt.createElement(en(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Za(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Mo.get(t.strings);return i===void 0&&Mo.set(t.strings,i=new Tt(t)),i}k(t){Ws(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new ct(this.O(It()),this.O(It()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=ko(t).nextSibling;ko(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Ri=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=L,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=L}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=at(this,t,i,0),n=!Mt(t)||t!==this._$AH&&t!==Fe,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=at(this,a[s+c],i,c),p===Fe&&(p=this._$AH[c]),n||=!Mt(p)||p!==this._$AH[c],p===L?t=L:t!==L&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===L?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Ja=class extends Ri{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===L?void 0:t}},Xa=class extends Ri{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==L)}},Ya=class extends Ri{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=at(this,t,i,0)??L)===Fe)return;const s=this._$AH,o=t===L&&s!==L||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==L&&(s===L||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class el{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){at(this,t)}}const tl={I:ct},il=Ds.litHtmlPolyfillSupport;il?.(Tt,ct),(Ds.litHtmlVersions??=[]).push("3.3.2");const sl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new ct(t.insertBefore(It(),r),r,void 0,i??{})}return o._$AI(e),o};const _s=globalThis;let C=class extends ot{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=sl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};C._$litElement$=!0,C.finalized=!0,_s.litElementHydrateSupport?.({LitElement:C});const ol=_s.litElementPolyfillSupport;ol?.({LitElement:C});(_s.litElementVersions??=[]).push("4.2.2");const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const rl={attribute:!0,type:String,converter:oi,reflect:!1,hasChanged:Es},nl=(e=rl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?nl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function b(e){return d({...e,state:!0,attribute:!1})}const al=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function z(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return al(i,s,{get(){return r(this)}})}}async function S(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(ll(n)??o.statusText)}const r=await o.json();return t(r)}function ll(e){if(cl(e))return typeof e.error=="string"?e.error:void 0}function cl(e){return typeof e=="object"&&e!==null}const Os={sessionsDeleteArchived:"sessions.deleteArchived"},dl=Object.values(Os),pl=new Set(dl);function hl(e){return typeof e=="string"&&pl.has(e)}function tn(e,t){return e?.capabilities?.includes(t)===!0}function Rt(e){return typeof e=="object"&&e!==null}function y(e){if(!Rt(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function pe(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function ul(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function fl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function gl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:ul(t.messages),start:pe(t,"start"),total:pe(t,"total")}}function ml(e){const t=y(e);return N(sn)(t.machines)}function sn(e){const t=y(e),i=wl(t,"kind"),s=$(t,"baseUrl"),o=on(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function vl(e){const t=y(e),i=on(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ni(t.web)},...t.sessiond===void 0?{}:{sessiond:ni(t.sessiond)},...s===void 0?{}:{error:s}}}function bl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:an(t.components)},...t.capabilities===void 0?{}:{capabilities:Ls(t.capabilities)},...i===void 0?{}:{error:i}}}function wl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function on(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function To(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function yl(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree")}}function ds(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:pe(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function gt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:pe(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Sl)(t.queuedMessages),...w("messageCount",Te(t,"messageCount")),tokens:xl(t.tokens),cost:pe(t,"cost"),...kl(t.model),...Ol(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function Sl(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function xl(e){const t=y(e);return{input:pe(t,"input"),output:pe(t,"output"),cacheRead:pe(t,"cacheRead"),cacheWrite:pe(t,"cacheWrite"),total:pe(t,"total")}}function rn(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",Te(t,"contextWindow")),...w("reasoning",t.reasoning)}}function kl(e){return e===void 0?{}:{model:rn(e)}}function $l(e){const t=y(e);return{models:N(rn)(t.models)}}function Pl(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function Rl(e){const t=y(e);return{levels:N(Pl)(t.levels)}}function Cl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Il(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Ml(e){const t=y(e),i=t.source===void 0?void 0:Il(t.source);return{configured:D(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Tl(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:Cl(t.authType),status:Ml(t.status)}}function Al(e){const t=y(e);return{providers:N(Tl)(t.providers)}}function Ft(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:El(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Dl(t.auth)),...w("prompt",Wl(t.prompt)),...w("select",_l(t.select))}}function El(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Dl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Wl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...w("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function _l(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(cn)(t.options)}}function Ol(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Lo(t,"tokens"),contextWindow:pe(t,"contextWindow"),percent:Lo(t,"percent")}}}function Ll(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...w("description",$(t,"description"))}}function nn(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function jl(e){const t=y(e);return{path:m(t,"path"),entries:N(Nl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Nl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...w("size",Te(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function zl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",$(t,"language")),...w("mediaType",Fl(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:pe(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function Fl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Bl(e){const t=y(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",Te(t,"ahead")),...w("behind",Te(t,"behind")),files:N(Ul)(t.files)}}function Ul(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function Hl(e){const t=y(e);return{...w("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function Fi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...w("exitCode",Te(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function Ct(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:ql(t.status),...w("exitCode",Te(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:Kl(t.metadata,"metadata")}}function ql(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Kl(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Vl(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Gl(e){const t=y(e);return{workspaces:N(Vl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Eo(e){const t=y(e);return{path:m(t,"path"),exists:D(t,"exists"),config:Do(t.config),effectiveConfig:Do(t.effectiveConfig),envOverrides:Xl(t.envOverrides)}}function Do(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",Te(t,"port")),...w("allowedHosts",Ql(t.allowedHosts)),...w("shortcuts",Zl(t.shortcuts)),...w("plugins",Jl(t.plugins))}}function Ql(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function Zl(e){if(e!==void 0){if(!Rt(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function Jl(e){if(e!==void 0){if(!Rt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Rt(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!Rt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Xl(e){const t=y(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts")}}function Yl(e){const t=y(e);return{plugins:N(ec)(t.plugins)}}function ec(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:tc(t.scope),machineSpecific:ic(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function tc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function ic(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:rc(t.components),release:ac(t.release),commands:lc(t.commands),messages:N(cc)(t.messages)}}function oc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:an(t.components),capabilities:Ls(t.capabilities)}}function rc(e){const t=y(e);return{web:ni(t.web),sessiond:ni(t.sessiond)}}function an(e){const t=y(e);return{web:Wo(t.web),sessiond:Wo(t.sessiond)}}function Wo(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:Ls(t.capabilities),...w("error",$(t,"error"))}}function ni(e){const t=y(e);return{component:ln(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...w("installation",nc(t.installation)),...w("error",$(t,"error"))}}function nc(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot"))}}function ac(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function lc(e){const t=y(e);return{...w("update",$(t,"update")),...w("restart",$(t,"restart")),...w("restartWeb",$(t,"restartWeb")),...w("restartSessiond",$(t,"restartSessiond")),...w("status",$(t,"status"))}}function cc(e){const t=y(e);return{id:m(t,"id"),severity:dc(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function ln(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Ls(e){if(!Array.isArray(e)||!e.every(hl))throw new Error("Invalid PI WEB capabilities");return e}function dc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function _o(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(cn)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...pc(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function cn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function pc(e){return e===void 0?{}:{session:ds(e)}}function Bt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function ps(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function hc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function uc(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Oo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:fl(t.sessionIds,"sessionIds"),s=Te(t,"archivedCount"),o=Te(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function fc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function gc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function mc(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Te(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Lo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function w(e,t){return t===void 0?{}:{[e]:t}}function vc(e){return typeof e=="string"?e:e.id}function bc(e){return typeof e=="string"?void 0:e.cwd}function wc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function yc(e,t,i="local"){const s=new URLSearchParams,o=bc(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(vc(e))}/messages${r===""?"":`?${r}`}`}function Sc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const M=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function xc(e){return typeof e=="string"?e:e.id}function dn(e){return typeof e=="string"?void 0:e.cwd}function pn(e,t="local"){return`${M(t)}/sessions/${encodeURIComponent(xc(e))}`}function X(e,t,i="local"){return`${pn(e,i)}/${t}`}function Ut(e,t,i="local"){return`${X(e,t,i)}${hn(e)}`}function kc(e,t="local"){return`${pn(e,t)}${hn(e)}`}function hn(e){const t=dn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function te(e,t={}){const i=dn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const un={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${M(e)}/pi-web/status`,sc),piWebRuntime:()=>S("/api/pi-web/runtime",oc)},$c={machines:()=>S("/api/machines",ml),addMachine:e=>S("/api/machines",sn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>S(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>S(`/api/machines/${encodeURIComponent(e)}/health`,vl),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,bl)},ai={config:()=>S("/api/config",Eo),saveConfig:e=>S("/api/config",Eo,{method:"PUT",body:JSON.stringify({config:e})})},hs={plugins:()=>S("/api/plugins",Yl)},fn={workspaceActivity:(e="local")=>S(`${M(e)}/activity`,Gl)},Pc={projects:(e="local")=>S(`${M(e)}/projects`,N(To)),addProject:(e,t,i,s="local")=>S(`${M(s)}/projects`,To,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${M(t)}/projects/${encodeURIComponent(e)}`,ps,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${M(t)}/project-directories?q=${encodeURIComponent(e)}`,N(nn))},us={workspaces:(e,t="local")=>S(`${M(t)}/projects/${e}/workspaces`,N(yl)),deleteWorkspace:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ct,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,jl),workspaceFile:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,zl)},Rc={sessions:(e,t="local")=>S(`${M(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ds)),startSession:(e,t="local")=>S(`${M(t)}/sessions`,ds,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(yc(e,t,i),gl),status:(e,t="local")=>S(Ut(e,"status",t),gt),models:(e,t="local")=>S(Ut(e,"models",t),$l),setModel:(e,t,i,s="local")=>S(X(e,"model",s),gt,{method:"POST",body:te(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(X(e,"model/cycle",i),gt,{method:"POST",body:te(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Ut(e,"thinking-levels",t),Rl),setThinkingLevel:(e,t,i="local")=>S(X(e,"thinking-level",i),gt,{method:"POST",body:te(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(X(e,"thinking-level/cycle",t),gt,{method:"POST",body:te(e)}),commands:(e,t="local")=>S(Ut(e,"commands",t),N(Ll)),prompt:(e,t,i,s="local")=>S(X(e,"prompt",s),Bt,{method:"POST",body:te(e,i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>S(X(e,"shell",i),Bt,{method:"POST",body:te(e,{text:t})}),runCommand:(e,t,i="local")=>S(X(e,"commands/run",i),_o,{method:"POST",body:te(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(X(e,"commands/respond",s),_o,{method:"POST",body:te(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(X(e,"abort",t),hc,{method:"POST",body:te(e)}),stop:(e,t="local")=>S(X(e,"stop",t),uc,{method:"POST",body:te(e)}),archive:(e,t="local")=>S(X(e,"archive",t),Oo,{method:"POST",body:te(e)}),archiveWithDescendants:(e,t="local")=>S(X(e,"archive-tree",t),Oo,{method:"POST",body:te(e)}),restore:(e,t="local")=>S(X(e,"restore",t),fc,{method:"POST",body:te(e)}),deleteArchived:(e,t="local")=>S(kc(e,t),gc,{method:"DELETE"}),detachParent:(e,t="local")=>S(X(e,"detach-parent",t),mc,{method:"POST",body:te(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return S(`${M(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Al)},saveApiKey:(e,t,i="local")=>S(`${M(i)}/auth/api-key`,Bt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${M(t)}/auth/logout`,Bt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${M(t)}/auth/oauth`,Ft,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}`,Ft),respondOAuthFlow:(e,t,i,s="local")=>S(`${M(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Ft,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${M(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Ft,{method:"POST"})},nt={terminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Fi)),startTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Fi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ps,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ps,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${M(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Fi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ct,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${M(t)}/terminal-command-runs${Ic(e)}`,N(Ct)),getCommandRun:(e,t="local")=>Cc(e,t),cancelCommandRun:(e,t="local")=>S(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ct,{method:"POST"})};async function Cc(e,t){const i=await fetch(`${M(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Mc(s)??i.statusText)}return Ct(await i.json())}}function Ic(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Mc(e){if(!Tc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Tc(e){return typeof e=="object"&&e!==null}const Ac={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),S(`${M(i.machineId)}/files?${s.toString()}`,N(nn))}},Ec={gitStatus:(e,t,i="local")=>S(`${M(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Bl),gitDiff:(e,t,i,s="local")=>S(wc(s,e,t,i),Hl)},O={...un,...$c,...ai,...hs,...fn,...Pc,...us,...Rc,...nt,...Ac,...Ec};function Dc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Ns()}${js(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function Mb(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ns()}${js(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Wc(e="local"){return new WebSocket(`${Ns()}${js(e)}/events`)}function js(e){return`/api/machines/${encodeURIComponent(e)}`}function Ns(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Xt(){return{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,selectedTerminalId:void 0,error:""}}function _c(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ci(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function gn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const mn="local";function Bi(e,t){return`${e}:${t}`}function vn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??mn}class Oc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??fn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Lc(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=jc(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Lc(e){const t={};for(const i of e.workspaces)gn(i)&&(t[i.cwd]=i);return t}function jc(e,t){const i={...e};return gn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Nc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??O,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=zc(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function zc(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Dt(e){return e.replaceAll(":",".")}function Fc(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Ui(e,t){const i=Fc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function Se(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Bc(o,s)}function Bc(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const jo=Dt("core:workspace.files");class Uc{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await O.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await O.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:qc(this.getState().expandedDirs,t)});return}try{const o=await O.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),Se(jo,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await O.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(Hc(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),Se(jo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function Hc(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function qc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const No=Dt("core:workspace.git");class Kc{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await O.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Se(No,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),Se(No,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([O.gitDiff(i.id,s.id,{path:t},g(this.getState())),O.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Vc{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await O.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:zo(this.getState().machineActivities,o),machineRuntimes:zo(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Xt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await O.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await O.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Hi(this.getState().machineStatuses,t.id),machineRuntimes:Hi(this.getState().machineRuntimes,t.id),machineActivities:Hi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await O.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await O.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await O.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>O.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>O.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Hi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function zo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Gc{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await O.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await O.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await O.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const fs="pi-web:cached-new-sessions:v1",Qc="browserCachedNew",dt="local";function Wt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=dt,i=Wt()){if(e.messageCount!==0||e.archived===!0)return;const s=zs(i).filter(o=>o.id!==e.id||o.machineId!==t);Fs([gs(e,t),...s],i)}function gs(e,t=dt){return{...e,browserCachedNew:!0,machineId:t}}function Bo(e,t=dt,i=Wt()){const s=zs(i).filter(o=>o.id!==e||o.machineId!==t);Fs(s,i)}function Zc(e,t,i=dt,s=Wt()){const o=new Set(t.map(c=>c.id)),r=zs(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Fs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ae(e){return e===void 0?!1:Yc(e)&&e.browserCachedNew===!0}function Jc(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:dt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function zs(e=Wt()){try{const t=e?.getItem(fs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Xc(s)):[]}catch{return[]}}function Fs(e,t=Wt()){try{e.length===0?t?.removeItem(fs):t?.setItem(fs,JSON.stringify(e))}catch{}}function Xc(e){if(!ed(e))return[];const t=it(e,"id"),i=it(e,"path"),s=it(e,"cwd"),o=it(e,"created"),r=it(e,"modified"),n=it(e,"firstMessage"),a=td(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=qi(e,"name"),p=qi(e,"parentSessionPath"),u=qi(e,"machineId")??dt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Yc(e){return Qc in e}function ed(e){return typeof e=="object"&&e!==null}function it(e,t){const i=e[t];return typeof i=="string"?i:void 0}function qi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function td(e,t){const i=e[t];return typeof i=="number"?i:void 0}function id(e){return bd(e.flatMap(Bs)).filter(t=>t.parts.length>0)}function $e(e,t){return{role:e,parts:[{type:"text",text:t}]}}function mt(e,t){const i=dd(t);return i===void 0?e:{...e,meta:i}}function sd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,$e(t,i)]}function od(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Bs(e){if(nd(e))return[e];if(_(e,"role")==="bashExecution")return[mt(ud(e),e)];const t=fd(_(e,"role")),i=gd(ue(e,"content"),e),s=t==="user"?ad(i):void 0;if(s!==void 0)return s.map(p=>mt(p,e));const o=cd(e);if(t==="tool")return[mt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[mt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=rd(e);return c===void 0?a:[...a,mt(c,e)]}function rd(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return $e("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function nd(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ue(e,"parts"))}function ad(e){if(e.length!==1||e[0]?.type!=="text")return;const t=ld(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function ld(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function cd(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function dd(e){const t=pd(ue(e,"timestamp")),i=hd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function pd(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function hd(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function ud(e){const t=_(e,"command")??"",i=Yt(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ue(e,"output");s!=null&&i.push("",ci(s));const o=ue(e,"exitCode");o!=null&&i.push("",`exit ${ci(o)}`),Yt(e,"cancelled")===!0&&i.push("","cancelled"),Yt(e,"truncated")===!0&&i.push("","output truncated");const r=_(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
-
`)}]}}function
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Bv8l_MFi.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BZKsaE9s.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as xo,w as nt,J as qi,R as La,S as ja,G as Na,U as za,V as Fa,A as Ba,W as Ua,X as Ha,Y as qa,Z as ko,x as $o,_ as Ka}from"./vendor-editor-core-Bc1A7SO7.js";import{m as Va,i as Ga,d as Qa}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const si=globalThis,Ls=si.ShadowRoot&&(si.ShadyCSS===void 0||si.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,js=Symbol(),Po=new WeakMap;let rn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==js)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(Ls&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Po.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Po.set(i,t))}return t}toString(){return this.cssText}};const Za=e=>new rn(typeof e=="string"?e:e+"",void 0,js),O=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(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.")})(o)+e[r+1],e[0]);return new rn(i,e,js)},Ja=(e,t)=>{if(Ls)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=si.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Ro=Ls?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Za(i)})(e):e;const{is:Xa,defineProperty:Ya,getOwnPropertyDescriptor:el,getOwnPropertyNames:tl,getOwnPropertySymbols:il,getPrototypeOf:sl}=Object,Ei=globalThis,Io=Ei.trustedTypes,ol=Io?Io.emptyScript:"",rl=Ei.reactiveElementPolyfillSupport,Et=(e,t)=>e,di={toAttribute(e,t){switch(t){case Boolean:e=e?ol:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Ns=(e,t)=>!Xa(e,t),Co={attribute:!0,type:String,converter:di,reflect:!1,useDefault:!1,hasChanged:Ns};Symbol.metadata??=Symbol("metadata"),Ei.litPropertyMetadata??=new WeakMap;let dt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=Co){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Ya(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=el(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Co}static _$Ei(){if(this.hasOwnProperty(Et("elementProperties")))return;const t=sl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Et("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Et("properties"))){const i=this.properties,s=[...tl(i),...il(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(Ro(o))}else t!==void 0&&i.push(Ro(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ja(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:di).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:di;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ns)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};dt.elementStyles=[],dt.shadowRootOptions={mode:"open"},dt[Et("elementProperties")]=new Map,dt[Et("finalized")]=new Map,rl?.({ReactiveElement:dt}),(Ei.reactiveElementVersions??=[]).push("2.1.2");const zs=globalThis,Mo=e=>e,pi=zs.trustedTypes,Ao=pi?pi.createPolicy("lit-html",{createHTML:e=>e}):void 0,nn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,an="?"+Be,nl=`<${an}>`,Xe=document,Wt=()=>Xe.createComment(""),_t=e=>e===null||typeof e!="object"&&typeof e!="function",Fs=Array.isArray,al=e=>Fs(e)||typeof e?.[Symbol.iterator]=="function",Ki=`[
|
|
3
|
+
\f\r]`,St=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,To=/-->/g,Eo=/>/g,qe=RegExp(`>|${Ki}(?:([^\\s"'>=/]+)(${Ki}*=${Ki}*(?:[^
|
|
4
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Do=/'/g,Wo=/"/g,ln=/^(?:script|style|textarea|title)$/i,cn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=cn(1),he=cn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),_o=new WeakMap,Qe=Xe.createTreeWalker(Xe,129);function dn(e,t){if(!Fs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ao!==void 0?Ao.createHTML(t):t}const ll=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=St;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===St?u[1]==="!--"?n=To:u[1]!==void 0?n=Eo:u[2]!==void 0?(ln.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??St,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?Wo:Do):n===Wo||n===Do?n=qe:n===To||n===Eo?n=St:(n=qe,o=void 0);const v=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===St?c+nl:h>=0?(s.push(p),c.slice(0,h)+nn+c.slice(h)+Be+v):c+Be+(h===-2?a:v)}return[dn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ot{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=ll(t,i);if(this.el=Ot.createElement(p,s),Qe.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Qe.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(nn)){const f=u[n++],v=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:v,ctor:P[1]==="."?dl:P[1]==="?"?pl:P[1]==="@"?hl:Di}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(ln.test(o.tagName)){const h=o.textContent.split(Be),f=h.length-1;if(f>0){o.textContent=pi?pi.emptyScript:"";for(let v=0;v<f;v++)o.append(h[v],Wt()),Qe.nextNode(),c.push({type:2,index:++r});o.append(h[f],Wt())}}}else if(o.nodeType===8)if(o.data===an)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Xe.createElement("template");return s.innerHTML=t,s}}function ft(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=_t(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ft(e,o._$AS(e,t.values),o,s)),t}class cl{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Xe).importNode(i,!0);Qe.currentNode=o;let r=Qe.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new mt(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new ul(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Qe.nextNode(),n++)}return Qe.currentNode=Xe,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class mt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ft(this,t,i),_t(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):al(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&_t(this._$AH)?this._$AA.nextSibling.data=t:this.T(Xe.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ot.createElement(dn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new cl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=_o.get(t.strings);return i===void 0&&_o.set(t.strings,i=new Ot(t)),i}k(t){Fs(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new mt(this.O(Wt()),this.O(Wt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Mo(t).nextSibling;Mo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Di=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=ft(this,t,i,0),n=!_t(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=ft(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!_t(p)||p!==this._$AH[c],p===F?t=F:t!==F&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},dl=class extends Di{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},pl=class extends Di{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},hl=class extends Di{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=ft(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},ul=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){ft(this,t)}};const fl={I:mt},gl=zs.litHtmlPolyfillSupport;gl?.(Ot,mt),(zs.litHtmlVersions??=[]).push("3.3.3");const ml=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new mt(t.insertBefore(Wt(),r),r,void 0,i??{})}return o._$AI(e),o};const Bs=globalThis;let C=class extends dt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=ml(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};C._$litElement$=!0,C.finalized=!0,Bs.litElementHydrateSupport?.({LitElement:C});const vl=Bs.litElementPolyfillSupport;vl?.({LitElement:C});(Bs.litElementVersions??=[]).push("4.2.2");const D=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const bl={attribute:!0,type:String,converter:di,reflect:!1,hasChanged:Ns},wl=(e=bl,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?wl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const yl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return yl(i,s,{get(){return r(this)}})}}async function S(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(e,{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Sl(n)??o.statusText)}const r=await o.json();return t(r)}function Sl(e){if(xl(e))return typeof e.error=="string"?e.error:void 0}function xl(e){return typeof e=="object"&&e!==null}const Ze={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},kl=Object.values(Ze),$l=new Set(kl);function Pl(e){return typeof e=="string"&&$l.has(e)}function ht(e,t){return e?.capabilities?.includes(t)===!0}function ut(e){return typeof e=="object"&&e!==null}function y(e){if(!ut(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function le(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Rl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Il(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Cl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:Rl(t.messages),start:le(t,"start"),total:le(t,"total")}}function Ml(e){const t=y(e);return N(pn)(t.machines)}function pn(e){const t=y(e),i=El(t,"kind"),s=$(t,"baseUrl"),o=hn(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Al(e){const t=y(e),i=hn(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:hi(t.web)},...t.sessiond===void 0?{}:{sessiond:hi(t.sessiond)},...s===void 0?{}:{error:s}}}function Tl(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:fn(t.components)},...t.capabilities===void 0?{}:{capabilities:Us(t.capabilities)},...i===void 0?{}:{error:i}}}function El(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function hn(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Oo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Dl(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function ms(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:le(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function xt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:le(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Wl)(t.queuedMessages),...b("messageCount",Pe(t,"messageCount")),tokens:_l(t.tokens),cost:le(t,"cost"),...Ol(t.model),...Ql(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Wl(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function _l(e){const t=y(e);return{input:le(t,"input"),output:le(t,"output"),cacheRead:le(t,"cacheRead"),cacheWrite:le(t,"cacheWrite"),total:le(t,"total")}}function un(e){const t=y(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",Pe(t,"contextWindow")),...b("reasoning",t.reasoning)}}function Ol(e){return e===void 0?{}:{model:un(e)}}function Ll(e){const t=y(e);return{models:N(un)(t.models)}}function jl(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Nl(e){const t=y(e);return{levels:N(jl)(t.levels)}}function zl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Fl(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Bl(e){const t=y(e),i=t.source===void 0?void 0:Fl(t.source);return{configured:E(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function Ul(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:zl(t.authType),status:Bl(t.status)}}function Hl(e){const t=y(e);return{providers:N(Ul)(t.providers)}}function Vt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:ql(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Kl(t.auth)),...b("prompt",Vl(t.prompt)),...b("select",Gl(t.select))}}function ql(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Kl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function Vl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Gl(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(mn)(t.options)}}function Ql(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Ho(t,"tokens"),contextWindow:le(t,"contextWindow"),percent:Ho(t,"percent")}}}function Zl(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...b("description",$(t,"description"))}}function vs(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Jl(e){const t=y(e);return{path:m(t,"path"),entries:N(Xl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function Xl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...b("size",Pe(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function Yl(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",ec(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:le(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function ec(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function tc(e){const t=y(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",Pe(t,"ahead")),...b("behind",Pe(t,"behind")),files:N(ic)(t.files)}}function ic(e){const t=y(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Lo(t.index),workingTree:Lo(t.workingTree)}}function Lo(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function sc(e){const t=y(e);return{...b("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Vi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...b("exitCode",Pe(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Dt(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:oc(t.status),...b("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:rc(t.metadata,"metadata")}}function oc(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function rc(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function nc(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ac(e){const t=y(e);return{workspaces:N(nc)(t.workspaces),generatedAt:m(t,"generatedAt")}}function jo(e){const t=y(e);return{path:m(t,"path"),exists:E(t,"exists"),config:No(t.config),effectiveConfig:No(t.effectiveConfig),envOverrides:gc(t.envOverrides)}}function No(e){const t=y(e);return{...b("host",$(t,"host")),...b("port",Pe(t,"port")),...b("allowedHosts",lc(t.allowedHosts)),...b("shortcuts",uc(t.shortcuts)),...b("plugins",fc(t.plugins)),...b("pathAccess",cc(t.pathAccess)),...b("maxUploadBytes",Pe(t,"maxUploadBytes")),...b("spawnSessions",Uo(t,"spawnSessions")),...b("subsessions",Uo(t,"subsessions"))}}function lc(e){if(e!==void 0){if(e===!0)return!0;if(pc(e))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function cc(e){if(e===void 0)return;if(!ut(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",dc(t,"pathAccess.allowedPaths"))}}function dc(e,t){if(e!==void 0){if(hc(e))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function pc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function hc(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}function uc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function fc(e){if(e!==void 0){if(!ut(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!ut(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!ut(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function gc(e){const t=y(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function mc(e){const t=y(e);return{plugins:N(vc)(t.plugins)}}function vc(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:bc(t.scope),machineSpecific:wc(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function bc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function wc(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function yc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:xc(t.components),release:$c(t.release),commands:Pc(t.commands),messages:N(Rc)(t.messages)}}function Sc(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fn(t.components),capabilities:Us(t.capabilities)}}function xc(e){const t=y(e);return{web:hi(t.web),sessiond:hi(t.sessiond)}}function fn(e){const t=y(e);return{web:zo(t.web),sessiond:zo(t.sessiond)}}function zo(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Us(t.capabilities),...b("error",$(t,"error"))}}function hi(e){const t=y(e);return{component:gn(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...b("installation",kc(t.installation)),...b("error",$(t,"error"))}}function kc(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function $c(e){const t=y(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function Pc(e){const t=y(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function Rc(e){const t=y(e);return{id:m(t,"id"),severity:Ic(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function gn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Us(e){if(!Array.isArray(e)||!e.every(Pl))throw new Error("Invalid PI WEB capabilities");return e}function Ic(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Fo(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(mn)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...Cc(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function mn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function Cc(e){return e===void 0?{}:{session:ms(e)}}function Gt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Mc(e){const t=y(e);return N(Ac)(t.attachments)}function Ac(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:le(t,"size")}}function bs(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Tc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Ec(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Bo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Il(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Dc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Wc(e){if(y(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function _c(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Oc(e){if(y(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Uo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Ho(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function b(e,t){return t===void 0?{}:{[e]:t}}function Lc(e){return typeof e=="string"?e:e.id}function jc(e){return typeof e=="string"?void 0:e.cwd}function Nc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function zc(e,t,i="local"){const s=new URLSearchParams,o=jc(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Lc(e))}/messages${r===""?"":`?${r}`}`}function Fc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}const A=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Bc(e){return typeof e=="string"?e:e.id}function vn(e){return typeof e=="string"?void 0:e.cwd}function bn(e,t="local"){return`${A(t)}/sessions/${encodeURIComponent(Bc(e))}`}function V(e,t,i="local"){return`${bn(e,i)}/${t}`}function Qt(e,t,i="local"){return`${V(e,t,i)}${wn(e)}`}function Uc(e,t="local"){return`${bn(e,t)}${wn(e)}`}function wn(e){const t=vn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=vn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const yn={piWebStatus:(e="local")=>S(e==="local"?"/api/pi-web/status":`${A(e)}/pi-web/status`,yc),piWebRuntime:()=>S("/api/pi-web/runtime",Sc)},Hc={machines:()=>S("/api/machines",Ml),addMachine:e=>S("/api/machines",pn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>S(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>S(`/api/machines/${encodeURIComponent(e)}/health`,Al),runtime:e=>S(`/api/machines/${encodeURIComponent(e)}/runtime`,Tl)},ui={config:()=>S("/api/config",jo),saveConfig:e=>S("/api/config",jo,{method:"PUT",body:JSON.stringify({config:e})})},ws={plugins:()=>S("/api/plugins",mc)},Sn={workspaceActivity:(e="local")=>S(`${A(e)}/activity`,ac)},qc={projects:(e="local")=>S(`${A(e)}/projects`,N(Oo)),addProject:(e,t,i,s="local")=>S(`${A(s)}/projects`,Oo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>S(`${A(t)}/projects/${encodeURIComponent(e)}`,bs,{method:"DELETE"}),projectDirectories:(e,t="local")=>S(`${A(t)}/project-directories?q=${encodeURIComponent(e)}`,N(vs))},ys={workspaces:(e,t="local")=>S(`${A(t)}/projects/${e}/workspaces`,N(Dl)),deleteWorkspace:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Dt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Jl),workspaceFile:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Yl)},Kc={sessions:(e,t="local")=>S(`${A(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(ms)),startSession:(e,t="local")=>S(`${A(t)}/sessions`,ms,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>S(zc(e,t,i),Cl),status:(e,t="local")=>S(Qt(e,"status",t),xt),models:(e,t="local")=>S(Qt(e,"models",t),Ll),setModel:(e,t,i,s="local")=>S(V(e,"model",s),xt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>S(V(e,"model/cycle",i),xt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>S(Qt(e,"thinking-levels",t),Nl),setThinkingLevel:(e,t,i="local")=>S(V(e,"thinking-level",i),xt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>S(V(e,"thinking-level/cycle",t),xt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>S(Qt(e,"commands",t),N(Zl)),prompt:(e,t,i,s="local",o)=>S(V(e,"prompt",s),Gt,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>S(V(e,"attachments",i),Mc,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>S(V(e,"shell",i),Gt,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>S(V(e,"commands/run",i),Fo,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>S(V(e,"commands/respond",s),Fo,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>S(V(e,"abort",t),Tc,{method:"POST",body:Q(e)}),stop:(e,t="local")=>S(V(e,"stop",t),Ec,{method:"POST",body:Q(e)}),archive:(e,t="local")=>S(V(e,"archive",t),Bo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>S(V(e,"archive-tree",t),Bo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>S(V(e,"restore",t),Dc,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>S(Uc(e,t),Wc,{method:"DELETE"}),detachParent:(e,t="local")=>S(V(e,"detach-parent",t),_c,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>S(V(e,"reload",t),Oc,{method:"POST",body:Q(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return S(`${A(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Hl)},saveApiKey:(e,t,i="local")=>S(`${A(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>S(`${A(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>S(`${A(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>S(`${A(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>S(`${A(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},pt={terminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Vi)),startTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Vi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,bs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,bs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>S(`${A(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Vi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Dt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>S(`${A(t)}/terminal-command-runs${Gc(e)}`,N(Dt)),getCommandRun:(e,t="local")=>Vc(e,t),cancelCommandRun:(e,t="local")=>S(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Dt,{method:"POST"})};async function Vc(e,t){const i=await fetch(`${A(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Qc(s)??i.statusText)}return Dt(await i.json())}}function Gc(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Qc(e){if(!Zc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Zc(e){return typeof e=="object"&&e!==null}const Jc={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?S(`${A(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,N(vs)):(s.set("cwd",e),S(`${A(i.machineId)}/files?${s.toString()}`,N(vs)))}},Xc={gitStatus:(e,t,i="local")=>S(`${A(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,tc),gitDiff:(e,t,i,s="local")=>S(Nc(s,e,t,i),sc)},j={...yn,...Hc,...ui,...ws,...Sn,...qc,...ys,...Kc,...pt,...Jc,...Xc};function Yc(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${qs()}${Hs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function $w(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${qs()}${Hs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function ed(e="local"){return new WebSocket(`${qs()}${Hs(e)}/events`)}function Hs(e){return`/api/machines/${encodeURIComponent(e)}`}function qs(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function oi(){return{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,selectedTerminalId:void 0,error:""}}function td(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ye(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function xn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const kn="local";function Gi(e,t){return`${e}:${t}`}function $n(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??kn}class id{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Sn}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,sd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=od(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function sd(e){const t={};for(const i of e.workspaces)xn(i)&&(t[i.cwd]=i);return t}function od(e,t){const i={...e};return xn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class rd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??j,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=nd(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function nd(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Nt(e){return e.replaceAll(":",".")}function ad(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Qi(e,t){const i=ad(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function xe(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));ld(o,s)}function ld(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const qo=Nt("core:workspace.files");class cd{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await j.workspaceTree(t.id,i.id,"",s),r={...this.getState().expandedDirs};await Promise.all(Object.keys(r).map(async n=>{r[n]=(await j.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:o.entries,expandedDirs:r,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:pd(this.getState().expandedDirs,t)});return}try{const o=await j.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),xe(qo,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await j.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(dd(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),xe(qo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}}function dd(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function pd(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Ko=Nt("core:workspace.git");class hd{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await j.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),xe(Ko,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),xe(Ko,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([j.gitDiff(i.id,s.id,{path:t},g(this.getState())),j.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class ud{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await j.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Vo(this.getState().machineActivities,o),machineRuntimes:Vo(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...oi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await j.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await j.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Zi(this.getState().machineStatuses,t.id),machineRuntimes:Zi(this.getState().machineRuntimes,t.id),machineActivities:Zi(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await j.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await j.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>j.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>j.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Zi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Vo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class fd{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await j.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await j.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await j.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Ss="pi-web:cached-new-sessions:v1",gd="browserCachedNew",vt="local";function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Go(e,t=vt,i=zt()){if(e.messageCount!==0||e.archived===!0)return;const s=Ks(i).filter(o=>o.id!==e.id||o.machineId!==t);Vs([xs(e,t),...s],i)}function xs(e,t=vt){return{...e,browserCachedNew:!0,machineId:t}}function Qo(e,t=vt,i=zt()){const s=Ks(i).filter(o=>o.id!==e||o.machineId!==t);Vs(s,i)}function md(e,t,i=vt,s=zt()){const o=new Set(t.map(c=>c.id)),r=Ks(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Vs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ee(e){return e===void 0?!1:wd(e)&&e.browserCachedNew===!0}function vd(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:vt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ks(e=zt()){try{const t=e?.getItem(Ss);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>bd(s)):[]}catch{return[]}}function Vs(e,t=zt()){try{e.length===0?t?.removeItem(Ss):t?.setItem(Ss,JSON.stringify(e))}catch{}}function bd(e){if(!yd(e))return[];const t=at(e,"id"),i=at(e,"path"),s=at(e,"cwd"),o=at(e,"created"),r=at(e,"modified"),n=at(e,"firstMessage"),a=Sd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Ji(e,"name"),p=Ji(e,"parentSessionPath"),u=Ji(e,"machineId")??vt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function wd(e){return gd in e}function yd(e){return typeof e=="object"&&e!==null}function at(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ji(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Sd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function xd(e){return jd(e.flatMap(Gs)).filter(t=>t.parts.length>0)}function Te(e,t){return{role:e,parts:[{type:"text",text:t}]}}function kt(e,t){const i=Ad(t);return i===void 0?e:{...e,meta:i}}function kd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Te(t,i)]}function $d(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Gs(e){if(Rd(e))return[e];if(W(e,"role")==="bashExecution")return[kt(Dd(e),e)];const t=Wd(W(e,"role")),i=_d(fe(e,"content"),e),s=t==="user"?Id(i):void 0;if(s!==void 0)return s.map(p=>kt(p,e));const o=Md(e);if(t==="tool")return[kt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[kt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Pd(e);return c===void 0?a:[...a,kt(c,e)]}function Pd(e){if(W(e,"role")!=="assistant"||W(e,"stopReason")!=="error")return;const t=W(e,"errorMessage")?.trim();return Te("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Rd(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Id(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Cd(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Cd(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Md(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ad(e){const t=Td(fe(e,"timestamp")),i=Ed(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Td(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Ed(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Dd(e){const t=W(e,"command")??"",i=ri(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",gi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${gi(o)}`),ri(e,"cancelled")===!0&&i.push("","cancelled"),ri(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
+
`)}]}}function Wd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function _d(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=W(i,"type"),o=W(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=W(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=W(i,"name")??"tool",n=fe(i,"arguments"),a=W(i,"id"),c=r==="read"?Ld(W(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:Ft(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=W(i,"data"),n=W(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return Zo(i)}).map(i=>i.type==="text"&&W(t,"role")==="toolResult"?Od(i.text,t):i):Zo(e)}function Od(e,t){const i=W(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:W(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ri(t,"isError")===!0}}function Ld(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function jd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Nd(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&zd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function Nd(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function zd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=fi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function fi(e){const t=fe(e,"preview");if(!Qs(t))return;const i=W(t,"diff"),s=W(t,"error"),o=Bd(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Zo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Ft(e)}]:[{type:"text",text:gi(e)}]}function Ft(e){if(!Qs(e))return gi(e);const t=W(e,"command");if(t!==void 0)return t;const i=W(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${Fd(n)}`).join(" · ")}function Fd(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function Qs(e){return typeof e=="object"&&e!==null}function fe(e,t){return Qs(e)?e[t]:void 0}function W(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function ri(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function Bd(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function gi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Ud="pi-web:prompt-draft:";function mi(e){return`${Ud}${e}`}function Wi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Pn(e,t=Wi()){try{return t?.getItem(mi(e))??""}catch{return""}}function vi(e,t,i=Wi()){try{t?i?.setItem(mi(e),t):i?.removeItem(mi(e))}catch{}}function Zs(e,t=Wi()){try{t?.removeItem(mi(e))}catch{}}function Hd(e,t,i=Wi()){const s=Pn(e,i);s!==""&&(vi(t,s,i),Zs(e,i))}function qd(e,t){return Te("bash",`${t===!0?`excluded from context
|
|
6
6
|
|
|
7
|
-
`:""}$ ${e}`)}function
|
|
7
|
+
`:""}$ ${e}`)}function Kd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Te("bash",t)];const o=Gd(s.text)?"":`
|
|
8
8
|
|
|
9
|
-
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function
|
|
9
|
+
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function Vd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
|
|
10
10
|
|
|
11
11
|
`)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash command failed"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`full output: ${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
|
|
12
12
|
|
|
13
13
|
${o.join(`
|
|
14
|
-
`)}`}]}]}function
|
|
14
|
+
`)}`}]}]}function Gd(e){const t=e.lastIndexOf(`
|
|
15
15
|
|
|
16
|
-
`),i=e.lastIndexOf("$ ");return t>i}function
|
|
17
|
-
`);if(typeof e=="object"&&e!==null){const t=
|
|
16
|
+
`),i=e.lastIndexOf("$ ");return t>i}function Qd(e,t){if(t.type==="message.append")return cp(e,t.message);if(t.type==="assistant.delta")return kd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return $d(e,t.text);if(t.type==="tool.start")return ep(e,t);if(t.type==="tool.update")return In(e,t.toolCallId,i=>tp(i,t));if(t.type==="tool.end")return Rn(e,t.toolCallId,t.toolName,Ft(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,qd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Kd(e,t.chunk);if(t.type==="shell.end")return Vd(e,t);if(t.type==="command.output")return[...e,Te(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Te("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Zd(e,t.message)}function Zd(e,t){const i=ip(t);if(i!==void 0)return Rn(e,i.toolCallId,i.toolName,Ft(i.content),i.text,i.isError,i.content,i.details);const s=Gs(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Xd(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>Jd(r,n),e)}function Jd(e,t){const i=sp(e,t);if(i.length>0)return op(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||lp(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Xd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Yd(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function ep(e,t){const i=t.toolName==="read"?Yd(Je(t.args,"path")):void 0;if(i!==void 0)return dp(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Ft(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function tp(e,t){const i=fi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Rn(e,t,i,s,o,r,n,a){const c=In(e,t,h=>{const f=fi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=fi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function In(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function ip(e){if(Je(e,"role")!=="toolResult")return;const t=Je(e,"toolCallId"),i=wi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Je(e,"toolName")??"tool",text:Cn(i),isError:fp(e,"isError")===!0,content:i,details:wi(e,"details")}}function Cn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Cn).filter(t=>t!=="").join(`
|
|
17
|
+
`);if(typeof e=="object"&&e!==null){const t=Je(e,"text")??Je(e,"content")??Je(e,"output");if(t!==void 0)return t}return""}function sp(e,t){const i=bi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=An(e)+1;for(let n=e.length-1;n>=r;n--){const a=bi(e[n]);if(a.length===0)continue;const c=o-a.length;if(!(c<0)&&ap(a,i.slice(c,o))&&(s.unshift(n),o=c,o===0))return s}return[]}function op(e,t,i){const s=rp(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const c=e[a];c!==void 0&&!r.has(a)&&n.push(c)}return n}function rp(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return np(e[o])?[o,...t]:t}function np(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function bi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function ap(e,t){return e.length===t.length&&e.every((i,s)=>Mn(i,t[s]))}function Mn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Jo(e.path)===Jo(t.path)||e.name===t.name}function Jo(e){return e.replace(/\\/g,"/")}function lp(e,t){return Xo(e)===Xo(t)}function Xo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
18
18
|
|
|
19
|
-
`)}function
|
|
20
|
-
`))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function
|
|
21
|
-
`)+1,s=e.slice(i),o=
|
|
22
|
-
`))+1;return e.slice(t)}class ap{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Pn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Dc(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await $n(t);lp(i)&&this.onEvent?.(i)}}class Qo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Pn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Wc(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await $n(t);dp(i)&&this.onEvent?.(i)}}function lp(e){const t=Ks(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","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(t)}function cp(e){const t=Ks(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function dp(e){const t=Ks(e);return cp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Ks(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function $n(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Pn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Ot(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Mi{constructor(t,i,s=Ot()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of pp(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Vs(e){return typeof e=="string"&&e!==""?e:void 0}function pp(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!hp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function hp(e){return!up(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function up(e){return typeof e=="object"&&e!==null}class fp{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const gp="pi-web:session-selection:v1";class mp{constructor(t=Ot()){this.sessionIdsByCwd=new Mi(gp,Vs,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function vp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return wp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function bp(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function wp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function yp(e,t,i){return bs(e,[t],i)}function bs(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Sp(e,t,i){return ws(e,t,[i])}function ws(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const vt=100;class xp{constructor(t,i,s,o=new fp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new ap,this.api=r.api??O,this.transcripts=r.transcripts??new ep}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();bp(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Fo(s,i);const o=gs(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return vp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t,{limit:vt},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:vt},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ae(t)&&Ap(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:vt},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(rp(t))return this.runShell(t);const o=this.getState().selectedSession;if(!(!o||o.archived===!0))try{await this.api.prompt(o,t,i,g(this.getState())),this.markCachedNewSessionPersisted(o)}catch(r){this.setState({error:String(r)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,$e("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,$e("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,$e("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ae(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=yp(i.sessions,t.id,new Date().toISOString()),o=Sp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ae(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=bs(o.sessions,s,new Date().toISOString()),n=ws(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=Zo(t).filter(n=>n.archived!==!0&&!ae(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=Jo(o);if(r.length>0){const n=this.getState(),a=bs(n.sessions,r,new Date().toISOString()),c=ws(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=Zo(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!tn(o,Os.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=Jo(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ae(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Bo(t.id,g(this.getState())),Hs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:vt},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=$p(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return vn(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);Fo(o,s),$d(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Bo(t.id,s);const r=gs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!ae(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Jc(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,$e(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&pi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ci(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Ip(i,t.sessionId,t.messageCount),...s?{sessionActivities:kp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!t.isStreaming&&this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(Mp(t))return}if(Tp(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:vt},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function kp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zo(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function Jo(e){return e.filter(Pp).map(t=>t.value)}function $p(e){return e.filter(Rp).map(t=>Cp(t.reason))}function Pp(e){return e.status==="fulfilled"}function Rp(e){return e.status==="rejected"}function Cp(e){return e instanceof Error?e.message:String(e)}function Ip(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function Mp(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function Tp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Ap(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ep{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const Dp="pi-web:workspace-selection:v1";class Wp{constructor(t=Ot()){this.workspaceIdsByProject=new Mi(Dp,Vs,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function _p(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Op{constructor(t,i,s,o,r=new Ep,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??O}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Xt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Bi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Xt()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=_p(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Bi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Bi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Xt()});try{const o=Zc(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=jp(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Lp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function jp(e){return e.find(t=>t.isMain)??e[0]}const Np="pi-web:machine-navigation:v1";class zp{constructor(t=Ot()){this.snapshotsByMachine=new Mi(Np,Bp,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?er(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,er(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Fp(e){return{machineId:e,surface:{}}}function Xo(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??mn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function Yo(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function er(e){return{...e,surface:{...e.surface}}}function Bp(e){if(!Cn(e))return;const t=We(e,"machineId");if(t===void 0)return;const i=Rn(We(e,"tool")),s=Hp(We(e,"view"));return{machineId:t,projectId:We(e,"projectId"),workspaceId:We(e,"workspaceId"),sessionId:We(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Up(e.surface)}}function Up(e){return Cn(e)?{selectedFilePath:We(e,"selectedFilePath"),selectedDiffPath:We(e,"selectedDiffPath"),selectedTerminalId:We(e,"selectedTerminalId")}:{}}function Hp(e){return e==="navigation"||e==="chat"?e:Rn(e)}function Rn(e){return qp(e)?e:void 0}function qp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function We(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Cn(e){return typeof e=="object"&&e!==null}const Kp="pi-web:terminal-selection:v1";class Vp{constructor(t=Ot()){this.terminalIdsByCwd=new Mi(Kp,Vs,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Tb(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Ab(e){return e.find(t=>!t.exited)??e[0]}const In=1200,Gp=["mod","alt","shift"];class Qp{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Tn(t);if(o===void 0)return!1;const r=Gs(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!At(o))return!1}else if(!At(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>rh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>Qs(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},In)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Gs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Zp(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(ys)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Yp),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=eh(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:tr(u),v=h?[...a.get(p)??[]].sort(ys).map(tr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Ki(e){return An(e,{requireFirstChordActivator:!0})}function Mn(e){const t=An(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ei(e){return Mn(e).map(t=>t.split("+").map(Dn).join("+")).join(" ")}function Tn(e){if(e.isComposing)return;const t=sh(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function At(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Zp(e,t,i){const s=Jp(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Mn(o),n=r[0];if(!(n===void 0||!At(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Xp(r),order:i}}function Jp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Xp(e){return e.join("\0")}function tr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ys(e,t){return ir(e.source)-ir(t.source)||sr(e.action.id,t.action.id)||sr(e.action.title,t.action.title)||e.order-t.order}function Yp(e,t){return e.tokens.length-t.tokens.length||ys(e,t)}function eh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Qs(e.tokens,i.tokens))}function ir(e){switch(e){case"custom":return 0;case"default":return 1}}function sr(e,t){return e<t?-1:e>t?1:0}function An(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=th(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!At(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function th(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=ih(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Dn(n)} modifiers.`};i.add(n);continue}const a=En(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...Gp.filter(r=>i.has(r)),s].join("+")}}function ih(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function En(e){const t=oh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function sh(e){if(e===" ")return"space";const t=e.toLowerCase();return En(t)}function oh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Dn(e){return e==="mod"?or()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?or()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function rh(e,t){return e.length===t.length&&Qs(e,t)}function Qs(e,t){return t.every((i,s)=>e[s]===i)}function or(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Zs="themes:classic",nh="themes:pi-web-dark",ah={themeId:nh,auto:!0},Wn="pi-web-app-theme",lh=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],ch=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function dh(){try{const e=window.localStorage.getItem(Wn);return e===null?void 0:gh(e)}catch{return}}function ph(e){try{window.localStorage.setItem(Wn,JSON.stringify(e))}catch{}}function hh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of lh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function uh(e){const t=fh(e.themes,e.fallbackThemeId??Zs),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=_n(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function fh(e,t=Zs){return e.find(i=>i.id===t)??e[0]}function _n(e,t){return e.find(i=>i.light===t||i.dark===t)}function gh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return mh(i)?i:void 0}catch{return}}function mh(e){if(!vh(e))return!1;const t=e.themeId,i=e.auto;return bh(t)&&typeof i=="boolean"}function vh(e){return typeof e=="object"&&e!==null}function bh(e){return typeof e=="string"&&ch.test(e)}const wh="workspace.delete",yh="pi.operation",Sh="target.workspaceId";function xh(e){return{...e===void 0?{}:{projectId:e},metadata:{[yh]:wh}}}function kh(e){const t={};for(const i of e){const s=Ss(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function $h(e){return Object.entries(e).filter(([,t])=>fi(t)).map(([t])=>t)}function On(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&fi(i)}function Ss(e){return e.metadata[Sh]}function fi(e){return e.status==="queued"||e.status==="running"}function Ph(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the PI WEB color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:bt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:rr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:bt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:bt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:rr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:bt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Rh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:bt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Ch,run:e=>e.archiveSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Ih,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ci(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function bt(e){return e.state.selectedWorkspace!==void 0}function rr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Rh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!On(e.state,t)}function Ch(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ae(t)}function Ih(e){return ae(e.state.selectedSession)}const Mh="modulepreload",Th=function(e){return"/"+e},nr={},Ln=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Th(p),p in nr)return;nr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Mh,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Ah=10*1024*1024,Eh="10 MB";function Dh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ti(e)}function ti(e){switch(e){case"navigation":return rt`
|
|
19
|
+
`)}function cp(e,t){const i=Gs(t);return i.length===0?e:[...e,...i]}function dp(e,t){const i=e.at(-1);return pp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function pp(e,t){const i=bi(t);if(t.role!=="skill"||i.length===0)return!1;const s=An(e)+1;return i.every(o=>hp(e,o,s))}function hp(e,t,i){for(let s=e.length-1;s>=i;s--)if(bi(e[s]).some(o=>Mn(o,t)))return!0;return!1}function An(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function up(e){return typeof e=="object"&&e!==null}function wi(e,t){return up(e)?e[t]:void 0}function Je(e,t){const i=wi(e,t);return typeof i=="string"?i:void 0}function fp(e,t){const i=wi(e,t);return typeof i=="boolean"?i:void 0}const gp="pi-web:chat-history:v2:",mp=1800*1e3;function vp(e){try{const t=sessionStorage.getItem(yi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!kp(i))return;if(Date.now()-i.savedAt>mp){sessionStorage.removeItem(yi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function bp(e,t){try{sessionStorage.setItem(yi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function wp(e){try{sessionStorage.removeItem(yi(e))}catch{}}function yp(e,t){if(e===void 0||!ks(e))return t;if(!ks(t))return e;if(Sp(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return Yo(o,i,e),Yo(o,i,t),xp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Sp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function xp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Yo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function yi(e){return`${gp}${e}`}function kp(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&ks({messages:t,start:i,total:s})}function ks(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some($p)}function $p(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Pp={read:vp,write:bp,remove:wp};class Rp{constructor(t=Pp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return er(this.rawHistoryPage(t))}mergeHistory(t,i){const s=yp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),er(s)}applyLiveEvent(t,i){return Qd(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function er(e){const t=e?.start??0;return{messages:xd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Tn(e,t=e.length){const i=e.slice(0,t),s=Ip(i,t);if(s!==void 0)return s;const o=Cp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
|
|
20
|
+
`))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function En(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Ip(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Cp(e,t){const i=e.lastIndexOf(`
|
|
21
|
+
`)+1,s=e.slice(i),o=tr(s,"@ "),r=tr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function tr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Mp(e[i-1]))return i;return-1}function Mp(e){return e===" "||e===" "}function Js(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Tp(e).startsWith("/")?{kind:"command"}:Tn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Ap(e){return Js(e).kind==="shell"}function Tp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
22
|
+
`))+1;return e.slice(t)}class Ep{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Wn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Yc(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Dn(t);Dp(i)&&this.onEvent?.(i)}}class ir{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Wn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=ed(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Dn(t);_p(i)&&this.onEvent?.(i)}}function Dp(e){const t=Xs(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function Wp(e){const t=Xs(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function _p(e){const t=Xs(e);return Wp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Xs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Dn(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Wn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Bt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class _i{constructor(t,i,s=Bt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of Op(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Ys(e){return typeof e=="string"&&e!==""?e:void 0}function Op(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!Lp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function Lp(e){return!jp(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function jp(e){return typeof e=="object"&&e!==null}class Np{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const zp="pi-web:session-selection:v1";class Fp{constructor(t=Bt()){this.sessionIdsByCwd=new _i(zp,Ys,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Bp(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Hp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function Up(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Hp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function qp(e,t,i){return $s(e,[t],i)}function $s(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function Kp(e,t,i){return Ps(e,t,[i])}function Ps(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const $t=100;class Vp{constructor(t,i,s,o=new Np,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Ep,this.api=r.api??j,this.transcripts=r.transcripts??new Rp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Up(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);Go(s,i);const o=xs(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Bp(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:$t},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:$t},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ee(t)&&ih(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Ap(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=g(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(v=>En(v.path,!1)).join(" "),f=t===""?h:`${t}
|
|
23
|
+
|
|
24
|
+
${h}`;await this.api.prompt(a,f,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:_n(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Te("user",t)]});try{await this.api.shell(i,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Te("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Te("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,g(this.getState()));const i=this.getState(),s=qp(i.sessions,t.id,new Date().toISOString()),o=Kp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ee(t)))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=$s(o.sessions,s,new Date().toISOString()),n=Ps(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=sr(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=g(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=or(o);if(r.length>0){const n=this.getState(),a=$s(n.sessions,r,new Date().toISOString()),c=Ps(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=sr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=g(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!ht(o,Ze.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=or(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,g(this.getState())).catch(()=>{}),Qo(t.id,g(this.getState())),Zs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||ee(t)||t.archived===!0)return;const i=g(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!ht(s,Ze.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:$t},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=Qp(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return $n(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);Go(o,s),Hd(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),Qo(t.id,s);const r=xs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(vd(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Te(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&vi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ye(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Yp(i,t.sessionId,t.messageCount),...s?{sessionActivities:Gp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(eh(t))return}if(th(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:$t},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Gp(e,t){return _n(e,t)}function _n(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function sr(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function or(e){return e.filter(Zp).map(t=>t.value)}function Qp(e){return e.filter(Jp).map(t=>Xp(t.reason))}function Zp(e){return e.status==="fulfilled"}function Jp(e){return e.status==="rejected"}function Xp(e){return e instanceof Error?e.message:String(e)}function Yp(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function eh(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function th(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function ih(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class sh{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const oh="pi-web:workspace-selection:v1";class rh{constructor(t=Bt()){this.workspaceIdsByProject=new _i(oh,Ys,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function nh(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class ah{constructor(t,i,s,o,r=new sh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??j}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...oi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Gi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...oi()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=nh(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Gi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Gi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...oi()});try{const o=md(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=ch(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function lh(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function ch(e){return e.find(t=>t.isMain)??e[0]}const dh="pi-web:machine-navigation:v1";class ph{constructor(t=Bt()){this.snapshotsByMachine=new _i(dh,uh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?ar(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,ar(t))}forget(t){this.snapshotsByMachine.delete(t)}}function hh(e){return{machineId:e,surface:{}}}function rr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??kn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function nr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function ar(e){return{...e,surface:{...e.surface}}}function uh(e){if(!Ln(e))return;const t=Oe(e,"machineId");if(t===void 0)return;const i=On(Oe(e,"tool")),s=gh(Oe(e,"view"));return{machineId:t,projectId:Oe(e,"projectId"),workspaceId:Oe(e,"workspaceId"),sessionId:Oe(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:fh(e.surface)}}function fh(e){return Ln(e)?{selectedFilePath:Oe(e,"selectedFilePath"),selectedDiffPath:Oe(e,"selectedDiffPath"),selectedTerminalId:Oe(e,"selectedTerminalId")}:{}}function gh(e){return e==="navigation"||e==="chat"?e:On(e)}function On(e){return mh(e)?e:void 0}function mh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Oe(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Ln(e){return typeof e=="object"&&e!==null}const vh="pi-web:terminal-selection:v1";class bh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(vh,Ys,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Pw(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Rw(e){return e.find(t=>!t.exited)??e[0]}const jn=1200,wh=["mod","alt","shift"];class yh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=zn(t);if(o===void 0)return!1;const r=eo(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Lt(o))return!1}else if(!Lt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Ah(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>to(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},jn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function eo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Sh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(Rs)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort($h),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Ph(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:lr(u),v=h?[...a.get(p)??[]].sort(Rs).map(lr):[];return{...p,active:h,shadows:v,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Xi(e){return Fn(e,{requireFirstChordActivator:!0})}function Nn(e){const t=Fn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ni(e){return Nn(e).map(t=>t.split("+").map(Un).join("+")).join(" ")}function zn(e){if(e.isComposing)return;const t=Ch(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function Lt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Sh(e,t,i){const s=xh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Nn(o),n=r[0];if(!(n===void 0||!Lt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:kh(r),order:i}}function xh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function kh(e){return e.join("\0")}function lr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Rs(e,t){return cr(e.source)-cr(t.source)||dr(e.action.id,t.action.id)||dr(e.action.title,t.action.title)||e.order-t.order}function $h(e,t){return e.tokens.length-t.tokens.length||Rs(e,t)}function Ph(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&to(e.tokens,i.tokens))}function cr(e){switch(e){case"custom":return 0;case"default":return 1}}function dr(e,t){return e<t?-1:e>t?1:0}function Fn(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Rh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Rh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=Ih(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${Un(n)} modifiers.`};i.add(n);continue}const a=Bn(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...wh.filter(r=>i.has(r)),s].join("+")}}function Ih(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function Bn(e){const t=Mh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Ch(e){if(e===" ")return"space";const t=e.toLowerCase();return Bn(t)}function Mh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Un(e){return e==="mod"?pr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?pr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Ah(e,t){return e.length===t.length&&to(e,t)}function to(e,t){return t.every((i,s)=>e[s]===i)}function pr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const io="themes:classic",Th="themes:pi-web-dark",Eh={themeId:Th,auto:!0},Hn="pi-web-app-theme",Dh=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],Wh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function _h(){try{const e=window.localStorage.getItem(Hn);return e===null?void 0:zh(e)}catch{return}}function Oh(e){try{window.localStorage.setItem(Hn,JSON.stringify(e))}catch{}}function Lh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Dh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function jh(e){const t=Nh(e.themes,e.fallbackThemeId??io),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=qn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function Nh(e,t=io){return e.find(i=>i.id===t)??e[0]}function qn(e,t){return e.find(i=>i.light===t||i.dark===t)}function zh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Fh(i)?i:void 0}catch{return}}function Fh(e){if(!Bh(e))return!1;const t=e.themeId,i=e.auto;return Uh(t)&&typeof i=="boolean"}function Bh(e){return typeof e=="object"&&e!==null}function Uh(e){return typeof e=="string"&&Wh.test(e)}const Hh="workspace.delete",qh="pi.operation",Kh="target.workspaceId";function Vh(e){return{...e===void 0?{}:{projectId:e},metadata:{[qh]:Hh}}}function Gh(e){const t={};for(const i of e){const s=Is(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function Qh(e){return Object.entries(e).filter(([,t])=>Si(t)).map(([t])=>t)}function Kn(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&Si(i)}function Is(e){return e.metadata[Kh]}function Si(e){return e.status==="queued"||e.status==="running"}function Zh(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the PI WEB color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:hr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:Pt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Pt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:hr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Pt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:Jh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Pt,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:Xh,run:e=>e.archiveSession()},{id:"session.reload",title:"Reload Session",description:"Re-read the selected session from disk to pick up entries written by another process",group:"Session",enabled:eu,run:e=>e.reloadSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected browser-cached new session",group:"Session",enabled:Yh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&Ye(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Pt(e){return e.state.selectedWorkspace!==void 0}function hr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Jh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Kn(e.state,t)}function Xh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function Yh(e){return ee(e.state.selectedSession)}function eu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[g(e.state)];return i?.ok!==!0||!ht(i,Ze.sessionsReload)?!1:!Ye(e.state.status,e.state.activity)}const tu="modulepreload",iu=function(e){return"/"+e},ur={},Vn=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=iu(p),p in ur)return;ur[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":tu,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((v,P)=>{f.addEventListener("load",v),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},su=10*1024*1024,ou="10 MB";function ru(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ai(e)}function ai(e){switch(e){case"navigation":return he`
|
|
23
25
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
24
26
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
25
27
|
<path d="M10 7h8"></path>
|
|
@@ -28,17 +30,17 @@ ${o.join(`
|
|
|
28
30
|
<circle cx="6" cy="17" r="1.5"></circle>
|
|
29
31
|
<path d="M10 17h8"></path>
|
|
30
32
|
</svg>
|
|
31
|
-
`;case"chat":return
|
|
33
|
+
`;case"chat":return he`
|
|
32
34
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
33
35
|
<path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
|
|
34
36
|
<path d="M8 9h8"></path>
|
|
35
37
|
<path d="M8 13h5"></path>
|
|
36
38
|
</svg>
|
|
37
|
-
`;case"files":return
|
|
39
|
+
`;case"files":return he`
|
|
38
40
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
39
41
|
<path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
|
|
40
42
|
</svg>
|
|
41
|
-
`;case"git":return
|
|
43
|
+
`;case"git":return he`
|
|
42
44
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
43
45
|
<circle cx="6" cy="6" r="2"></circle>
|
|
44
46
|
<circle cx="18" cy="6" r="2"></circle>
|
|
@@ -47,13 +49,13 @@ ${o.join(`
|
|
|
47
49
|
<path d="M6 8v2a6 6 0 0 0 6 6"></path>
|
|
48
50
|
<path d="M18 8v2a6 6 0 0 1-6 6"></path>
|
|
49
51
|
</svg>
|
|
50
|
-
`;case"terminal":return
|
|
52
|
+
`;case"terminal":return he`
|
|
51
53
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
52
54
|
<rect x="3" y="5" width="18" height="14" rx="2"></rect>
|
|
53
55
|
<path d="m7 10 3 3-3 3"></path>
|
|
54
56
|
<path d="M12 16h5"></path>
|
|
55
57
|
</svg>
|
|
56
|
-
`}}function
|
|
58
|
+
`}}function nu(){return[{id:"workspace.files",title:"Files",icon:ai("files"),order:10,render:au},{id:"workspace.git",title:"Git",icon:ai("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:hu},{id:"workspace.terminal",title:"Terminal",icon:ai("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:pu}]}function au(e){return l`
|
|
57
59
|
<section class="toolbar">
|
|
58
60
|
<strong>Files</strong>
|
|
59
61
|
${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
|
|
@@ -61,30 +63,30 @@ ${o.join(`
|
|
|
61
63
|
</section>
|
|
62
64
|
<section class="split">
|
|
63
65
|
<div class="list tree">
|
|
64
|
-
${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>
|
|
66
|
+
${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>Gn(e,t,0))}
|
|
65
67
|
</div>
|
|
66
68
|
<div class="viewer">
|
|
67
|
-
${
|
|
69
|
+
${cu(e)}
|
|
68
70
|
</div>
|
|
69
71
|
</section>
|
|
70
|
-
`}function
|
|
71
|
-
<button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{
|
|
72
|
+
`}function Gn(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
|
|
73
|
+
<button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{lu(e,t)}}>
|
|
72
74
|
<span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
|
|
73
75
|
<span>${t.name}</span>
|
|
74
76
|
</button>
|
|
75
|
-
${o?s.map(n=>
|
|
76
|
-
`}function
|
|
77
|
+
${o?s.map(n=>Gn(e,n,i+1)):null}
|
|
78
|
+
`}function lu(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function cu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?du(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${Cs(t.size)}</p>`:(Qn(),l`
|
|
77
79
|
<div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
|
|
78
80
|
<code-viewer .content=${t.content} .language=${t.language}></code-viewer>
|
|
79
|
-
`)}function
|
|
81
|
+
`)}function du(e,t){const i=`${t.mimeType??"image"} · ${Cs(t.size)}`;if(t.size>su)return l`
|
|
80
82
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
81
|
-
<p class="muted">Image too large to preview: ${
|
|
82
|
-
`;const s=
|
|
83
|
+
<p class="muted">Image too large to preview: ${Cs(t.size)} · limit ${ou}</p>
|
|
84
|
+
`;const s=Fc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
|
|
83
85
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
84
86
|
<div class="image-preview">
|
|
85
87
|
<img src=${s} alt=${t.path} decoding="async" />
|
|
86
88
|
</div>
|
|
87
|
-
`}function
|
|
89
|
+
`}function pu(e){return gu(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function hu(e){const t=e.gitStatus;return l`
|
|
88
90
|
<section class="toolbar">
|
|
89
91
|
<strong>Git</strong>
|
|
90
92
|
${e.gitStale?l`<span class="stale">stale</span>`:null}
|
|
@@ -93,29 +95,29 @@ ${o.join(`
|
|
|
93
95
|
<section class="split">
|
|
94
96
|
<div class="list">
|
|
95
97
|
${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
|
|
96
|
-
<p class="summary">${
|
|
98
|
+
<p class="summary">${mu(t)}</p>
|
|
97
99
|
${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
|
|
98
100
|
<button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
|
|
99
|
-
<span>${
|
|
101
|
+
<span>${vu(i.index,i.workingTree)}</span>
|
|
100
102
|
<span>${i.path}</span>
|
|
101
103
|
</button>
|
|
102
104
|
`)}
|
|
103
105
|
`:l`<p class="muted">Not a git repository.</p>`}
|
|
104
106
|
</div>
|
|
105
107
|
<div class="viewer">
|
|
106
|
-
${
|
|
108
|
+
${uu(e)}
|
|
107
109
|
</div>
|
|
108
110
|
</section>
|
|
109
|
-
`}function
|
|
111
|
+
`}function uu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
|
|
110
112
|
<div class=${s.length===1?"diffs single":"diffs"}>
|
|
111
|
-
${s.map(o=>
|
|
113
|
+
${s.map(o=>fu(o))}
|
|
112
114
|
</div>
|
|
113
|
-
`}function
|
|
115
|
+
`}function fu(e){return Qn(),l`
|
|
114
116
|
<section class="diff-section">
|
|
115
117
|
<div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
|
|
116
118
|
<code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
|
|
117
119
|
</section>
|
|
118
|
-
`}function Nn(){Ln(()=>import("./CodeViewer-iYSv2-dg.js"),__vite__mapDeps([0,1,2,3]))}function Uh(){Ln(()=>import("./TerminalPanel-BpFW6j27.js"),__vite__mapDeps([4,5,6,1,2]))}function Hh(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function qh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function xs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Vi(t)} KB`;const i=t/1024;return i<1024?`${Vi(i)} MB`:`${Vi(i/1024)} GB`}function Vi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Kh={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Ph(),workspacePanels:Wh()}})},Vh={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},Gh={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#3d4a78","--pi-selection-bg":"#151b31","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Qh={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},Zh={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:Gh},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Qh},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:Vh}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Jh=/^[a-z][a-z0-9.-]*$/u;function Xh(e){return Jh.test(e)}const Yh="machine.";function eu(e,t){if(e==="")throw new Error("Machine id is required");if(!Xh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${tu(e)}.${t}`}function tu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function ar(e="/pi-web-plugins/manifest.json",t={}){const i=await iu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=ru(n,r);s.push({id:t.machineId===void 0?o.id:eu(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function iu(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return su(await t.json())}}function su(e){if(!gi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!gi(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:ou(t.machineSpecific)}})}}function ou(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function ru(e,t){if(!gi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nu(e){return gi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function gi(e){return typeof e=="object"&&e!==null}const au=/^[a-z][a-z0-9.-]*$/u,lu=/^[a-z][a-z0-9.-]*$/u,zn=new WeakMap,Fn=new WeakMap;class cu{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:rt}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&uu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=gu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=du(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(Gi(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(Gi(c,t)):void 0},render:c=>i.render(Gi(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!au.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${fu(i)}`);return i}}function du(e,t){return zn.get(e)?.(t)??e}function Gi(e,t){return Fn.get(e)?.(t)??e}function pu(e,t){return zn.set(e,t),e}function hu(e,t){return Fn.set(e,t),e}function uu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function fu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function gu(e){return e.state.selectedMachine?.id??"local"}const mu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vu(){return typeof window>"u"||!("matchMedia"in window)?[]:mu.map(e=>window.matchMedia(e))}function lr(e,t=bu()){return e.some(i=>i.matches)||wu(t)}function bu(){return typeof navigator>"u"?void 0:navigator}function wu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yu=250;class Su{constructor(t=xu()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},yu)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function xu(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const ku="(max-width: 760px)";class $u{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=lr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Pu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Su,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=lr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Pu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(ku)}const mi=["machines","projects","workspaces","sessions"];function Ru(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Js(e,t){if(e!=="none")return e??Ru(t)}function Cu(e,t){return t.isMobileLayout?Js(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Iu(e,t,i){return Js(e,i.state)===t?"none":t}function Mu(e,t,i){return i?t:e}function Tu(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Du(i)}function Au(e){return mi[mi.indexOf(e)+1]}class Eu{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Js(this.expanded,this.getState())}isCollapsed(t){return Cu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Iu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Tu(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Mu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Au(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Wu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Du(e){const t=new Set(e);return mi.filter(i=>t.has(i))}function Wu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _u{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Bn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Bn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const ks="pi-web:panel-sizes:v1",Ou={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Lu{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Xs(),this.panelSizes=Fu(this.storage)}hostConnected(){}constraints(t){return Lt(t)}panelWidth(t,i){return he(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=he(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Hu(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=qu(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Bu(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${dr(he("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${dr(he("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Lt(e){return Ou[e]}function ju(e,t,i){return e==="navigation"?i-t:t-i}function Nu(e,t,i,s,o=Lt(e)){return he(e,t+ju(e,i,s),o)}function zu(e,t,i,s={}){const o=s.constraints??Lt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Ku(e,i,r);if(n!==void 0)return he(e,t+n,o)}function he(e,t,i=Lt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Fu(e=Xs()){try{const t=e?.getItem(ks);if(t==null||t==="")return{};const i=JSON.parse(t);return Uu(i)}catch{return{}}}function Bu(e,t=Xs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ks);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=he("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=he("workspace",e.workspacePanelWidth)),t.setItem(ks,JSON.stringify(i))}catch{}}function Uu(e){if(!Vu(e)||e.version!==1)return{};const t={},i=cr(e.navigationPanelWidth),s=cr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=he("navigation",i)),s!==void 0&&(t.workspacePanelWidth=he("workspace",s)),t}function cr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hu(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function qu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ku(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function dr(e){return`${String(Math.round(e))}px`}function Xs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vu(e){return typeof e=="object"&&e!==null}function pr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Gu(e.get("tool")),view:Qu(e.get("view"))}}function Qi(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Gu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Qu(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Un(e)?e:void 0}function Un(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function hr(){return Zu(new URLSearchParams(window.location.search).get("settings"))}function Zi(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function Zu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Ju(e,t){return t===void 0?e:e.map(i=>Yu(i,t))}function Xu(e,t){const i=new Set(Gs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Ju(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Hn(s):s)}function Yu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Hn(e):{...e,shortcut:i}}function Hn(e){const t={...e};return delete t.shortcut,t}function ef(e,t){const i=t.api??nt,s=t.pollIntervalMs??1e3,o=t.setTimeout??sf(),r=t.clearTimeout??of();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:tf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function tf(e,t,i,s,o){return ur(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&ur(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function ur(e){return e.status==="succeeded"||e.status==="failed"}function sf(){return(e,t)=>globalThis.setTimeout(e,t)}function of(){return e=>{globalThis.clearTimeout(e)}}function rf(e,t){return t[e.path]}function nf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function af(e,t,i){return Kn(lf(e,t,i))}function qn(e){return Kn(Object.values(e??{}))}function Kn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function lf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Ht=0,cf=120;function jt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Vn():df(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ht,f=i.top-c-Ht;return[...h<cf&&f>h?[`bottom: ${st(r-i.top+Ht)};`,`max-height: ${st(Math.max(0,f))};`]:[`top: ${st(i.bottom+Ht)};`,`max-height: ${st(Math.max(0,h))};`],`right: ${st(Math.max(0,o-u))};`,`max-width: ${st(Math.max(0,u-n))};`].join(" ")}function df(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vn()}function Vn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function st(e){return`${String(Math.round(e))}px`}function Gn(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Ti(e,t="Active"){const i=Gn(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const pf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Qn(e){return e.composedPath().some(t=>hf(t,pf))}function hf(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Ai(e,t){Qn(e)||t()}function Ei(e,t){return Qn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ue(e,()=>{fr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ue(e,()=>{fr(e.currentTarget,1)}):e.key==="Home"?Ue(e,()=>{gr(e.currentTarget,0)}):e.key==="End"?Ue(e,()=>{gr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ue(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ue(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ue(e,t.cancel):!1}function Di(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ue(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function fr(e,t){const i=Jn(e),s=Xn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Zn(i,o+t)}function gr(e,t){const i=Jn(e);i.length!==0&&Zn(i,t<0?i.length-1:t)}function Zn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Jn(e){const t=Xn(e)?.getRootNode();return t===void 0||!uf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function uf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Xn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ff=W`
|
|
120
|
+
`}function Qn(){Vn(()=>import("./CodeViewer-Bv8l_MFi.js"),__vite__mapDeps([0,1,2,3]))}function gu(){Vn(()=>import("./TerminalPanel-BZKsaE9s.js"),__vite__mapDeps([4,5,6,1,2]))}function mu(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function vu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Cs(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Yi(t)} KB`;const i=t/1024;return i<1024?`${Yi(i)} MB`:`${Yi(i/1024)} GB`}function Yi(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const bu={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:Zh(),workspacePanels:nu()}})},wu={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},yu={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Su={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},xu={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:yu},{id:"pi-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:Su},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:wu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ku=/^[a-z][a-z0-9.-]*$/u;function $u(e){return ku.test(e)}const Pu="machine.";function Ru(e,t){if(e==="")throw new Error("Machine id is required");if(!$u(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Pu}${Iu(e)}.${t}`}function Iu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function fr(e="/pi-web-plugins/manifest.json",t={}){const i=await Cu(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=Tu(n,r);s.push({id:t.machineId===void 0?o.id:Ru(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function Cu(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return Mu(await t.json())}}function Mu(e){if(!xi(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!xi(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:Au(t.machineSpecific)}})}}function Au(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function Tu(e,t){if(!xi(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Eu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Eu(e){return xi(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function xi(e){return typeof e=="object"&&e!==null}const Du=/^[a-z][a-z0-9.-]*$/u,Wu=/^[a-z][a-z0-9.-]*$/u,Zn=new WeakMap,Jn=new WeakMap;class _u{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&Nu(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Fu(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=Ou(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(es(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(es(c,t)):void 0},render:c=>i.render(es(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Du.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Wu.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${zu(i)}`);return i}}function Ou(e,t){return Zn.get(e)?.(t)??e}function es(e,t){return Jn.get(e)?.(t)??e}function Lu(e,t){return Zn.set(e,t),e}function ju(e,t){return Jn.set(e,t),e}function Nu(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function zu(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Fu(e){return e.state.selectedMachine?.id??"local"}const Bu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Uu(){return typeof window>"u"||!("matchMedia"in window)?[]:Bu.map(e=>window.matchMedia(e))}function gr(e,t=Hu()){return e.some(i=>i.matches)||qu(t)}function Hu(){return typeof navigator>"u"?void 0:navigator}function qu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Ku=250;class Vu{constructor(t=Gu()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},Ku)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Gu(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Qu="(max-width: 760px)";class Zu{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=gr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Ju(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Uu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Vu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=gr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Ju(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Qu)}const ki=["machines","projects","workspaces","sessions"];function Xu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function so(e,t){if(e!=="none")return e??Xu(t)}function Yu(e,t){return t.isMobileLayout?so(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function ef(e,t,i){return so(e,i.state)===t?"none":t}function tf(e,t,i){return i?t:e}function sf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),nf(i)}function of(e){return ki[ki.indexOf(e)+1]}class rf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return so(this.expanded,this.getState())}isCollapsed(t){return Yu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(ef(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(sf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(tf(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=of(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){af(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function nf(e){const t=new Set(e);return ki.filter(i=>t.has(i))}function af(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class lf{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Xn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Xn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ms="pi-web:panel-sizes:v1",cf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class df{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??oo(),this.panelSizes=ff(this.storage)}hostConnected(){}constraints(t){return Ut(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=vf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=bf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){gf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${vr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${vr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ut(e){return cf[e]}function pf(e,t,i){return e==="navigation"?i-t:t-i}function hf(e,t,i,s,o=Ut(e)){return ue(e,t+pf(e,i,s),o)}function uf(e,t,i,s={}){const o=s.constraints??Ut(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=wf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ut(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function ff(e=oo()){try{const t=e?.getItem(Ms);if(t==null||t==="")return{};const i=JSON.parse(t);return mf(i)}catch{return{}}}function gf(e,t=oo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ms);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(Ms,JSON.stringify(i))}catch{}}function mf(e){if(!yf(e)||e.version!==1)return{};const t={},i=mr(e.navigationPanelWidth),s=mr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function mr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function vf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function bf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function wf(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function vr(e){return`${String(Math.round(e))}px`}function oo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yf(e){return typeof e=="object"&&e!==null}function br(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Sf(e.get("tool")),view:xf(e.get("view"))}}function ts(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Sf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function xf(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Yn(e)?e:void 0}function Yn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function wr(){return kf(new URLSearchParams(window.location.search).get("settings"))}function is(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function kf(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function $f(e,t){return t===void 0?e:e.map(i=>Rf(i,t))}function Pf(e,t){const i=new Set(eo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return $f(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ea(s):s)}function Rf(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ea(e):{...e,shortcut:i}}function ea(e){const t={...e};return delete t.shortcut,t}function If(e,t){const i=t.api??pt,s=t.pollIntervalMs??1e3,o=t.setTimeout??Mf(),r=t.clearTimeout??Af();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:Cf(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Cf(e,t,i,s,o){return yr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&yr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function yr(e){return e.status==="succeeded"||e.status==="failed"}function Mf(){return(e,t)=>globalThis.setTimeout(e,t)}function Af(){return e=>{globalThis.clearTimeout(e)}}function Tf(e,t){return t[e.path]}function Ef(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Df(e,t,i){return ia(Wf(e,t,i))}function ta(e){return ia(Object.values(e??{}))}function ia(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Wf(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Zt=0,_f=120;function Ht(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?sa():Of(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Zt,f=i.top-c-Zt;return[...h<_f&&f>h?[`bottom: ${lt(r-i.top+Zt)};`,`max-height: ${lt(Math.max(0,f))};`]:[`top: ${lt(i.bottom+Zt)};`,`max-height: ${lt(Math.max(0,h))};`],`right: ${lt(Math.max(0,o-u))};`,`max-width: ${lt(Math.max(0,u-n))};`].join(" ")}function Of(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():sa()}function sa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function lt(e){return`${String(Math.round(e))}px`}function oa(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Oi(e,t="Active"){const i=oa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Lf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ra(e){return e.composedPath().some(t=>jf(t,Lf))}function jf(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Li(e,t){ra(e)||t()}function ji(e,t){return ra(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Sr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Sr(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{xr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{xr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function Ni(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Sr(e,t){const i=aa(e),s=la(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||na(i,o+t)}function xr(e,t){const i=aa(e);i.length!==0&&na(i,t<0?i.length-1:t)}function na(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function aa(e){const t=la(e)?.getRootNode();return t===void 0||!Nf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Nf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function la(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const zf=O`
|
|
119
121
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
120
122
|
:host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
|
|
121
123
|
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
@@ -209,11 +211,11 @@ ${o.join(`
|
|
|
209
211
|
}
|
|
210
212
|
status-bar { flex: 0 0 auto; }
|
|
211
213
|
chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
212
|
-
prompt-editor
|
|
214
|
+
prompt-editor { flex: 0 0 auto; }
|
|
213
215
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
214
216
|
.empty { margin: auto; color: var(--pi-muted); }
|
|
215
217
|
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
216
|
-
`,
|
|
218
|
+
`,Ff=O`
|
|
217
219
|
:host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
|
|
218
220
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
219
221
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -268,7 +270,7 @@ ${o.join(`
|
|
|
268
270
|
.image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
|
|
269
271
|
pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
270
272
|
p { margin: 10px; }
|
|
271
|
-
`,
|
|
273
|
+
`,zi=O`
|
|
272
274
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
273
275
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
274
276
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -310,6 +312,8 @@ ${o.join(`
|
|
|
310
312
|
.activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
|
|
311
313
|
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
312
314
|
.activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
|
|
315
|
+
/* Client-side sending (upload in flight); distinct from server activity, which propagates to workspace/machine rows. */
|
|
316
|
+
.activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
|
|
313
317
|
.action-menu { position: relative; align-self: stretch; }
|
|
314
318
|
.action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
|
|
315
319
|
.action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
|
|
@@ -327,7 +331,7 @@ ${o.join(`
|
|
|
327
331
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
328
332
|
.workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
|
|
329
333
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
330
|
-
`,
|
|
334
|
+
`,Bf=O`
|
|
331
335
|
:host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
332
336
|
.chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
333
337
|
.chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
|
|
@@ -338,6 +342,7 @@ ${o.join(`
|
|
|
338
342
|
.dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
|
|
339
343
|
.activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
340
344
|
.msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
|
|
345
|
+
.msg.assistant { background: var(--pi-surface); }
|
|
341
346
|
.msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
|
|
342
347
|
.msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
|
|
343
348
|
.msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
|
|
@@ -350,6 +355,7 @@ ${o.join(`
|
|
|
350
355
|
.msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
|
|
351
356
|
.msg.event-group > summary .label { margin: 0; }
|
|
352
357
|
.group-body { padding: 0 12px 12px; }
|
|
358
|
+
.chat-image { display: block; max-width: 100%; max-height: 320px; margin: 8px 0 0; border: 1px solid var(--pi-border-muted); border-radius: 8px; object-fit: contain; }
|
|
353
359
|
.group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
|
|
354
360
|
.group-msg.tool { color: var(--pi-warning); }
|
|
355
361
|
.group-msg.tool-execution-shell { color: var(--pi-text); }
|
|
@@ -376,6 +382,8 @@ ${o.join(`
|
|
|
376
382
|
.msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
|
|
377
383
|
.msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
|
|
378
384
|
.msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
|
|
385
|
+
.msg.assistant > .msg-header .label { color: var(--pi-text-secondary); }
|
|
386
|
+
.msg.user > .msg-header .label { color: var(--pi-accent); }
|
|
379
387
|
.msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
|
|
380
388
|
.msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
|
|
381
389
|
.msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
|
|
@@ -411,7 +419,7 @@ ${o.join(`
|
|
|
411
419
|
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
412
420
|
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
|
|
413
421
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
414
|
-
`,
|
|
422
|
+
`,Uf=O`
|
|
415
423
|
:host { display: block; }
|
|
416
424
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
417
425
|
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -436,7 +444,7 @@ ${o.join(`
|
|
|
436
444
|
table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
|
|
437
445
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
438
446
|
th { background: var(--pi-surface); }
|
|
439
|
-
`,
|
|
447
|
+
`,Hf=O`
|
|
440
448
|
:host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
|
|
441
449
|
.bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
|
|
442
450
|
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -446,7 +454,7 @@ ${o.join(`
|
|
|
446
454
|
.activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
447
455
|
.muted { color: var(--pi-dim); }
|
|
448
456
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
449
|
-
`,
|
|
457
|
+
`,qf=O`
|
|
450
458
|
:host { display: block; }
|
|
451
459
|
.menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
|
|
452
460
|
button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
|
|
@@ -454,7 +462,7 @@ ${o.join(`
|
|
|
454
462
|
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
455
463
|
span { color: var(--pi-muted); font-size: 12px; }
|
|
456
464
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
457
|
-
`,
|
|
465
|
+
`,ca=O`
|
|
458
466
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
459
467
|
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
460
468
|
section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -468,7 +476,7 @@ ${o.join(`
|
|
|
468
476
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
469
477
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
470
478
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
471
|
-
`,
|
|
479
|
+
`,Kf=O`
|
|
472
480
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
473
481
|
.backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
|
|
474
482
|
section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -486,7 +494,7 @@ ${o.join(`
|
|
|
486
494
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
487
495
|
kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
|
|
488
496
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
489
|
-
`,
|
|
497
|
+
`,Vf=O`
|
|
490
498
|
:host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
491
499
|
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
|
|
492
500
|
footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
@@ -495,16 +503,30 @@ ${o.join(`
|
|
|
495
503
|
.compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
|
|
496
504
|
.compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
497
505
|
.select-model { max-width: min(42vw, 320px); }
|
|
498
|
-
.
|
|
506
|
+
.icon-button { flex: 0 0 auto; display: inline-grid; place-items: center; width: 36px; height: 36px; padding: 0; }
|
|
507
|
+
.icon-button .prompt-action-icon, .icon-button .prompt-thinking-gauge { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
508
|
+
.icon-button .prompt-action-icon-filled { fill: currentColor; stroke: none; }
|
|
509
|
+
.send-button:not(:disabled) { color: var(--pi-accent, var(--pi-text)); }
|
|
510
|
+
.stop-button:not(:disabled) { color: var(--pi-danger); }
|
|
511
|
+
.select-thinking .prompt-thinking-gauge .gauge-bar { fill: currentColor; stroke: none; opacity: .28; }
|
|
512
|
+
.select-thinking .prompt-thinking-gauge .gauge-bar-active { opacity: 1; }
|
|
513
|
+
.editor-attach { position: absolute; right: 8px; bottom: 8px; z-index: 2; width: 30px; height: 30px; }
|
|
514
|
+
.editor-attach .prompt-action-icon { width: 16px; height: 16px; }
|
|
499
515
|
textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
|
|
500
516
|
textarea { overflow-y: auto; padding: 8px; }
|
|
501
517
|
.markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
|
|
502
|
-
.markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
|
|
518
|
+
.markdown-editor .cm-content { min-height: 38px; padding: 8px 44px 8px 8px; caret-color: var(--pi-text); }
|
|
503
519
|
.markdown-editor .cm-line { padding: 0; }
|
|
504
520
|
.markdown-editor .cm-placeholder { color: var(--pi-dim); }
|
|
505
521
|
.markdown-editor .cm-focused { outline: none; }
|
|
506
522
|
.shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
|
|
507
|
-
.mode-hint { position: absolute; right:
|
|
523
|
+
.mode-hint { position: absolute; right: 46px; bottom: 8px; max-width: calc(100% - 54px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
|
|
524
|
+
.attachments { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 8px; }
|
|
525
|
+
.attachment-chip { position: relative; width: 56px; height: 56px; border: 1px solid var(--pi-border); border-radius: 8px; overflow: hidden; background: var(--pi-bg); }
|
|
526
|
+
.attachment-chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
|
527
|
+
.attachment-remove { position: absolute; top: 1px; right: 1px; width: 18px; height: 18px; padding: 0; line-height: 16px; border-radius: 50%; border: 1px solid var(--pi-border); background: var(--pi-surface); color: var(--pi-text); font-size: 13px; cursor: pointer; }
|
|
528
|
+
.attachment-delivery select { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; font: 12px system-ui, sans-serif; }
|
|
529
|
+
.attachment-error { flex-basis: 100%; color: var(--pi-danger); font-size: 12px; }
|
|
508
530
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
509
531
|
button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
|
|
510
532
|
@media (max-width: 640px) {
|
|
@@ -517,10 +539,10 @@ ${o.join(`
|
|
|
517
539
|
@media (max-width: 430px) {
|
|
518
540
|
.compact-status { flex-basis: 170px; font-size: 11px; }
|
|
519
541
|
.select-model { max-width: 48vw; }
|
|
520
|
-
.select-thinking { max-width: 70px; }
|
|
521
542
|
button { padding: 5px 7px; }
|
|
543
|
+
.icon-button { width: 34px; height: 34px; }
|
|
522
544
|
}
|
|
523
|
-
`;var
|
|
545
|
+
`;var Gf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Gf(t,i,o),o};let J=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
524
546
|
<section>
|
|
525
547
|
<h2>${this.renderHeading()}</h2>
|
|
526
548
|
${this.collapsed?null:l`
|
|
@@ -529,12 +551,12 @@ ${o.join(`
|
|
|
529
551
|
</div>
|
|
530
552
|
`}
|
|
531
553
|
</section>
|
|
532
|
-
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=
|
|
554
|
+
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=da(e)&&this.onRemove!==void 0;return l`
|
|
533
555
|
<div
|
|
534
556
|
class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
|
|
535
557
|
tabindex="0"
|
|
536
558
|
title=${e.baseUrl??e.name}
|
|
537
|
-
@click=${o=>{
|
|
559
|
+
@click=${o=>{Li(o,()=>this.onSelect?.(e))}}
|
|
538
560
|
@keydown=${o=>{this.handleMachineKeydown(o,e)}}
|
|
539
561
|
>
|
|
540
562
|
<div class="action-main">
|
|
@@ -543,7 +565,7 @@ ${o.join(`
|
|
|
543
565
|
</div>
|
|
544
566
|
${s?this.renderMachineMenu(e):null}
|
|
545
567
|
</div>
|
|
546
|
-
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=
|
|
568
|
+
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return Oi(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=Zf(e.id);return l`
|
|
547
569
|
<div class="action-menu">
|
|
548
570
|
<button
|
|
549
571
|
class="action-menu-toggle"
|
|
@@ -559,13 +581,13 @@ ${o.join(`
|
|
|
559
581
|
</div>
|
|
560
582
|
`:null}
|
|
561
583
|
</div>
|
|
562
|
-
`}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=
|
|
584
|
+
`}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[zi,O`
|
|
563
585
|
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
564
586
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
565
587
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
566
588
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
567
589
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
568
|
-
`];
|
|
590
|
+
`];ae([d({attribute:!1})],J.prototype,"machines",2);ae([d({attribute:!1})],J.prototype,"selected",2);ae([d({attribute:!1})],J.prototype,"statuses",2);ae([d({attribute:!1})],J.prototype,"activities",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ae([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([d({attribute:!1})],J.prototype,"onSelect",2);ae([d({attribute:!1})],J.prototype,"onRemove",2);ae([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ae([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ae([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);ae([w()],J.prototype,"openMenuMachineId",2);ae([w()],J.prototype,"menuStyle",2);J=ae([D("machine-list")],J);function da(e){return e.kind==="remote"}function Zf(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Jf=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Jf(t,i,o),o};let G=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
569
591
|
<section>
|
|
570
592
|
<h2>${this.renderHeading()}</h2>
|
|
571
593
|
${this.collapsed?null:l`
|
|
@@ -575,7 +597,7 @@ ${o.join(`
|
|
|
575
597
|
class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
|
|
576
598
|
tabindex="0"
|
|
577
599
|
title=${e.path}
|
|
578
|
-
@click=${t=>{
|
|
600
|
+
@click=${t=>{Li(t,()=>this.onSelect?.(e))}}
|
|
579
601
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
580
602
|
>
|
|
581
603
|
<div class="action-main">
|
|
@@ -595,19 +617,19 @@ ${o.join(`
|
|
|
595
617
|
</div>
|
|
596
618
|
`}
|
|
597
619
|
</section>
|
|
598
|
-
`}handleProjectKeydown(e,t){
|
|
620
|
+
`}handleProjectKeydown(e,t){ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Df(e,this.workspacesByProjectId[e.id]??[],this.activities);return Oi(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
|
|
599
621
|
|
|
600
|
-
This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};
|
|
622
|
+
This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};G.styles=zi;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([w()],G.prototype,"openMenuProjectId",2);ie([w()],G.prototype,"menuStyle",2);G=ie([D("project-list")],G);function kr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Yf(t)}`)}function Yf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&eg(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function eg(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var tg=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var o=s>1?void 0:s?ig(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tg(t,i,o),o};let q=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
601
623
|
<section>
|
|
602
624
|
<h2>${this.renderHeading()}</h2>
|
|
603
625
|
${this.collapsed?null:l`
|
|
604
626
|
<div class="list-body">
|
|
605
|
-
${this.workspaces.map(e=>{const t=
|
|
627
|
+
${this.workspaces.map(e=>{const t=sg(e),i=this.workspaceLabelItems(e);return l`
|
|
606
628
|
<div
|
|
607
629
|
class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
|
|
608
630
|
tabindex="0"
|
|
609
631
|
title=${t}
|
|
610
|
-
@click=${s=>{
|
|
632
|
+
@click=${s=>{Li(s,()=>this.onSelect?.(e))}}
|
|
611
633
|
@keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
|
|
612
634
|
>
|
|
613
635
|
<div class="action-main">
|
|
@@ -619,18 +641,18 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
619
641
|
</div>
|
|
620
642
|
`}
|
|
621
643
|
</section>
|
|
622
|
-
`}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=
|
|
644
|
+
`}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Ef(Tf(e,this.activities));return Oi(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
|
|
623
645
|
<span class="workspace-primary">
|
|
624
646
|
<span class="workspace-primary-label">${e}</span>
|
|
625
647
|
${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
|
|
626
648
|
</span>
|
|
627
649
|
${t.length===0?null:l`
|
|
628
650
|
<small class="workspace-secondary">
|
|
629
|
-
<span class="workspace-label">${
|
|
651
|
+
<span class="workspace-label">${kr(t)}</span>
|
|
630
652
|
</small>
|
|
631
653
|
`}
|
|
632
654
|
${this.renderActivity(i)}
|
|
633
|
-
`}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=
|
|
655
|
+
`}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=rg(i.id);return l`
|
|
634
656
|
<div class="action-menu">
|
|
635
657
|
<button
|
|
636
658
|
class="action-menu-toggle"
|
|
@@ -647,7 +669,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
647
669
|
</div>
|
|
648
670
|
`:null}
|
|
649
671
|
</div>
|
|
650
|
-
`}renderWorkspaceActions(e){if(!
|
|
672
|
+
`}renderWorkspaceActions(e){if(!og(e))return;const t=this.isDeleting(e);return l`
|
|
651
673
|
<div class="workspace-menu-actions">
|
|
652
674
|
<button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
|
|
653
675
|
</div>
|
|
@@ -664,11 +686,11 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
664
686
|
${t.length===0?null:l`
|
|
665
687
|
<div class="workspace-detail-row">
|
|
666
688
|
<dt>Details</dt>
|
|
667
|
-
<dd><span class="workspace-label">${
|
|
689
|
+
<dd><span class="workspace-label">${kr(t)}</span></dd>
|
|
668
690
|
</div>
|
|
669
691
|
`}
|
|
670
692
|
</dl>
|
|
671
|
-
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=
|
|
693
|
+
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}ji(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=zi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([w()],q.prototype,"openMenuWorkspaceId",2);X([w()],q.prototype,"menuStyle",2);q=X([D("workspace-list")],q);function sg(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function og(e){return e.isGitWorktree&&!e.isMain}function rg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var ng=Object.defineProperty,ag=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var o=s>1?void 0:s?ag(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ng(t,i,o),o};function Rt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=dg(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>It(r)==="current"),s=pa(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=lg(this.sessions);return l`
|
|
672
694
|
<section>
|
|
673
695
|
${this.renderHeading(e.length+s.length,i)}
|
|
674
696
|
${this.collapsed?null:l`
|
|
@@ -691,7 +713,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
691
713
|
${this.renderCurrentSelectionButton(t)}
|
|
692
714
|
<button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
|
|
693
715
|
</h2>
|
|
694
|
-
`;const i=this.selected===void 0?"No session selected":
|
|
716
|
+
`;const i=this.selected===void 0?"No session selected":Rt(this.selected),s=this.selected?.path??i;return l`
|
|
695
717
|
<h2>
|
|
696
718
|
<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span>${this.collapsed?l`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
|
|
697
719
|
${this.renderCurrentSelectionButton(t)}
|
|
@@ -704,7 +726,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
704
726
|
${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close archived session selection":"Select archived sessions"} aria-label=${t?"Close archived session selection":"Select archived sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
|
|
705
727
|
<small class="section-count">${e.length}</small>
|
|
706
728
|
</h2>
|
|
707
|
-
`}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!
|
|
729
|
+
`}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ee(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
|
|
708
730
|
<div class="bulk-row selecting">
|
|
709
731
|
<button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"Clear visible":"Select visible"}</button>
|
|
710
732
|
<small>${t.length} selected${o!==t.length?l` · ${o} visible`:null}</small>
|
|
@@ -721,37 +743,38 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
721
743
|
<button @click=${()=>{this.closeSelection("archived")}}>Done</button>
|
|
722
744
|
${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
|
|
723
745
|
</div>
|
|
724
|
-
`}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=
|
|
746
|
+
`}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=It(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
|
|
725
747
|
<div
|
|
726
748
|
class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
|
|
727
749
|
style=${`--depth:${String(o)}`}
|
|
728
750
|
tabindex="0"
|
|
729
751
|
title=${s.path}
|
|
730
|
-
@click=${p=>{
|
|
752
|
+
@click=${p=>{Li(p,()=>{this.activateSessionRow(s,i)})}}
|
|
731
753
|
@keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
|
|
732
754
|
>
|
|
733
755
|
<div class="action-main ${n?"selecting":""}">
|
|
734
|
-
${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${
|
|
735
|
-
<span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${
|
|
756
|
+
${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Rt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
|
|
757
|
+
<span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Rt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} messages</small>
|
|
736
758
|
${this.renderActivity(s)}
|
|
737
759
|
</div>
|
|
738
760
|
<div class="action-menu">
|
|
739
761
|
<button class="action-menu-toggle" title="Session actions" @click=${p=>{p.stopPropagation(),this.toggleMenu(s.id,p.currentTarget)}}>⋯</button>
|
|
740
762
|
${this.openMenuSessionId===s.id?l`
|
|
741
763
|
<div class="action-menu-panel" style=${this.menuStyle}>
|
|
742
|
-
${
|
|
764
|
+
${ee(s)?l`<button title="Delete browser-cached new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:s.archived===!0?l`
|
|
743
765
|
<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(s)}}>Restore</button>
|
|
744
766
|
<button class="danger" title=${this.canDeleteArchived?"Permanently delete archived session":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(s)}}>Delete archived session</button>
|
|
745
767
|
`:l`
|
|
746
|
-
${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
|
|
747
768
|
<button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
|
|
748
769
|
${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(s,t)}}>Archive with descendants (${t})</button>`:null}
|
|
770
|
+
${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
|
|
771
|
+
${this.canReload?l`<button title=${Ye(this.statuses[s.id],this.activities[s.id])?"Stop current session activity before reloading":"Reload session from disk"} ?disabled=${Ye(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(s)}}>Reload</button>`:null}
|
|
749
772
|
`}
|
|
750
773
|
</div>
|
|
751
774
|
`:null}
|
|
752
775
|
</div>
|
|
753
776
|
</div>
|
|
754
|
-
`}handleSessionKeydown(e,t,i){
|
|
777
|
+
`}handleSessionKeydown(e,t,i){ji(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&It(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${Rt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${Rt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=ss(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=ss(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>It(i)===e).map(i=>i.id);this.selectedSessionIds=ss(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&It(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){const t=cg(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Oi(t,t==="sending"?"Sending message":"Session active")}};R.styles=[zi,O`
|
|
755
778
|
h2 { min-height: 30px; }
|
|
756
779
|
h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
757
780
|
.bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
|
|
@@ -765,7 +788,7 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
765
788
|
.action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
|
|
766
789
|
.action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
|
|
767
790
|
.session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
|
|
768
|
-
`];A([d({attribute:!1})],I.prototype,"sessions",2);A([d({attribute:!1})],I.prototype,"statuses",2);A([d({attribute:!1})],I.prototype,"activities",2);A([d({attribute:!1})],I.prototype,"selected",2);A([d({type:Boolean})],I.prototype,"canStart",2);A([d({type:Boolean})],I.prototype,"canDeleteArchived",2);A([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);A([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);A([d({attribute:!1})],I.prototype,"onSelect",2);A([d({attribute:!1})],I.prototype,"onStart",2);A([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);A([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);A([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);A([d({attribute:!1})],I.prototype,"onFocusNextSection",2);A([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);A([d({attribute:!1})],I.prototype,"onArchive",2);A([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);A([d({attribute:!1})],I.prototype,"onArchiveMany",2);A([d({attribute:!1})],I.prototype,"onRestore",2);A([d({attribute:!1})],I.prototype,"onDelete",2);A([d({attribute:!1})],I.prototype,"onDeleteArchived",2);A([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);A([d({attribute:!1})],I.prototype,"onDetachParent",2);A([b()],I.prototype,"openMenuSessionId",2);A([b()],I.prototype,"menuStyle",2);A([b()],I.prototype,"archivedExpanded",2);A([b()],I.prototype,"selectionScopes",2);A([b()],I.prototype,"selectedSessionIds",2);I=A([E("session-list")],I);function yt(e){return e.archived===!0?"archived":"current"}function Ji(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Of(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Lf(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return ta(e.filter(s=>i.has(s.id)))}function ta(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const Ys={CHILD:2,ELEMENT:6},eo=e=>(...t)=>({_$litDirective$:e,values:t});let to=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:jf}=tl,vr=e=>e,br=()=>document.createComment(""),St=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(br(),o),n=s.insertBefore(br(),o);i=new jf(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=vr(c).nextSibling;vr(s).insertBefore(c,o),c=p}}}return i},He=(e,t,i=e)=>(e._$AI(t,i),e),Nf={},zf=(e,t=Nf)=>e._$AH=t,Ff=e=>e._$AH,Xi=e=>{e._$AR(),e._$AA.remove()};const wr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Bf=eo(class extends to{constructor(e){if(super(e),e.type!==Ys.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=Ff(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=He(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=He(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=He(o[h],r[P]),St(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=He(o[f],r[v]),St(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=wr(n,v,P),u=wr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const B=u.get(n[v]),et=B!==void 0?o[B]:null;if(et===null){const ht=St(e,o[h]);He(ht,r[v]),c[v]=ht}else c[v]=He(et,r[v]),St(e,o[h],et),o[B]=null;v++}else Xi(o[f]),f--;else Xi(o[h]),h++;for(;v<=P;){const B=St(e,c[P+1]);He(B,r[v]),c[v++]=B}for(;h<=f;){const B=o[h++];B!==null&&Xi(B)}return this.ut=n,zf(e,c),Fe}}),Uf="pi-web:chat-groups:",Hf={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(yr(e));return t===null||t===""?void 0:Kf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(yr(e),JSON.stringify(t))}catch{}}};class qf{constructor(t=Hf){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Sr(r,this.openGroupKeys)&&Sr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function yr(e){return`${Uf}${e}`}function Kf(e){if(Array.isArray(e))return{open:Yi(e),closedDefaultOpen:[]};if(Vf(e))return{open:Array.isArray(e.open)?Yi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Yi(e.closedDefaultOpen):[]}}function Yi(e){return e.filter(t=>typeof t=="string")}function Sr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Vf(e){return typeof e=="object"&&e!==null}function Gf(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>xr(a,v)),u=a.parts.filter(v=>!xr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function Qf(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function xr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Zf=30;function Jf(e,t){const i=Yf(ig(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Xf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=eg(s,t.markerOffset);return}e.scrollTop=tg(e.scrollHeight,t.distanceFromBottom)}function Yf(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function eg(e,t){return e-t}function tg(e,t){return Math.max(0,e-t)}function ig(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const sg=600,og=1;function rg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ng(e)||ag(e)}function ng(e){return e.scrollTop<(e.topThreshold??Math.max(sg,e.clientHeight))}function ag(e){return e.scrollHeight<=e.clientHeight+og}const lg="pi-web:chat-scroll:",cg=180,dg=48,pg=2,hg={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},ug={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class fg{constructor(t=hg,i=ug){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=cg){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=pg){if(t===""||i===void 0||!ts(i))return"skipped";try{if(sa(i,o)){const a={mode:"bottom"};return this.storage.setItem(es(t),JSON.stringify(a)),"saved"}const r=vg(i,s);if(r===void 0)return"skipped";const n=mg(i,r);return this.storage.setItem(es(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ts(i))return{status:"skipped"};const r=bg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(es(t));if(i===null||i==="")return;const s=JSON.parse(i);return gg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function es(e){return`${lg}${e}`}function gg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function ts(e){return e.clientHeight>0&&e.scrollHeight>0}function ia(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function sa(e,t=dg){return ia(e)<t}function mg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:io(t)??"",offset:t.getBoundingClientRect().top-i}}function vg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(io(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function kr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function bg(e,t){return e.find(i=>io(i)===t)}function io(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var wg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,so=(e,t,i,s)=>{for(var o=s>1?void 0:s?yg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&wg(t,i,o),o};let Et=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=$r(this.positionPercent),t=$r(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
|
|
791
|
+
`];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([w()],R.prototype,"openMenuSessionId",2);M([w()],R.prototype,"menuStyle",2);M([w()],R.prototype,"archivedExpanded",2);M([w()],R.prototype,"selectionScopes",2);M([w()],R.prototype,"selectedSessionIds",2);R=M([D("session-list")],R);function It(e){return e.archived===!0?"archived":"current"}function ss(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function lg(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function cg(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Ye(t,i)?"session":void 0}function dg(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return pa(e.filter(s=>i.has(s.id)))}function pa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const ro={CHILD:2,ELEMENT:6},no=e=>(...t)=>({_$litDirective$:e,values:t});let ao=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:pg}=fl,$r=e=>e,Pr=()=>document.createComment(""),Ct=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(Pr(),o),n=s.insertBefore(Pr(),o);i=new pg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=$r(c).nextSibling;$r(s).insertBefore(c,o),c=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),hg={},ug=(e,t=hg)=>e._$AH=t,fg=e=>e._$AH,os=e=>{e._$AR(),e._$AA.remove()};const Rr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},gg=no(class extends ao{constructor(e){if(super(e),e.type!==ro.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=fg(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,v=0,P=r.length-1;for(;h<=f&&v<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[v])c[v]=Ve(o[h],r[v]),h++,v++;else if(a[f]===n[P])c[P]=Ve(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Ve(o[h],r[P]),Ct(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[v])c[v]=Ve(o[f],r[v]),Ct(e,o[h],o[f]),f--,v++;else if(p===void 0&&(p=Rr(n,v,P),u=Rr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const H=u.get(n[v]),rt=H!==void 0?o[H]:null;if(rt===null){const wt=Ct(e,o[h]);Ve(wt,r[v]),c[v]=wt}else c[v]=Ve(rt,r[v]),Ct(e,o[h],rt),o[H]=null;v++}else os(o[f]),f--;else os(o[h]),h++;for(;v<=P;){const H=Ct(e,c[P+1]);Ve(H,r[v]),c[v++]=H}for(;h<=f;){const H=o[h++];H!==null&&os(H)}return this.ut=n,ug(e,c),Ue}}),mg="pi-web:chat-groups:",vg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Ir(e));return t===null||t===""?void 0:wg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Ir(e),JSON.stringify(t))}catch{}}};class bg{constructor(t=vg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Cr(r,this.openGroupKeys)&&Cr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Ir(e){return`${mg}${e}`}function wg(e){if(Array.isArray(e))return{open:rs(e),closedDefaultOpen:[]};if(yg(e))return{open:Array.isArray(e.open)?rs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?rs(e.closedDefaultOpen):[]}}function rs(e){return e.filter(t=>typeof t=="string")}function Cr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function yg(e){return typeof e=="object"&&e!==null}function Sg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(v=>Mr(a,v)),u=a.parts.filter(v=>!Mr(a,v)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const v=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...f},index:h})}}),n(),i}function xg(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function Mr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const kg=30;function $g(e,t){const i=Rg(Mg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Pg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ig(s,t.markerOffset);return}e.scrollTop=Cg(e.scrollHeight,t.distanceFromBottom)}function Rg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function Ig(e,t){return e-t}function Cg(e,t){return Math.max(0,e-t)}function Mg(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const Ag=600,Tg=1;function Eg(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Dg(e)||Wg(e)}function Dg(e){return e.scrollTop<(e.topThreshold??Math.max(Ag,e.clientHeight))}function Wg(e){return e.scrollHeight<=e.clientHeight+Tg}const _g="pi-web:chat-scroll:",Og=180,Lg=48,jg=2,Ng={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},zg={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Fg{constructor(t=Ng,i=zg){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=Og){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=jg){if(t===""||i===void 0||!as(i))return"skipped";try{if(ua(i,o)){const a={mode:"bottom"};return this.storage.setItem(ns(t),JSON.stringify(a)),"saved"}const r=Hg(i,s);if(r===void 0)return"skipped";const n=Ug(i,r);return this.storage.setItem(ns(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!as(i))return{status:"skipped"};const r=qg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(ns(t));if(i===null||i==="")return;const s=JSON.parse(i);return Bg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!as(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ns(e){return`${_g}${e}`}function Bg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function as(e){return e.clientHeight>0&&e.scrollHeight>0}function ha(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ua(e,t=Lg){return ha(e)<t}function Ug(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:lo(t)??"",offset:t.getBoundingClientRect().top-i}}function Hg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(lo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Ar(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function qg(e,t){return e.find(i=>lo(i)===t)}function lo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var Kg=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,co=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kg(t,i,o),o};let jt=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Tr(this.positionPercent),t=Tr(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
|
|
769
792
|
<div
|
|
770
793
|
class="meter"
|
|
771
794
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -781,21 +804,21 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
781
804
|
<div class="marker"></div>
|
|
782
805
|
</div>
|
|
783
806
|
</div>
|
|
784
|
-
`}};
|
|
807
|
+
`}};jt.styles=O`
|
|
785
808
|
:host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
|
|
786
809
|
:host(:hover), :host(:focus-within) { opacity: .92; }
|
|
787
810
|
.meter { height: 100%; }
|
|
788
811
|
.track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
|
|
789
812
|
.progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
|
|
790
813
|
.marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
|
|
791
|
-
`;
|
|
792
|
-
]`).replace("lheading",
|
|
793
|
-
`),i=t.length-1;for(;i>=0&&
|
|
794
|
-
`)}function
|
|
814
|
+
`;co([d({type:Number})],jt.prototype,"positionPercent",2);co([d({type:Number})],jt.prototype,"loadedPercent",2);jt=co([D("conversation-meter")],jt);function Tr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class As extends ao{constructor(t){if(super(t),this.it=F,t.type!==ro.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}As.directiveName="unsafeHTML",As.resultType=1;const Gg=no(As);function po(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var it=po();function fa(e){it=e}var Ge={exec:()=>null};function ct(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(Z.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var Qg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Z={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ct(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ct(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ct(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ct(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ct(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ct(e=>new RegExp(`^ {0,${e}}>`))},Zg=/^(?:[ \t]*(?:\n|$))+/,Jg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Xg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Yg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ho=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ga=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ma=I(ga).replace(/bull/g,ho).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),em=I(ga).replace(/bull/g,ho).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),uo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,tm=/^[^\n]+/,fo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,im=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",fo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sm=I(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ho).getRegex(),Fi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",go=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,om=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",go).replace("tag",Fi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),va=I(uo).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),rm=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",va).getRegex(),mo={blockquote:rm,code:Jg,def:im,fences:Xg,heading:Yg,hr:qt,html:om,lheading:ma,list:sm,newline:Zg,paragraph:va,table:Ge,text:tm},Er=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex(),nm={...mo,lheading:em,table:Er,paragraph:I(uo).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Fi).getRegex()},am={...mo,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",go).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(uo).replace("hr",qt).replace("heading",` *#{1,6} *[^
|
|
815
|
+
]`).replace("lheading",ma).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,cm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ba=/^( {2,}|\\)\n(?!\s*$)/,dm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,bt=/[\p{P}\p{S}]/u,Bi=/[\s\p{P}\p{S}]/u,vo=/[^\s\p{P}\p{S}]/u,pm=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Bi).getRegex(),wa=/(?!~)[\p{P}\p{S}]/u,hm=/(?!~)[\s\p{P}\p{S}]/u,um=/(?:[^\s\p{P}\p{S}]|~)/u,fm=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Qg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ya=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gm=I(ya,"u").replace(/punct/g,bt).getRegex(),mm=I(ya,"u").replace(/punct/g,wa).getRegex(),Sa="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",vm=I(Sa,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),bm=I(Sa,"gu").replace(/notPunctSpace/g,um).replace(/punctSpace/g,hm).replace(/punct/g,wa).getRegex(),wm=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),ym=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,bt).getRegex(),Sm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",xm=I(Sm,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Bi).replace(/punct/g,bt).getRegex(),km=I(/\\(punct)/,"gu").replace(/punct/g,bt).getRegex(),$m=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Pm=I(go).replace("(?:-->|$)","-->").getRegex(),Rm=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Pm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),$i=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Im=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",$i).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xa=I(/^!?\[(label)\]\[(ref)\]/).replace("label",$i).replace("ref",fo).getRegex(),ka=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",fo).getRegex(),Cm=I("reflink|nolink(?!\\()","g").replace("reflink",xa).replace("nolink",ka).getRegex(),Dr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bo={_backpedal:Ge,anyPunctuation:km,autolink:$m,blockSkip:fm,br:ba,code:cm,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:gm,emStrongRDelimAst:vm,emStrongRDelimUnd:wm,escape:lm,link:Im,nolink:ka,punctuation:pm,reflink:xa,reflinkSearch:Cm,tag:Rm,text:dm,url:Ge},Mm={...bo,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",$i).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$i).getRegex()},Ts={...bo,emStrongRDelimAst:bm,emStrongLDelim:mm,delLDelim:ym,delRDelim:xm,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Dr).getRegex()},Am={...Ts,br:I(ba).replace("{2,}","*").getRegex(),text:I(Ts.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Jt={normal:mo,gfm:nm,pedantic:am},Mt={normal:bo,gfm:Ts,breaks:Am,pedantic:Mm},Tm={"&":"&","<":"<",">":">",'"':""","'":"'"},Wr=e=>Tm[e];function Ae(e,t){if(t){if(Z.escapeTest.test(e))return e.replace(Z.escapeReplace,Wr)}else if(Z.escapeTestNoEncode.test(e))return e.replace(Z.escapeReplaceNoEncode,Wr);return e}function _r(e){try{e=encodeURI(e).replace(Z.percentDecode,"%")}catch{return null}return e}function Or(e,t){let i=e.replace(Z.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(Z.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(Z.slashPipe,"|");return s}function Fe(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Lr(e){let t=e.split(`
|
|
816
|
+
`),i=t.length-1;for(;i>=0&&Z.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
|
|
817
|
+
`)}function Em(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function Dm(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function jr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function Wm(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
|
|
795
818
|
`).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
|
|
796
|
-
`)}var
|
|
797
|
-
`),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:
|
|
798
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=
|
|
819
|
+
`)}var Pi=class{options;rules;lexer;constructor(e){this.options=e||it}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Lr(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=Wm(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=Fe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Fe(t[0],`
|
|
820
|
+
`),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Fe(t[0],`
|
|
821
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Fe(t[0],`
|
|
799
822
|
`).split(`
|
|
800
823
|
`),s="",o="",r=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
|
|
801
824
|
`),u=p.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -803,23 +826,23 @@ This only removes it from PI WEB; it will not change the project folder.`)&&this
|
|
|
803
826
|
${p}`:p,o=o?`${o}
|
|
804
827
|
${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let v=f,P=v.raw+`
|
|
805
828
|
`+i.join(`
|
|
806
|
-
`),
|
|
829
|
+
`),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-v.raw.length)+H.raw,o=o.substring(0,o.length-v.text.length)+H.text;break}else if(f?.type==="list"){let v=f,P=v.raw+`
|
|
807
830
|
`+i.join(`
|
|
808
|
-
`),
|
|
809
|
-
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=
|
|
831
|
+
`),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-f.raw.length)+H.raw,o=o.substring(0,o.length-v.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
|
|
832
|
+
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Dm(t[2].split(`
|
|
810
833
|
`,1)[0],t[1].length),f=e.split(`
|
|
811
834
|
`,1)[0],v=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):v?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),v&&this.rules.other.blankLine.test(f)&&(p+=f+`
|
|
812
|
-
`,e=e.substring(f.length+1),c=!0),!c){let
|
|
813
|
-
`,1)[0],
|
|
814
|
-
`+
|
|
815
|
-
`+f}v=!f.trim(),p+=
|
|
816
|
-
`,e=e.substring(
|
|
817
|
-
`),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=
|
|
818
|
-
`):[],r={type:"table",raw:
|
|
819
|
-
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(
|
|
835
|
+
`,e=e.substring(f.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),rt=this.rules.other.hrRegex(P),wt=this.rules.other.fencesBeginRegex(P),So=this.rules.other.headingBeginRegex(P),_a=this.rules.other.htmlBeginRegex(P),Oa=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Hi=e.split(`
|
|
836
|
+
`,1)[0],yt;if(f=Hi,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),yt=f):yt=f.replace(this.rules.other.tabCharGlobal," "),wt.test(f)||So.test(f)||_a.test(f)||Oa.test(f)||H.test(f)||rt.test(f))break;if(yt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
|
|
837
|
+
`+yt.slice(P);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||wt.test(h)||So.test(h)||rt.test(h))break;u+=`
|
|
838
|
+
`+f}v=!f.trim(),p+=Hi+`
|
|
839
|
+
`,e=e.substring(Hi.length+1),h=yt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Lr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Fe(t[0],`
|
|
840
|
+
`),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Or(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
841
|
+
`):[],r={type:"table",raw:Fe(t[0],`
|
|
842
|
+
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Or(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Fe(t[0],`
|
|
820
843
|
`),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
|
|
821
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=
|
|
822
|
-
`),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(
|
|
844
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Fe(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=Em(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),jr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return jr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},ke=class Es{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||it,this.options.tokenizer=this.options.tokenizer||new Pi,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:Z,block:Jt.normal,inline:Mt.normal};this.options.pedantic?(i.block=Jt.pedantic,i.inline=Mt.pedantic):this.options.gfm&&(i.block=Jt.gfm,this.options.breaks?i.inline=Mt.breaks:i.inline=Mt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Jt,inline:Mt}}static lex(t,i){return new Es(i).lex(t)}static lexInline(t,i){return new Es(i).inlineTokens(t)}lex(t){t=t.replace(Z.carriageReturn,`
|
|
845
|
+
`),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Z.tabCharGlobal," ").replace(Z.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
|
|
823
846
|
`:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
824
847
|
`)?"":`
|
|
825
848
|
`)+r.raw,a.text+=`
|
|
@@ -832,9 +855,9 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
832
855
|
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
833
856
|
`)?"":`
|
|
834
857
|
`)+r.raw,a.text+=`
|
|
835
|
-
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},
|
|
836
|
-
`;return s?'<pre><code class="language-'+
|
|
837
|
-
`:"<pre><code>"+(i?o:
|
|
858
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),v;this.options.extensions.startInline.forEach(P=>{v=P.call({lexer:this},f),typeof v=="number"&&v>=0&&(h=Math.min(h,v))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Ri=class{options;parser;constructor(e){this.options=e||it}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Z.notSpaceStart)?.[0],o=e.replace(Z.endingNewline,"")+`
|
|
859
|
+
`;return s?'<pre><code class="language-'+Ae(s)+'">'+(i?o:Ae(o,!0))+`</code></pre>
|
|
860
|
+
`:"<pre><code>"+(i?o:Ae(o,!0))+`</code></pre>
|
|
838
861
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
839
862
|
${this.parser.parse(e)}</blockquote>
|
|
840
863
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -850,19 +873,19 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
850
873
|
`}tablerow({text:e}){return`<tr>
|
|
851
874
|
${e}</tr>
|
|
852
875
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
|
|
853
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${
|
|
854
|
-
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+
|
|
876
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Ae(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=_r(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ae(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=_r(e);if(o===null)return Ae(i);e=o;let r=`<img src="${e}" alt="${Ae(i)}"`;return t&&(r+=` title="${Ae(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ae(e.text)}},wo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class Ds{options;renderer;textRenderer;constructor(t){this.options=t||it,this.options.renderer=this.options.renderer||new Ri,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new wo}static parse(t,i){return new Ds(i).parse(t)}static parseInline(t,i){return new Ds(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},Tt=class{options;block;constructor(e){this.options=e||it}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},_m=class{defaults=po();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ri;TextRenderer=wo;Lexer=ke;Tokenizer=Pi;Hooks=Tt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ri(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Pi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new Tt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];Tt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&Tt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
|
|
877
|
+
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ae(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},et=new _m;function T(e,t){return et.parse(e,t)}T.options=T.setOptions=function(e){return et.setOptions(e),T.defaults=et.defaults,fa(T.defaults),T};T.getDefaults=po;T.defaults=it;T.use=function(...e){return et.use(...e),T.defaults=et.defaults,fa(T.defaults),T};T.walkTokens=function(e,t){return et.walkTokens(e,t)};T.parseInline=et.parseInline;T.Parser=$e;T.parser=$e.parse;T.Renderer=Ri;T.TextRenderer=wo;T.Lexer=ke;T.lexer=ke.lex;T.Tokenizer=Pi;T.Hooks=Tt;T.parse=T;T.options;T.setOptions;T.use;T.walkTokens;T.parseInline;$e.parse;ke.lex;const $a=new T.Renderer;$a.html=({text:e})=>jm(e);const Om=300,At=new Map;function Lm(e){const t=At.get(e);if(t!==void 0)return t;const i=T.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$a}),s=Nm(i);if(At.set(e,s),At.size>Om){const o=At.keys().next().value;o!==void 0&&At.delete(o)}return s}function jm(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function Nm(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!zm(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function zm(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Fm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,Pa=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};let Ii=class extends C{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${Gg(Lm(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="Copy code block",s.setAttribute("aria-label","Copy code block");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Um(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"Copied code block":t==="failed"?"Failed to copy code block":"Copy code block";e.title=s,e.setAttribute("aria-label",s)}};Ii.styles=Uf;Pa([d()],Ii.prototype,"text",2);Ii=Pa([D("formatted-text")],Ii);async function Um(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var Hm=Object.defineProperty,qm=Object.getOwnPropertyDescriptor,Kt=(e,t,i,s)=>{for(var o=s>1?void 0:s?qm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hm(t,i,o),o};const Nr=180;let tt=class extends C{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=Km(e.args),s=Vm(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Gm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
|
|
855
878
|
<section class=${`tool-card ${e.status}`}>
|
|
856
879
|
<div class="tool-header">
|
|
857
880
|
<div class="tool-title">
|
|
858
|
-
<span class="status-icon" aria-hidden="true">${
|
|
881
|
+
<span class="status-icon" aria-hidden="true">${Zm(e.status)}</span>
|
|
859
882
|
<strong>${e.toolName}</strong>
|
|
860
883
|
${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
|
|
861
884
|
</div>
|
|
862
885
|
<div class="tool-meta">
|
|
863
|
-
${
|
|
886
|
+
${zr(e)===void 0?null:l`<span>${zr(e)}</span>`}
|
|
864
887
|
${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
|
|
865
|
-
<span class="status-label">${
|
|
888
|
+
<span class="status-label">${Jm(e.status)}</span>
|
|
866
889
|
</div>
|
|
867
890
|
</div>
|
|
868
891
|
|
|
@@ -877,7 +900,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
877
900
|
<pre>${e}</pre>
|
|
878
901
|
</details>
|
|
879
902
|
`}renderDiffBody(e,t){const i=e.split(`
|
|
880
|
-
`),s=!this.showFullDiff&&i.length>
|
|
903
|
+
`),s=!this.showFullDiff&&i.length>Nr,o=s?i.slice(0,Nr):i;return l`
|
|
881
904
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
|
|
882
905
|
<summary>
|
|
883
906
|
<span>${t}</span>
|
|
@@ -887,14 +910,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
887
910
|
<span>${s?`Showing ${String(o.length)} of ${String(i.length)} lines`:"Full diff"}</span>
|
|
888
911
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
|
|
889
912
|
</div>
|
|
890
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${
|
|
913
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Qm(r)}>${r}</span>`)}</code></pre>
|
|
891
914
|
${s?l`
|
|
892
915
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
893
916
|
Show all ${String(i.length)} diff lines
|
|
894
917
|
</button>
|
|
895
918
|
`:null}
|
|
896
919
|
</details>
|
|
897
|
-
`}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};
|
|
920
|
+
`}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};tt.styles=O`
|
|
898
921
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
899
922
|
.tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
|
|
900
923
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -934,19 +957,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
934
957
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
935
958
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
936
959
|
.show-more { justify-self: start; }
|
|
937
|
-
`;
|
|
938
|
-
`))
|
|
960
|
+
`;Kt([d({attribute:!1})],tt.prototype,"execution",2);Kt([w()],tt.prototype,"showFullDiff",2);Kt([w()],tt.prototype,"copied",2);Kt([w()],tt.prototype,"diffOpen",2);tt=Kt([D("tool-execution-view")],tt);function Km(e){return Ws(e,"path")??Ws(e,"file_path")}function zr(e){if(e.toolName!=="edit")return;const t=li(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof li(e.args,"oldText")=="string"&&typeof li(e.args,"newText")=="string")return"1 edit"}function Vm(e){return Ws(e,"diff")}function Gm(e){let t=0,i=0;for(const s of e.split(`
|
|
961
|
+
`))Ra(s)?t++:Ia(s)&&i++;return{added:t,removed:i}}function Qm(e){return Ra(e)?"added":Ia(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Ra(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ia(e){return e.startsWith("-")&&!e.startsWith("---")}function Zm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Jm(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Xm(e){return typeof e=="object"&&e!==null}function li(e,t){return Xm(e)?e[t]:void 0}function Ws(e,t){const i=li(e,t);return typeof i=="string"?i:void 0}var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ym(t,i,o),o};const tv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),iv=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ls=["You opened this chat while the assistant was already replying. The complete answer will appear shortly.","We joined mid-sentence. Holding the curtain until the full reply is ready.","The assistant started before this tab arrived. We’ll show the full answer when it lands.","Catching the reply in one piece — no spoilers, no half-answers.","The tokens are still assembling themselves. Full answer incoming.","We arrived fashionably late to this response. The complete version will appear soon."];function Fr(){return ls[Math.floor(Math.random()*ls.length)]??ls[0]}function Br(e){return ci(e,0,100)}function ci(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let z=class extends C{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new bg,this.scrollController=new Fg,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
|
|
939
962
|
<div class="chat-wrap">
|
|
940
963
|
${this.renderConversationRail()}
|
|
941
964
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
|
|
942
965
|
${this.renderHistoryBoundary()}
|
|
943
|
-
${
|
|
966
|
+
${gg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
|
|
944
967
|
${this.renderQueuedMessages()}
|
|
945
968
|
${this.renderSessionActivity()}
|
|
946
969
|
</div>
|
|
947
970
|
${this.renderActivityDock()}
|
|
948
971
|
</div>
|
|
949
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
972
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Sg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
|
|
973
|
+
<div class="activity-dock active" aria-live="polite">
|
|
974
|
+
<span class="dot"></span>
|
|
975
|
+
<span class="activity-text">Sending your message…</span>
|
|
976
|
+
</div>
|
|
977
|
+
`;const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
|
|
950
978
|
<div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
|
|
951
979
|
<span class="dot"></span>
|
|
952
980
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
@@ -975,7 +1003,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
975
1003
|
<span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
|
|
976
1004
|
${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
|
|
977
1005
|
</aside>
|
|
978
|
-
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?
|
|
1006
|
+
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Fr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Fr(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;return t===void 0||e!=="idle"&&t.phase==="idle"?e:t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?Br(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=ci(this.currentConversationIndex??t,0,e-1);return Br(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
|
|
979
1007
|
<div class="history-boundary">
|
|
980
1008
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
|
|
981
1009
|
<span>Scroll up to load earlier messages</span>
|
|
@@ -992,7 +1020,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
992
1020
|
<details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
|
|
993
1021
|
<summary>
|
|
994
1022
|
<b class="label">${s?"live events":"events"}</b>
|
|
995
|
-
<span>${
|
|
1023
|
+
<span>${xg(e)}</span>
|
|
996
1024
|
</summary>
|
|
997
1025
|
<div class="group-body">
|
|
998
1026
|
${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
|
|
@@ -1019,7 +1047,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1019
1047
|
</div>
|
|
1020
1048
|
`}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
|
|
1021
1049
|
|
|
1022
|
-
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:
|
|
1050
|
+
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:tv.format(t),full:iv.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
|
|
1023
1051
|
<details class="part skill-invocation">
|
|
1024
1052
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
1025
1053
|
<small>${e.location}</small>
|
|
@@ -1030,50 +1058,95 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1030
1058
|
<strong>Loaded ${e.name}</strong>
|
|
1031
1059
|
<small>read ${e.path}</small>
|
|
1032
1060
|
</div>
|
|
1033
|
-
`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
|
|
1061
|
+
`:e.type==="image"?l`<img class="part chat-image" src=${`data:${e.mimeType};base64,${e.data}`} alt="attached image" loading="lazy" />`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
|
|
1034
1062
|
<details class="part" ?open=${e.isError}>
|
|
1035
1063
|
<summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
|
|
1036
1064
|
<formatted-text .text=${e.text}></formatted-text>
|
|
1037
1065
|
</details>
|
|
1038
|
-
`:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&
|
|
1066
|
+
`:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&Eg({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?ua(e):!0}isAtBottom(){const e=this.chat;return e?ha(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return $g(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Pg(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<kg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=ci(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ci(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Ar(e,t)??Ar(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};z.styles=Bf;U([d({attribute:!1})],z.prototype,"messages",2);U([d()],z.prototype,"sessionId",2);U([d({type:Number})],z.prototype,"messageStart",2);U([d({type:Number})],z.prototype,"messageEnd",2);U([d({type:Number})],z.prototype,"messageTotal",2);U([d({type:Boolean})],z.prototype,"hasMore",2);U([d({type:Boolean})],z.prototype,"loadingMore",2);U([d({type:Boolean})],z.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],z.prototype,"isSendingPrompt",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Number})],z.prototype,"pendingMessageCount",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"activity",2);U([d({attribute:!1})],z.prototype,"onLoadMore",2);U([B(".chat")],z.prototype,"chat",2);U([w()],z.prototype,"pinnedToBottom",2);U([w()],z.prototype,"expandedMetaKey",2);U([w()],z.prototype,"copiedMessageKey",2);U([w()],z.prototype,"currentConversationIndex",2);U([w()],z.prototype,"loadMoreRequested",2);z=U([D("chat-view")],z);const sv=["image/jpeg","image/png","image/gif","image/webp"],ov=new Set(sv);function rv(e){return typeof e=="string"&&ov.has(e)}function nv(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const av="Only PNG, JPEG, GIF, and WebP images are supported.",lv="Failed to read an attachment.";async function cv(e,t){const i=[];let s;for(const o of e){if(!rv(o.type)){s=av;continue}try{const r=await t(o);i.push({name:dv(o),mimeType:o.type,data:r,size:o.size})}catch{s=lv}}return{attachments:i,...s===void 0?{}:{error:s}}}function dv(e){return e.name!==""?e.name:`pasted-image.${nv(e.type)}`}const Ca="pi-web:attachment-delivery";function Ma(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function pv(e=Ma()){try{return e?.getItem(Ca)==="folder"?"folder":"inline"}catch{return"inline"}}function hv(e,t=Ma()){try{t?.setItem(Ca,e)}catch{}}function uv(){return he`
|
|
1067
|
+
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1068
|
+
<path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
|
|
1069
|
+
</svg>
|
|
1070
|
+
`}function Aa(){return he`
|
|
1071
|
+
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1072
|
+
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
1073
|
+
<path d="M21 3 11.5 12.5"></path>
|
|
1074
|
+
</svg>
|
|
1075
|
+
`}function fv(){return he`
|
|
1076
|
+
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1077
|
+
<path d="M4 7h11"></path>
|
|
1078
|
+
<path d="M4 12h7"></path>
|
|
1079
|
+
<path d="M4 17h7"></path>
|
|
1080
|
+
<path d="m15 14 5 3-5 3z"></path>
|
|
1081
|
+
</svg>
|
|
1082
|
+
`}function gv(){return Aa()}function mv(){return he`
|
|
1083
|
+
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1084
|
+
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
1085
|
+
</svg>
|
|
1086
|
+
`}function vv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,f=20-h,v=p<e.filled;return he`<rect class=${v?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${f} width=${n} height=${h} rx="1"></rect>`});return he`
|
|
1087
|
+
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1088
|
+
${a}
|
|
1089
|
+
</svg>
|
|
1090
|
+
`}const bv=["off","minimal","low","medium","high","xhigh"];function _s(e){return e===void 0||e===""?"off":e}function wv(e,t){const i=t.length>=2?t:bv,s=i.length-1,o=_s(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class yv extends ao{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===ro.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const yo=no(yv);var Sv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Ui=(e,t,i,s)=>{for(var o=s>1?void 0:s?xv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sv(t,i,o),o};let gt=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
|
|
1039
1091
|
<div class="menu">
|
|
1040
1092
|
${this.items.map((e,t)=>l`
|
|
1041
|
-
<button class=${t===this.selectedIndex?"selected":""} ${
|
|
1093
|
+
<button class=${t===this.selectedIndex?"selected":""} ${yo(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
|
|
1042
1094
|
<strong>${e.insertText}</strong>
|
|
1043
1095
|
<span>${e.detail}</span>
|
|
1044
1096
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1045
1097
|
</button>
|
|
1046
1098
|
`)}
|
|
1047
1099
|
</div>
|
|
1048
|
-
`:null}};
|
|
1049
|
-
<footer class=${t?"shell-mode":""}>
|
|
1100
|
+
`:null}};gt.styles=qf;Ui([d({attribute:!1})],gt.prototype,"items",2);Ui([d({type:Number})],gt.prototype,"selectedIndex",2);Ui([d({attribute:!1})],gt.prototype,"onPick",2);gt=Ui([D("autocomplete-menu")],gt);var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,L=(e,t,i,s)=>{for(var o=s>1?void 0:s?$v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kv(t,i,o),o};let _=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=pv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new xo,this.readOnlyCompartment=new xo}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Xt(i,t);s!==void 0&&vi(s,this.draft);const o=Xt(this.machineId,this.sessionId);this.draft=o!==void 0?Pn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=Js(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
|
|
1101
|
+
<footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
|
|
1050
1102
|
<div class="editor-wrap">
|
|
1051
1103
|
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
|
|
1104
|
+
<input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${o=>{this.handleFileInput(o)}} />
|
|
1105
|
+
<button class="editor-attach icon-button" ?disabled=${s} title="Attach images" aria-label="Attach images" @click=${()=>{this.attachmentInput?.click()}}>${uv()}</button>
|
|
1052
1106
|
${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
|
|
1053
1107
|
${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
1054
|
-
|
|
1108
|
+
${this.renderAttachments()}
|
|
1109
|
+
<autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${o=>{this.pick(o)}}></autocomplete-menu>
|
|
1055
1110
|
</div>
|
|
1056
1111
|
<div class="actions">
|
|
1057
1112
|
${this.renderCompactStatus()}
|
|
1058
|
-
<button ?disabled=${
|
|
1059
|
-
${this.canSteer&&!this.isCompacting?l`<button ?disabled=${
|
|
1060
|
-
<button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} @click=${()=>this.onStop?.()}
|
|
1113
|
+
<button class="icon-button send-button" ?disabled=${s} title=${i?"Queue until the current activity finishes":"Send message"} aria-label=${i?"Queue message":"Send message"} @click=${()=>{this.send("followUp")}}>${i?fv():Aa()}</button>
|
|
1114
|
+
${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send("steer")}}>${gv()}</button>`:null}
|
|
1115
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${mv()}</button>
|
|
1061
1116
|
</div>
|
|
1062
1117
|
</footer>
|
|
1063
1118
|
`}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"no model",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
|
|
1064
1119
|
<div class="compact-status" aria-label="Session status">
|
|
1065
1120
|
<button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
|
|
1066
|
-
<button class="select-thinking" title
|
|
1121
|
+
<button class="select-thinking icon-button" title=${`Thinking level: ${_s(e.thinkingLevel)}`} aria-label=${`Thinking level: ${_s(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${vv(wv(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
1122
|
+
</div>
|
|
1123
|
+
`}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:l`
|
|
1124
|
+
<div class="attachments" aria-label="Pending attachments">
|
|
1125
|
+
${this.attachments.map(e=>l`
|
|
1126
|
+
<div class="attachment-chip" title=${e.name}>
|
|
1127
|
+
<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />
|
|
1128
|
+
<button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
1129
|
+
</div>
|
|
1130
|
+
`)}
|
|
1131
|
+
${this.attachments.length>0?l`
|
|
1132
|
+
<label class="attachment-delivery" title="How attachments are delivered to the agent">
|
|
1133
|
+
<select .value=${this.attachmentDelivery} @change=${e=>{this.changeDelivery(e)}}>
|
|
1134
|
+
<option value="inline">Attach to message</option>
|
|
1135
|
+
<option value="folder">Save to .pi-web/attachments</option>
|
|
1136
|
+
</select>
|
|
1137
|
+
</label>
|
|
1138
|
+
`:null}
|
|
1139
|
+
${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
|
|
1067
1140
|
</div>
|
|
1068
|
-
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new
|
|
1141
|
+
`}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",hv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Ur(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=Ur(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await cv(e,Iv);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new nt({parent:this.editorHost,state:qi.create({doc:this.draft,extensions:[La(),Va(),ja(),Na.of(" "),za(Ka,{fallback:!0}),nt.lineWrapping,nt.contentAttributes.of(e=>Av(e.state.sliceDoc(0,e.state.selection.main.head))),Fa("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(nt.editable.of(!this.disabled)),this.readOnlyCompartment.of(qi.readOnly.of(this.disabled)),nt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ba.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Ga(e)||qa(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>ko.shift?.(e)??!1},{key:"Backspace",run:e=>Qa(e)},...Ua,...Ha])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:$o.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(nt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(qi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Xt(this.machineId,this.sessionId);t!==void 0&&vi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await j.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(Pv);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await j.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(Rv);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=En(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Tn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):ko.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:$o.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=Xt(this.machineId,this.sessionId);e!==void 0&&Zs(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};_.styles=Vf;L([d({type:Boolean})],_.prototype,"disabled",2);L([d()],_.prototype,"sessionId",2);L([d()],_.prototype,"cwd",2);L([d()],_.prototype,"machineId",2);L([d()],_.prototype,"projectId",2);L([d()],_.prototype,"workspaceId",2);L([d({type:Boolean})],_.prototype,"workspaceScopedFileSuggestions",2);L([d({type:Boolean})],_.prototype,"canSteer",2);L([d({type:Boolean})],_.prototype,"isCompacting",2);L([d({type:Boolean})],_.prototype,"canStop",2);L([d({attribute:!1})],_.prototype,"status",2);L([d({type:Boolean})],_.prototype,"sending",2);L([d({attribute:!1})],_.prototype,"onSend",2);L([d({attribute:!1})],_.prototype,"onStop",2);L([d({attribute:!1})],_.prototype,"onSelectModel",2);L([d({attribute:!1})],_.prototype,"onSelectThinking",2);L([d({attribute:!1})],_.prototype,"availableThinkingLevels",2);L([B(".markdown-editor")],_.prototype,"editorHost",2);L([B(".attachment-input")],_.prototype,"attachmentInput",2);L([w()],_.prototype,"draft",2);L([w()],_.prototype,"completions",2);L([w()],_.prototype,"selectedIndex",2);L([w()],_.prototype,"attachments",2);L([w()],_.prototype,"attachmentDelivery",2);L([w()],_.prototype,"attachmentError",2);_=L([D("prompt-editor")],_);function Xt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return $n(e,t)}function Pv(){return[]}function Rv(){return[]}function Ur(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function Iv(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("Failed to read file"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("Unexpected file reader result"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const Cv={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Mv={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Av(e){return Js(e).kind==="normal"?Cv:Mv}function Yt(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function Tv(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,Ta=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ev(t,i,o),o};let Ci=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Yt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Yt(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
|
|
1069
1142
|
<div class="bar">
|
|
1070
|
-
<span>↑${
|
|
1071
|
-
<span>↓${
|
|
1143
|
+
<span>↑${Yt(s.input)}</span>
|
|
1144
|
+
<span>↓${Yt(s.output)}</span>
|
|
1072
1145
|
<span class="context">${i}</span>
|
|
1073
|
-
<span>${
|
|
1146
|
+
<span>${Tv(e.cost)}</span>
|
|
1074
1147
|
${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
|
|
1075
1148
|
</div>
|
|
1076
|
-
`}};
|
|
1149
|
+
`}};Ci.styles=Hf;Ta([d({attribute:!1})],Ci.prototype,"status",2);Ci=Ta([D("status-bar")],Ci);var Wv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?_v(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wv(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
|
|
1077
1150
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1078
1151
|
<section @mousedown=${t=>{t.stopPropagation()}}>
|
|
1079
1152
|
<header>
|
|
@@ -1083,7 +1156,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1083
1156
|
${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
|
|
1084
1157
|
<div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
|
|
1085
1158
|
${e.map((t,i)=>l`
|
|
1086
|
-
<button class=${i===this.selectedIndex?"selected":""} ${
|
|
1159
|
+
<button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
|
|
1087
1160
|
<span>${t.label}</span>
|
|
1088
1161
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1089
1162
|
</button>
|
|
@@ -1092,7 +1165,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1092
1165
|
</div>
|
|
1093
1166
|
</section>
|
|
1094
1167
|
</div>
|
|
1095
|
-
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};
|
|
1168
|
+
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=ca;Ne([d()],Re.prototype,"title",2);Ne([d({type:Boolean})],Re.prototype,"searchable",2);Ne([d({attribute:!1})],Re.prototype,"options",2);Ne([d({attribute:!1})],Re.prototype,"selectedValue",2);Ne([d({attribute:!1})],Re.prototype,"onPick",2);Ne([d({attribute:!1})],Re.prototype,"onCancel",2);Ne([w()],Re.prototype,"selectedIndex",2);Ne([w()],Re.prototype,"query",2);Re=Ne([D("command-picker")],Re);var Ov=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?Lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ov(t,i,o),o};let Le=class extends C{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
|
|
1096
1169
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1097
1170
|
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1098
1171
|
<header>
|
|
@@ -1105,19 +1178,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1105
1178
|
</header>
|
|
1106
1179
|
<div class="options">
|
|
1107
1180
|
${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
|
|
1108
|
-
<button class=${i===this.selectedIndex?"selected":""} ${
|
|
1181
|
+
<button class=${i===this.selectedIndex?"selected":""} ${yo(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
|
|
1109
1182
|
<span class="main">
|
|
1110
1183
|
<strong>${t.title}</strong>
|
|
1111
1184
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1112
1185
|
</span>
|
|
1113
|
-
${t.shortcut!==void 0?l`<kbd>${
|
|
1186
|
+
${t.shortcut!==void 0?l`<kbd>${ni(t.shortcut)}</kbd>`:null}
|
|
1114
1187
|
${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
|
|
1115
1188
|
</button>
|
|
1116
1189
|
`)}
|
|
1117
1190
|
</div>
|
|
1118
1191
|
</section>
|
|
1119
1192
|
</div>
|
|
1120
|
-
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};
|
|
1193
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Le.styles=Kf;st([d({attribute:!1})],Le.prototype,"actions",2);st([d({attribute:!1})],Le.prototype,"onRun",2);st([d({attribute:!1})],Le.prototype,"onCancel",2);st([B("input")],Le.prototype,"input",2);st([w()],Le.prototype,"queryText",2);st([w()],Le.prototype,"selectedIndex",2);Le=st([D("action-palette")],Le);var jv=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&jv(t,i,o),o};let se=class extends C{render(){const e=this.state;return e===void 0?null:l`
|
|
1121
1194
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
1122
1195
|
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1123
1196
|
<header>
|
|
@@ -1140,11 +1213,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1140
1213
|
<div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"Saving…":"Save API key"}</button></div>
|
|
1141
1214
|
</div>
|
|
1142
1215
|
`;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>l`
|
|
1143
|
-
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${
|
|
1216
|
+
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Hr(t.authType)}</small></button>
|
|
1144
1217
|
`)}</div>`}}renderProviderButton(e){return l`
|
|
1145
1218
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
1146
|
-
<span>${e.name}${e.status.source!==void 0?l` <em>${
|
|
1147
|
-
<small>${e.id} · ${
|
|
1219
|
+
<span>${e.name}${e.status.source!==void 0?l` <em>${Fv(e)}</em>`:null}</span>
|
|
1220
|
+
<small>${e.id} · ${Hr(e.authType)}</small>
|
|
1148
1221
|
</button>
|
|
1149
1222
|
`}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
|
|
1150
1223
|
<div class="form">
|
|
@@ -1167,7 +1240,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1167
1240
|
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
|
|
1168
1241
|
${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
1169
1242
|
</div>
|
|
1170
|
-
`}focusInputIfNeeded(){const e=
|
|
1243
|
+
`}focusInputIfNeeded(){const e=zv(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};se.styles=[ca,O`
|
|
1171
1244
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
1172
1245
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
1173
1246
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -1182,7 +1255,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1182
1255
|
.progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
|
|
1183
1256
|
.inline-options { display: grid; gap: 8px; }
|
|
1184
1257
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
1185
|
-
`];
|
|
1258
|
+
`];be([d({attribute:!1})],se.prototype,"state",2);be([d({attribute:!1})],se.prototype,"onChooseMethod",2);be([d({attribute:!1})],se.prototype,"onSelectProvider",2);be([d({attribute:!1})],se.prototype,"onApiKeyInput",2);be([d({attribute:!1})],se.prototype,"onSaveApiKey",2);be([d({attribute:!1})],se.prototype,"onLogoutProvider",2);be([d({attribute:!1})],se.prototype,"onOAuthInput",2);be([d({attribute:!1})],se.prototype,"onOAuthRespond",2);be([d({attribute:!1})],se.prototype,"onOAuthCancel",2);be([d({attribute:!1})],se.prototype,"onCancel",2);be([B("input")],se.prototype,"input",2);se=be([D("auth-dialog")],se);function Hr(e){return e==="oauth"?"subscription":"API key"}function zv(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Fv(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ runtime";case"fallback":return"✓ custom key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let ge=class extends C{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await j.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
|
|
1186
1259
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1187
1260
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
1188
1261
|
<header>
|
|
@@ -1214,7 +1287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1214
1287
|
</footer>
|
|
1215
1288
|
</section>
|
|
1216
1289
|
</div>
|
|
1217
|
-
`}};
|
|
1290
|
+
`}};ge.styles=O`
|
|
1218
1291
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1219
1292
|
.backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
|
|
1220
1293
|
section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -1232,7 +1305,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1232
1305
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1233
1306
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1234
1307
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1235
|
-
`;
|
|
1308
|
+
`;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([w()],ge.prototype,"path",2);De([w()],ge.prototype,"createMissing",2);De([w()],ge.prototype,"suggestions",2);De([w()],ge.prototype,"selected",2);De([w()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([D("project-dialog")],ge);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Kv(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&cs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||cs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?cs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
|
|
1236
1309
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1237
1310
|
<section @click=${s=>{s.stopPropagation()}}>
|
|
1238
1311
|
<form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
|
|
@@ -1267,7 +1340,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1267
1340
|
</form>
|
|
1268
1341
|
</section>
|
|
1269
1342
|
</div>
|
|
1270
|
-
`}};
|
|
1343
|
+
`}};me.styles=O`
|
|
1271
1344
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1272
1345
|
.backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
|
|
1273
1346
|
section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -1287,8 +1360,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1287
1360
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1288
1361
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1289
1362
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1290
|
-
`;
|
|
1291
|
-
`):""
|
|
1363
|
+
`;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([w()],me.prototype,"url",2);We([w()],me.prototype,"name",2);We([w()],me.prototype,"token",2);We([w()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([D("machine-dialog")],me);function Kv(e){const t=e.trim();if(t==="")return"";const i=qr(t)??qr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Vv(t)}function cs(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function qr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Vv(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Gv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function Qv(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
|
|
1364
|
+
`):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
1365
|
+
`)??""}}function Zv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const n=Number(o);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:Jv(e.allowedHostsText);const r=Xv(e.allowedPathsText);return r.length>0&&(i.pathAccess={allowedPaths:r}),i}function Jv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Xv(e){const t=e.split(`
|
|
1366
|
+
`).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Yv(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Yv(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}var eb=Object.defineProperty,tb=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?tb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&eb(t,i,o),o};let ve=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Gv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Qv(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
|
|
1292
1367
|
<div class="section-heading">
|
|
1293
1368
|
<div>
|
|
1294
1369
|
<h2>General configuration</h2>
|
|
@@ -1309,7 +1384,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1309
1384
|
<span>Host</span>
|
|
1310
1385
|
${this.renderOverrideBadge("host")}
|
|
1311
1386
|
</span>
|
|
1312
|
-
<input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:
|
|
1387
|
+
<input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Kr(t)})}}>
|
|
1313
1388
|
<small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
|
|
1314
1389
|
</label>
|
|
1315
1390
|
|
|
@@ -1318,7 +1393,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1318
1393
|
<span>Port</span>
|
|
1319
1394
|
${this.renderOverrideBadge("port")}
|
|
1320
1395
|
</span>
|
|
1321
|
-
<input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:
|
|
1396
|
+
<input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Kr(t)})}}>
|
|
1322
1397
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
|
|
1323
1398
|
</label>
|
|
1324
1399
|
|
|
@@ -1327,14 +1402,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1327
1402
|
<span>Allowed hosts</span>
|
|
1328
1403
|
${this.renderOverrideBadge("allowedHosts")}
|
|
1329
1404
|
</span>
|
|
1330
|
-
<select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:
|
|
1405
|
+
<select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:ob(t)==="all"?"all":"list"})}}>
|
|
1331
1406
|
<option value="list">Only listed hosts</option>
|
|
1332
1407
|
<option value="all">Allow every host</option>
|
|
1333
1408
|
</select>
|
|
1334
|
-
<textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:
|
|
1409
|
+
<textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Vr(t)})}}></textarea>
|
|
1335
1410
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
1336
1411
|
</div>
|
|
1337
1412
|
|
|
1413
|
+
<label class="field">
|
|
1414
|
+
<span class="field-heading">
|
|
1415
|
+
<span>External filesystem roots</span>
|
|
1416
|
+
</span>
|
|
1417
|
+
<textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:Vr(t)})}}></textarea>
|
|
1418
|
+
<small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
|
|
1419
|
+
</label>
|
|
1420
|
+
|
|
1338
1421
|
${this.renderEffectiveConfig()}
|
|
1339
1422
|
|
|
1340
1423
|
<footer class="form-actions">
|
|
@@ -1348,10 +1431,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1348
1431
|
<dl>
|
|
1349
1432
|
<div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
1350
1433
|
<div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
|
|
1351
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
1434
|
+
<div><dt>Allowed hosts</dt><dd>${ib(e.allowedHosts)}</dd></div>
|
|
1435
|
+
<div><dt>External roots</dt><dd>${sb(e.pathAccess?.allowedPaths)}</dd></div>
|
|
1352
1436
|
</dl>
|
|
1353
1437
|
</section>
|
|
1354
|
-
`}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(
|
|
1438
|
+
`}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Zv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=rb(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=O`
|
|
1355
1439
|
:host { display: block; }
|
|
1356
1440
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1357
1441
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1393,7 +1477,103 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1393
1477
|
.section-heading .secondary { justify-self: start; }
|
|
1394
1478
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1395
1479
|
}
|
|
1396
|
-
`;
|
|
1480
|
+
`;_e([d({attribute:!1})],ve.prototype,"configResponse",2);_e([d({type:Boolean})],ve.prototype,"loading",2);_e([d({type:Boolean})],ve.prototype,"saving",2);_e([d()],ve.prototype,"error",2);_e([d()],ve.prototype,"savedMessage",2);_e([d({attribute:!1})],ve.prototype,"onReload",2);_e([d({attribute:!1})],ve.prototype,"onSave",2);_e([w()],ve.prototype,"draft",2);_e([w()],ve.prototype,"localError",2);ve=_e([D("settings-general-panel")],ve);function ib(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function sb(e){return e===void 0||e.length===0?l`<span class="muted">External paths denied</span>`:e.join(", ")}function Kr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function ob(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Vr(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function rb(e){return e instanceof Error?e.message:String(e)}var nb=Object.defineProperty,ab=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?ab(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&nb(t,i,o),o};let Ee=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return l`
|
|
1481
|
+
<div class="section-heading">
|
|
1482
|
+
<div>
|
|
1483
|
+
<h2>Session daemon</h2>
|
|
1484
|
+
<p>These settings affect the long-lived session runtime. Changes are saved to the config file immediately but only take effect after the session daemon restarts.</p>
|
|
1485
|
+
</div>
|
|
1486
|
+
<button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
|
|
1487
|
+
</div>
|
|
1488
|
+
${this.renderMessages()}
|
|
1489
|
+
<div class="restart-note" role="note">Restart required: run <code>pi-web restart</code> (or restart the session daemon service) after changing these settings.</div>
|
|
1490
|
+
${e===void 0&&this.loading?l`<div class="loading-card">Loading configuration…</div>`:l`
|
|
1491
|
+
<div class="config-path-card">
|
|
1492
|
+
<span>Config file</span>
|
|
1493
|
+
<code>${e?.path??"Unknown"}</code>
|
|
1494
|
+
</div>
|
|
1495
|
+
<div class="field">
|
|
1496
|
+
<span class="field-heading">
|
|
1497
|
+
<span>Allow agents to start sessions</span>
|
|
1498
|
+
${t?l`<span class="override-badge">environment override</span>`:null}
|
|
1499
|
+
</span>
|
|
1500
|
+
<label class="toggle">
|
|
1501
|
+
<input
|
|
1502
|
+
type="checkbox"
|
|
1503
|
+
.checked=${i}
|
|
1504
|
+
?disabled=${this.loading||this.saving||t}
|
|
1505
|
+
@change=${r=>{this.toggleSpawnSessions(r)}}
|
|
1506
|
+
>
|
|
1507
|
+
<span>Enable the <code>spawn_session</code> tool</span>
|
|
1508
|
+
</label>
|
|
1509
|
+
<small>When enabled, LLMs can start new sessions, constrained to a workspace (any worktree) of the same registered project so every spawned session stays visible here. On by default.</small>
|
|
1510
|
+
</div>
|
|
1511
|
+
<div class="field">
|
|
1512
|
+
<span class="field-heading">
|
|
1513
|
+
<span>Allow agents to start tracked subsessions</span>
|
|
1514
|
+
<span class="beta-badge">beta</span>
|
|
1515
|
+
${s?l`<span class="override-badge">environment override</span>`:null}
|
|
1516
|
+
</span>
|
|
1517
|
+
<label class="toggle">
|
|
1518
|
+
<input
|
|
1519
|
+
type="checkbox"
|
|
1520
|
+
.checked=${o}
|
|
1521
|
+
?disabled=${this.loading||this.saving||s||!i}
|
|
1522
|
+
@change=${r=>{this.toggleSubsessions(r)}}
|
|
1523
|
+
>
|
|
1524
|
+
<span>Enable the <code>spawn_subsession</code> tools</span>
|
|
1525
|
+
</label>
|
|
1526
|
+
<small>Beta: agents can start child sessions they stay attached to (<code>spawn_subsession</code>, <code>list_subsessions</code>, <code>check_subsession</code>, <code>read_subsession</code>) and are notified when a child finishes. Requires "Allow agents to start sessions". Off by default.</small>
|
|
1527
|
+
</div>
|
|
1528
|
+
<section class="effective-card" aria-label="Effective configuration summary">
|
|
1529
|
+
<h3>Effective after environment overrides</h3>
|
|
1530
|
+
<dl>
|
|
1531
|
+
<div><dt>Spawn sessions</dt><dd>${i?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
|
|
1532
|
+
<div><dt>Subsessions</dt><dd>${o?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
|
|
1533
|
+
</dl>
|
|
1534
|
+
</section>
|
|
1535
|
+
`}
|
|
1536
|
+
`}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=O`
|
|
1537
|
+
:host { display: block; }
|
|
1538
|
+
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1539
|
+
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
1540
|
+
h2, h3, p { margin: 0; }
|
|
1541
|
+
h2 { font-size: 17px; line-height: 1.25; }
|
|
1542
|
+
h3 { font-size: 13px; line-height: 1.3; }
|
|
1543
|
+
p { color: var(--pi-muted); line-height: 1.45; }
|
|
1544
|
+
button, input { font: inherit; }
|
|
1545
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1546
|
+
button:disabled { opacity: .55; cursor: not-allowed; }
|
|
1547
|
+
.secondary { flex: 0 0 auto; }
|
|
1548
|
+
.message, .loading-card, .config-path-card, .effective-card, .restart-note { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
|
|
1549
|
+
.message { margin-bottom: 12px; }
|
|
1550
|
+
.error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
|
|
1551
|
+
.success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
|
|
1552
|
+
.loading-card { color: var(--pi-muted); }
|
|
1553
|
+
.restart-note { margin-bottom: 14px; border-color: var(--pi-warning-border); color: var(--pi-warning); background: var(--pi-warning-surface); line-height: 1.45; }
|
|
1554
|
+
.config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
|
|
1555
|
+
.config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
|
|
1556
|
+
code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
|
|
1557
|
+
.field { display: grid; gap: 7px; margin-bottom: 14px; }
|
|
1558
|
+
.field small { color: var(--pi-muted); line-height: 1.45; }
|
|
1559
|
+
.field-heading { display: flex; align-items: center; gap: 8px; }
|
|
1560
|
+
.toggle { display: flex; align-items: center; gap: 9px; cursor: pointer; }
|
|
1561
|
+
.toggle input { width: 16px; height: 16px; }
|
|
1562
|
+
.toggle input:disabled { cursor: not-allowed; }
|
|
1563
|
+
.override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
|
|
1564
|
+
.beta-badge { border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); background: var(--pi-bg); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
|
|
1565
|
+
.effective-card { display: grid; gap: 10px; }
|
|
1566
|
+
.effective-card dl { display: grid; gap: 8px; margin: 0; }
|
|
1567
|
+
.effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
|
|
1568
|
+
dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
|
|
1569
|
+
.muted { color: var(--pi-muted); }
|
|
1570
|
+
|
|
1571
|
+
@media (max-width: 760px) {
|
|
1572
|
+
.section-heading { display: grid; gap: 12px; }
|
|
1573
|
+
.section-heading .secondary { justify-self: start; }
|
|
1574
|
+
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1575
|
+
}
|
|
1576
|
+
`;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([D("settings-sessiond-panel")],Ee);var lb=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?cb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&lb(t,i,o),o};let Ie=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
|
|
1397
1577
|
<div class="section-heading">
|
|
1398
1578
|
<div>
|
|
1399
1579
|
<h2>Plugins</h2>
|
|
@@ -1420,7 +1600,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1420
1600
|
<span>${e.enabled?"Enabled":"Disabled"}</span>
|
|
1421
1601
|
</label>
|
|
1422
1602
|
</article>
|
|
1423
|
-
`}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};
|
|
1603
|
+
`}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ie.styles=O`
|
|
1424
1604
|
:host { display: block; }
|
|
1425
1605
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1426
1606
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1453,7 +1633,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1453
1633
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1454
1634
|
.toggle { justify-self: start; }
|
|
1455
1635
|
}
|
|
1456
|
-
`;
|
|
1636
|
+
`;ze([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);ze([d({attribute:!1})],Ie.prototype,"configResponse",2);ze([d({type:Boolean})],Ie.prototype,"loading",2);ze([d({type:Boolean})],Ie.prototype,"saving",2);ze([d()],Ie.prototype,"error",2);ze([d()],Ie.prototype,"savedMessage",2);ze([d({attribute:!1})],Ie.prototype,"onReload",2);ze([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=ze([D("settings-plugins-panel")],Ie);var db=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&db(t,i,o),o};const Gr={capture:!0};let oe=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=zn(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Lt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=gb(this.actions),t=this.shortcutResolutions();return l`
|
|
1457
1637
|
<div class="section-heading">
|
|
1458
1638
|
<div>
|
|
1459
1639
|
<h2>Keyboard shortcuts</h2>
|
|
@@ -1477,19 +1657,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1477
1657
|
</section>
|
|
1478
1658
|
`)}
|
|
1479
1659
|
`}
|
|
1480
|
-
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=
|
|
1481
|
-
<article class=${
|
|
1660
|
+
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Mi(e.id,i),o=wb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:Xi(r),a=n?.ok===!0?n.shortcut:bb(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=fb(t);return l`
|
|
1661
|
+
<article class=${hb(t)}>
|
|
1482
1662
|
<div class="shortcut-main">
|
|
1483
1663
|
<strong>${e.title}</strong>
|
|
1484
1664
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1485
1665
|
<small class="shortcut-id">${e.id}</small>
|
|
1486
|
-
<small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${
|
|
1666
|
+
<small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ni(e.shortcut)}</kbd>`:"No default shortcut"}</small>
|
|
1487
1667
|
</div>
|
|
1488
1668
|
<div class="shortcut-editor">
|
|
1489
1669
|
<div class="shortcut-status">
|
|
1490
|
-
${a!==void 0&&a!==""?l`<kbd>${
|
|
1491
|
-
<small class=${u}>${
|
|
1492
|
-
${f===void 0?null:l`<small class=${
|
|
1670
|
+
${a!==void 0&&a!==""?l`<kbd>${ni(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"Disabled":"Unassigned"}</span>`}
|
|
1671
|
+
<small class=${u}>${yb(u)}${p?" · Unsaved":""}</small>
|
|
1672
|
+
${f===void 0?null:l`<small class=${ub(t)}>${f}</small>`}
|
|
1493
1673
|
</div>
|
|
1494
1674
|
<label class="shortcut-input-label">
|
|
1495
1675
|
<span>Shortcut</span>
|
|
@@ -1502,7 +1682,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1502
1682
|
autocapitalize="off"
|
|
1503
1683
|
spellcheck="false"
|
|
1504
1684
|
?disabled=${this.saving}
|
|
1505
|
-
@input=${v=>{this.updateDraft(e.id,
|
|
1685
|
+
@input=${v=>{this.updateDraft(e.id,Sb(v))}}
|
|
1506
1686
|
>
|
|
1507
1687
|
</label>
|
|
1508
1688
|
${h!==""?l`<small class="recording-hint">${h}</small>`:null}
|
|
@@ -1514,7 +1694,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1514
1694
|
</div>
|
|
1515
1695
|
</div>
|
|
1516
1696
|
</article>
|
|
1517
|
-
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=
|
|
1697
|
+
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Mi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ni(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Xi(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?vb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(eo(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=Xi(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},jn)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Gr),this.recordingListenerActive=!1)}};oe.styles=O`
|
|
1518
1698
|
:host { display: block; }
|
|
1519
1699
|
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1520
1700
|
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -1569,7 +1749,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1569
1749
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1570
1750
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
1571
1751
|
}
|
|
1572
|
-
`;
|
|
1752
|
+
`;we([d({attribute:!1})],oe.prototype,"actions",2);we([d({attribute:!1})],oe.prototype,"configResponse",2);we([d({type:Boolean})],oe.prototype,"loading",2);we([d({type:Boolean})],oe.prototype,"saving",2);we([d()],oe.prototype,"error",2);we([d()],oe.prototype,"savedMessage",2);we([d({attribute:!1})],oe.prototype,"onReload",2);we([d({attribute:!1})],oe.prototype,"onSave",2);we([w()],oe.prototype,"drafts",2);we([w()],oe.prototype,"localError",2);we([w()],oe.prototype,"recording",2);oe=we([D("settings-shortcuts-panel")],oe);function hb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function ub(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function fb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function gb(e){const t=new Map;for(const i of[...e].sort(mb)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function mb(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function Mi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function vb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function bb(e,t){const i=Mi(e.id,t);if(i!==null)return i??e.shortcut}function wb(e,t){const i=Mi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function yb(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function Sb(e){return e.target instanceof HTMLInputElement?e.target.value:""}var xb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xb(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
|
|
1573
1753
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
1574
1754
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1575
1755
|
<header class="settings-header">
|
|
@@ -1582,6 +1762,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1582
1762
|
<div class="settings-body">
|
|
1583
1763
|
<nav class="settings-nav" aria-label="Settings sections">
|
|
1584
1764
|
${this.renderNavButton("general","General","Server config")}
|
|
1765
|
+
${this.renderNavButton("sessiond","Session daemon","Runtime settings")}
|
|
1585
1766
|
${this.renderNavButton("plugins","Plugins","Enable and disable")}
|
|
1586
1767
|
${this.renderNavButton("shortcuts","Keyboard","Shortcuts")}
|
|
1587
1768
|
</nav>
|
|
@@ -1591,7 +1772,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1591
1772
|
</div>
|
|
1592
1773
|
</section>
|
|
1593
1774
|
</div>
|
|
1594
|
-
`}renderActiveSection(){return this.section==="
|
|
1775
|
+
`}renderActiveSection(){return this.section==="sessiond"?l`
|
|
1776
|
+
<settings-sessiond-panel
|
|
1777
|
+
.configResponse=${this.configResponse}
|
|
1778
|
+
.loading=${this.loading}
|
|
1779
|
+
.saving=${this.saving}
|
|
1780
|
+
.error=${this.error}
|
|
1781
|
+
.savedMessage=${this.savedMessage}
|
|
1782
|
+
.onReload=${()=>this.loadConfig()}
|
|
1783
|
+
.onSave=${e=>this.saveConfig(e)}
|
|
1784
|
+
></settings-sessiond-panel>
|
|
1785
|
+
`:this.section==="shortcuts"?l`
|
|
1595
1786
|
<settings-shortcuts-panel
|
|
1596
1787
|
.actions=${this.actions}
|
|
1597
1788
|
.configResponse=${this.configResponse}
|
|
@@ -1628,7 +1819,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1628
1819
|
<strong>${t}</strong>
|
|
1629
1820
|
<small>${i}</small>
|
|
1630
1821
|
</button>
|
|
1631
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([
|
|
1822
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ui.config(),ws.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`Failed to load settings: ${ds(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ui.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${ds(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await ws.plugins()}catch(e){this.error=`Failed to refresh plugins: ${ds(e)}`}}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};re.styles=O`
|
|
1632
1823
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1633
1824
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
1634
1825
|
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -1655,7 +1846,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1655
1846
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
1656
1847
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
1657
1848
|
}
|
|
1658
|
-
`;
|
|
1849
|
+
`;ye([d({attribute:!1})],re.prototype,"section",2);ye([d({attribute:!1})],re.prototype,"actions",2);ye([d({attribute:!1})],re.prototype,"onNavigate",2);ye([d({attribute:!1})],re.prototype,"onClose",2);ye([d({attribute:!1})],re.prototype,"onConfigSaved",2);ye([w()],re.prototype,"configResponse",2);ye([w()],re.prototype,"pluginsResponse",2);ye([w()],re.prototype,"loading",2);ye([w()],re.prototype,"saving",2);ye([w()],re.prototype,"error",2);ye([w()],re.prototype,"savedMessage",2);re=ye([D("settings-dialog")],re);function ds(e){return e instanceof Error?e.message:String(e)}var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$b(t,i,o),o};let ce=class extends C{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
|
|
1659
1850
|
${this.hideToolTabs?null:l`
|
|
1660
1851
|
<header>
|
|
1661
1852
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -1685,32 +1876,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1685
1876
|
<h2>${e.title}</h2>
|
|
1686
1877
|
${e.body===void 0?null:l`<p>${e.body}</p>`}
|
|
1687
1878
|
</section>
|
|
1688
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};
|
|
1879
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ce.styles=Ff;Ce([d({attribute:!1})],ce.prototype,"workspace",2);Ce([d({attribute:!1})],ce.prototype,"panelContext",2);Ce([d({attribute:!1})],ce.prototype,"emptyState",2);Ce([d()],ce.prototype,"tool",2);Ce([d({attribute:!1})],ce.prototype,"panels",2);Ce([d({type:Boolean})],ce.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],ce.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],ce.prototype,"workspaceHeaderStrip",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollLeft",2);Ce([w()],ce.prototype,"workspaceHeaderCanScrollRight",2);ce=Ce([D("workspace-panel")],ce);var Rb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rb(t,i,o),o};let ne=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Cb(this.machines),t=Mb(this.machine),i=Tb(this.project),s=Db(this.workspace),o=_b(this.session);return l`
|
|
1689
1880
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
1690
1881
|
<span class="context-bar-label">Location</span>
|
|
1691
1882
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
1692
1883
|
${e?l`
|
|
1693
1884
|
<li class="context-item">
|
|
1694
|
-
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${
|
|
1885
|
+
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Ab(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
|
|
1695
1886
|
<span class="context-kind">Machine</span>
|
|
1696
1887
|
<span class="context-value">${t}</span>
|
|
1697
1888
|
</button>
|
|
1698
1889
|
</li>
|
|
1699
1890
|
`:null}
|
|
1700
1891
|
<li class="context-item">
|
|
1701
|
-
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${
|
|
1892
|
+
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Eb(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
|
|
1702
1893
|
<span class="context-kind">Project</span>
|
|
1703
1894
|
<span class="context-value">${i}</span>
|
|
1704
1895
|
</button>
|
|
1705
1896
|
</li>
|
|
1706
1897
|
<li class="context-item">
|
|
1707
|
-
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${
|
|
1898
|
+
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Wb(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
|
|
1708
1899
|
<span class="context-kind">Workspace</span>
|
|
1709
1900
|
<span class="context-value">${s}</span>
|
|
1710
1901
|
</button>
|
|
1711
1902
|
</li>
|
|
1712
1903
|
<li class="context-item">
|
|
1713
|
-
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${
|
|
1904
|
+
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Ob(this.session)} aria-label=${`Session: ${o}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
|
|
1714
1905
|
<span class="context-kind">Session</span>
|
|
1715
1906
|
<span class="context-value">${o}</span>
|
|
1716
1907
|
</button>
|
|
@@ -1724,7 +1915,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1724
1915
|
<path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
|
|
1725
1916
|
</svg>
|
|
1726
1917
|
</button>
|
|
1727
|
-
`}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};
|
|
1918
|
+
`}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ne.styles=O`
|
|
1728
1919
|
/* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
|
|
1729
1920
|
:host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
|
|
1730
1921
|
.context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
@@ -1750,7 +1941,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1750
1941
|
.context-kind { display: none; }
|
|
1751
1942
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
1752
1943
|
button { cursor: pointer; }
|
|
1753
|
-
`;
|
|
1944
|
+
`;Se([d({attribute:!1})],ne.prototype,"machines",2);Se([d({attribute:!1})],ne.prototype,"machine",2);Se([d({attribute:!1})],ne.prototype,"project",2);Se([d({attribute:!1})],ne.prototype,"workspace",2);Se([d({attribute:!1})],ne.prototype,"session",2);Se([d({attribute:!1})],ne.prototype,"refreshControl",2);Se([d({attribute:!1})],ne.prototype,"onOpenSection",2);Se([d({attribute:!1})],ne.prototype,"onShowActions",2);Se([B(".context-items")],ne.prototype,"contextItems",2);Se([w()],ne.prototype,"canScrollLeft",2);Se([w()],ne.prototype,"canScrollRight",2);ne=Se([D("app-context-bar")],ne);function Cb(e){return e.length>1}function Mb(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function Ab(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function Tb(e){return e?.name??"No project"}function Eb(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function Db(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function Wb(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function _b(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"No session"}function Ob(e){return e===void 0?"No session selected":e.path}var Lb=Object.defineProperty,jb=Object.getOwnPropertyDescriptor,ot=(e,t,i,s)=>{for(var o=s>1?void 0:s?jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Lb(t,i,o),o};let je=class extends C{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
|
|
1754
1945
|
<div class=${this.frameClass()}>
|
|
1755
1946
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
1756
1947
|
${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
|
|
@@ -1762,7 +1953,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1762
1953
|
`})}
|
|
1763
1954
|
</div>
|
|
1764
1955
|
</div>
|
|
1765
|
-
`}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:
|
|
1956
|
+
`}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:ru(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=O`
|
|
1766
1957
|
:host { flex: 0 0 auto; min-width: 0; }
|
|
1767
1958
|
.mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
|
|
1768
1959
|
.mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
|
|
@@ -1788,12 +1979,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1788
1979
|
.tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
1789
1980
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
1790
1981
|
}
|
|
1791
|
-
`;
|
|
1982
|
+
`;ot([d({attribute:!1})],je.prototype,"tabs",2);ot([d({attribute:!1})],je.prototype,"selectedView",2);ot([d({attribute:!1})],je.prototype,"onSelect",2);ot([B(".mobile-tabs")],je.prototype,"mobileTabs",2);ot([w()],je.prototype,"canScrollLeft",2);ot([w()],je.prototype,"canScrollRight",2);je=ot([D("app-mobile-main-tabs")],je);var Nb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?zb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Nb(t,i,o),o};let te=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=ps(e,this.statuses),i=e.name;return l`
|
|
1792
1983
|
<div class="machine-switcher">
|
|
1793
1984
|
<button
|
|
1794
1985
|
type="button"
|
|
1795
1986
|
class="machine-switcher-button"
|
|
1796
|
-
title=${
|
|
1987
|
+
title=${Zr(e)}
|
|
1797
1988
|
aria-label=${`Machine: ${i}. Switch machine.`}
|
|
1798
1989
|
aria-expanded=${String(this.open)}
|
|
1799
1990
|
@click=${s=>{this.toggleMenu(s.currentTarget)}}
|
|
@@ -1804,7 +1995,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1804
1995
|
<span class="machine-switcher-kicker">Machine</span>
|
|
1805
1996
|
<span class="machine-switcher-label">${i}</span>
|
|
1806
1997
|
</span>
|
|
1807
|
-
<span class=${`machine-status ${t}`}>${
|
|
1998
|
+
<span class=${`machine-status ${t}`}>${Qr(t)}</span>
|
|
1808
1999
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
1809
2000
|
</button>
|
|
1810
2001
|
${this.open?l`
|
|
@@ -1813,18 +2004,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1813
2004
|
</div>
|
|
1814
2005
|
`:null}
|
|
1815
2006
|
</div>
|
|
1816
|
-
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=
|
|
2007
|
+
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=ps(e,this.statuses),s=da(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
|
|
1817
2008
|
<div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
|
|
1818
2009
|
<button
|
|
1819
2010
|
type="button"
|
|
1820
2011
|
class="machine-option-main"
|
|
1821
|
-
title=${
|
|
2012
|
+
title=${Zr(e)}
|
|
1822
2013
|
data-machine-id=${e.id}
|
|
1823
2014
|
@click=${()=>{this.select(e)}}
|
|
1824
2015
|
@keydown=${r=>{this.handleMachineOptionKeydown(r)}}
|
|
1825
2016
|
>
|
|
1826
2017
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
1827
|
-
<small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${
|
|
2018
|
+
<small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Qr(i)}</small>
|
|
1828
2019
|
</button>
|
|
1829
2020
|
${s?l`
|
|
1830
2021
|
<div class="machine-option-actions">
|
|
@@ -1844,7 +2035,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1844
2035
|
</div>
|
|
1845
2036
|
`:null}
|
|
1846
2037
|
</div>
|
|
1847
|
-
`}renderActivity(e){const t=
|
|
2038
|
+
`}renderActivity(e){const t=ps(e,this.statuses);if(t==="offline"||t==="error")return;const i=ta(this.activities[e.id]);return oa(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Jr(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Jr(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Ht(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};te.styles=O`
|
|
1848
2039
|
:host { min-width: 0; display: block; }
|
|
1849
2040
|
.machine-switcher { min-width: 0; }
|
|
1850
2041
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
@@ -1859,6 +2050,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1859
2050
|
.activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
|
|
1860
2051
|
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
1861
2052
|
.activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
|
|
2053
|
+
.activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
|
|
1862
2054
|
.machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
|
|
1863
2055
|
.machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
|
|
1864
2056
|
.machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
|
|
@@ -1876,10 +2068,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1876
2068
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
1877
2069
|
.machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
1878
2070
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
1879
|
-
`;
|
|
2071
|
+
`;pe([d({attribute:!1})],te.prototype,"machines",2);pe([d({attribute:!1})],te.prototype,"selected",2);pe([d({attribute:!1})],te.prototype,"statuses",2);pe([d({attribute:!1})],te.prototype,"activities",2);pe([d({attribute:!1})],te.prototype,"onSelect",2);pe([d({attribute:!1})],te.prototype,"onRemove",2);pe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);pe([w()],te.prototype,"open",2);pe([w()],te.prototype,"menuStyle",2);pe([w()],te.prototype,"openActionsMachineId",2);pe([w()],te.prototype,"actionMenuStyle",2);te=pe([D("machine-switcher")],te);function ps(e,t){return t[e.id]?.status??e.status??"unknown"}function Qr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Zr(e){return e.baseUrl??e.name}function Jr(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ei(t.bottom)};`,`left: ${ei(o)};`,`width: ${ei(s)};`,`max-height: ${ei(r)};`].join(" ")}function ei(e){return`${String(Math.round(e))}px`}var Fb=Object.defineProperty,Bb=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fb(t,i,o),o};let x=class extends C{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
|
|
1880
2072
|
<header>
|
|
1881
2073
|
<strong>PI WEB</strong>
|
|
1882
|
-
${
|
|
2074
|
+
${Ai(this.machines)?l`
|
|
1883
2075
|
<machine-switcher
|
|
1884
2076
|
.machines=${this.machines}
|
|
1885
2077
|
.selected=${this.selectedMachine}
|
|
@@ -1896,7 +2088,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1896
2088
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
1897
2089
|
</div>
|
|
1898
2090
|
</header>
|
|
1899
|
-
${this.compact&&
|
|
2091
|
+
${this.compact&&Ai(this.machines)?l`
|
|
1900
2092
|
<machine-list
|
|
1901
2093
|
.machines=${this.machines}
|
|
1902
2094
|
.selected=${this.selectedMachine}
|
|
@@ -1944,9 +2136,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1944
2136
|
.sessions=${this.sessions}
|
|
1945
2137
|
.statuses=${this.sessionStatuses}
|
|
1946
2138
|
.activities=${this.sessionActivities}
|
|
2139
|
+
.sending=${this.sendingPrompts}
|
|
1947
2140
|
.selected=${this.selectedSession}
|
|
1948
2141
|
.canStart=${this.canStartSession}
|
|
1949
2142
|
.canDeleteArchived=${this.canDeleteArchivedSessions}
|
|
2143
|
+
.canReload=${this.canReloadSessions}
|
|
1950
2144
|
.archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
|
|
1951
2145
|
.collapsible=${this.collapsible}
|
|
1952
2146
|
.collapsed=${this.sessionsCollapsed}
|
|
@@ -1962,11 +2156,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1962
2156
|
.onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
|
|
1963
2157
|
.onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
|
|
1964
2158
|
.onDetachParent=${e=>this.onDetachParentSession?.(e)}
|
|
2159
|
+
.onReload=${e=>this.onReloadSession?.(e)}
|
|
1965
2160
|
.onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
|
|
1966
2161
|
.onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
|
|
1967
2162
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1968
2163
|
></session-list>
|
|
1969
|
-
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=
|
|
2164
|
+
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Ub(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Hb(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=O`
|
|
1970
2165
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
1971
2166
|
:host([compact]) { flex: 1 1 auto; }
|
|
1972
2167
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -1989,7 +2184,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1989
2184
|
:host([compact]) workspace-list[collapsed],
|
|
1990
2185
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
1991
2186
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1992
|
-
`;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([
|
|
2187
|
+
`;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([D("app-navigation-panel")],x);function Ai(e){return e.length>1}function Ub(e,t){const i=Ea(t);return i[i.indexOf(e)-1]}function Hb(e,t){const i=Ea(t);return i[i.indexOf(e)+1]??"chat"}function Ea(e){return ki.filter(t=>t!=="machines"||Ai(e))}var qb=Object.defineProperty,Kb=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?Kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&qb(t,i,o),o};const Vb=new Set(["ArrowLeft","ArrowRight","Home","End"]),Gb=420,Qb=4;let K=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
|
|
1993
2188
|
${this.renderResizeHandle()}
|
|
1994
2189
|
<button
|
|
1995
2190
|
type="button"
|
|
@@ -2000,7 +2195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2000
2195
|
aria-expanded=${String(!this.collapsed)}
|
|
2001
2196
|
@click=${()=>{this.onToggle?.()}}
|
|
2002
2197
|
>${this.renderIcon()}</button>
|
|
2003
|
-
`}renderResizeHandle(){if(!this.resizable)return
|
|
2198
|
+
`}renderResizeHandle(){if(!this.resizable)return F;const e=this.resizeConstraints();return l`
|
|
2004
2199
|
<div
|
|
2005
2200
|
class="resize-handle"
|
|
2006
2201
|
role="separator"
|
|
@@ -2019,7 +2214,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2019
2214
|
@dblclick=${t=>{this.onResizeDoubleClick(t)}}
|
|
2020
2215
|
@keydown=${t=>{this.onResizeKeyDown(t)}}
|
|
2021
2216
|
></div>
|
|
2022
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?
|
|
2217
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Qb)&&(t.moved=!0,this.commitPanelWidth(hf(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Vb.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=uf(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Gb){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Ut(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=O`
|
|
2023
2218
|
:host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
|
|
2024
2219
|
:host([side="navigation"]) { grid-column: 2; }
|
|
2025
2220
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -2038,7 +2233,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2038
2233
|
@media (max-width: 760px) {
|
|
2039
2234
|
:host([side="navigation"]) { display: none; }
|
|
2040
2235
|
}
|
|
2041
|
-
`;
|
|
2236
|
+
`;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([D("app-panel-edge-control")],K);var Zb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,Da=(e,t,i,s)=>{for(var o=s>1?void 0:s?Jb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zb(t,i,o),o};let Ti=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
|
|
2042
2237
|
<button
|
|
2043
2238
|
class="app-refresh-button"
|
|
2044
2239
|
title=${e}
|
|
@@ -2052,12 +2247,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2052
2247
|
<path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
|
|
2053
2248
|
<path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
|
|
2054
2249
|
</svg>
|
|
2055
|
-
`}}
|
|
2250
|
+
`}};Ti.styles=O`
|
|
2056
2251
|
:host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
|
|
2057
2252
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
2058
2253
|
.app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
|
|
2059
2254
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
2060
|
-
`;ya([d({attribute:!1})],$i.prototype,"onReload",2);$i=ya([E("app-refresh-control")],$i);var sb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?ob(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sb(t,i,o),o};const rb=900*1e3,nb=750,Ms=[1e3,3e3,8e3,15e3,3e4],Ur={capture:!0},ns="auto:on",Hr="auto:off",Qt="theme:",as=Dt("core:workspace.files"),ls=Dt("core:workspace.git"),Zt=Dt("core:workspace.terminal"),ab=320,lb=2,cb="(min-width: 1181px)";let ce=class extends C{constructor(){super(...arguments),this.state=_c(),this.sessions=new xp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new mp),this.activity=new Oc(()=>this.state,e=>{this.setState(e)}),this.auth=new Nc(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Op(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Wp),this.projects=new Gc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Vc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Uc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Kc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Qp,this.realtime=new Qo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new zp,this.terminalSelection=new Vp,this.appShell=new $u(this),this.panelCollapse=new _u(this),this.panelResize=new Lu(this),this.navigationSections=new Eu(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=db(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=dh()??ah,this.activeThemeId=Zs,this.isRefreshingApp=!1,this.settingsSection=hr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},rb),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Ur),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!ub(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),pb(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=pr();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=nb){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await un.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Sa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ai.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(pr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?Vr():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Vr():{selectedFilePath:Ui(as,"file"),selectedDiffPath:Ui(ls,"diff"),selectedTerminalId:Ui(Zt,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){Qi(e,{replace:!0}),Se(as,"file",void 0,{replace:!0}),Se(ls,"diff",void 0,{replace:!0}),Se(Zt,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=gb(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Ms.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await cs(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Qi({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Xo(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Xo(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Qi(Yo(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Se(as,"file",e.selectedFilePath,{replace:!0}),Se(ls,"diff",e.selectedDiffPath,{replace:!0}),Se(Zt,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Fp(e.id);if(await this.restoreRouteFor(Yo(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=Gr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=ef(e,{api:{runTerminalCommand:(r,n)=>nt.runTerminalCommand(r,n,t),listCommandRuns:r=>nt.listCommandRuns(r,t),getCommandRun:r=>nt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Se(Zt,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,Zi(e)}closeSettings(){this.settingsSection=void 0,Zi(void 0)}navigateSettings(e){this.settingsSection=e,Zi(e)}restoreSettingsRoute(){this.settingsSection=hr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Qo;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>hb(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):fb(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await nt.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=Kr(e),s=Kr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
|
|
2255
|
+
`;Da([d({attribute:!1})],Ti.prototype,"onReload",2);Ti=Da([D("app-refresh-control")],Ti);var Xb=Object.defineProperty,Yb=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Yb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Xb(t,i,o),o};const ew=900*1e3,tw=750,Os=[1e3,3e3,8e3,15e3,3e4],Xr={capture:!0},hs="auto:on",Yr="auto:off",ti="theme:",us=Nt("core:workspace.files"),fs=Nt("core:workspace.git"),ii=Nt("core:workspace.terminal"),iw=320,sw=2,ow="(min-width: 1181px)";let de=class extends C{constructor(){super(...arguments),this.state=td(),this.sessions=new Vp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Fp),this.activity=new id(()=>this.state,e=>{this.setState(e)}),this.auth=new rd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new ah(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new rh),this.projects=new fd(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new ud(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new cd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new hd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new yh,this.realtime=new ir,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new ph,this.terminalSelection=new bh,this.appShell=new Zu(this),this.panelCollapse=new lf(this),this.panelResize=new df(this),this.navigationSections=new rf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=rw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=_h()??Eh,this.activeThemeId=io,this.isRefreshingApp=!1,this.settingsSection=wr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},ew),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Xr),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!lw(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),nw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=br();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=tw){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=g(this.state);try{const t=await yn.piWebStatus(e);g(this.state)===e&&this.setState({piWebStatus:t})}catch(t){g(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>Wa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ui.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(br(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=g(this.state),r=e.projectId===void 0||e.projectId===""?sn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?sn():{selectedFilePath:Qi(us,"file"),selectedDiffPath:Qi(fs,"diff"),selectedTerminalId:Qi(ii,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){ts(e,{replace:!0}),xe(us,"file",void 0,{replace:!0}),xe(fs,"diff",void 0,{replace:!0}),xe(ii,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=dw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Os.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gs(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),ts({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(rr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(rr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ts(nr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){xe(us,"file",e.selectedFilePath,{replace:!0}),xe(fs,"diff",e.selectedDiffPath,{replace:!0}),xe(ii,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??hh(e.id);if(await this.restoreRouteFor(nr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=on(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=If(e,{api:{runTerminalCommand:(r,n)=>pt.runTerminalCommand(r,n,t),listCommandRuns:r=>pt.listCommandRuns(r,t),getCommandRun:r=>pt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){xe(ii,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,is(e)}closeSettings(){this.settingsSection=void 0,is(void 0)}navigateSettings(e){this.settingsSection=e,is(e)}restoreSettingsRoute(){this.settingsSection=wr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new ir;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>aw(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):cw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await pt.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=tn(e),s=tn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
|
|
2061
2256
|
<workspace-panel
|
|
2062
2257
|
id="workspace-panel"
|
|
2063
2258
|
.workspace=${e}
|
|
@@ -2103,7 +2298,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2103
2298
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
2104
2299
|
.onReset=${()=>{this.resetResizablePanel("workspace")}}
|
|
2105
2300
|
></app-panel-edge-control>
|
|
2106
|
-
`}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-
|
|
2301
|
+
`}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-sw-iw);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(ow).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&ht(e,Ze.sessionsReload)}supportsWorkspaceFileSuggestions(e=g(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&ht(t,Ze.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}renderNavigationPanel(){return l`
|
|
2107
2302
|
<app-navigation-panel
|
|
2108
2303
|
.machines=${this.state.machines}
|
|
2109
2304
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -2119,13 +2314,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2119
2314
|
.workspacesByProjectId=${this.state.workspacesByProjectId}
|
|
2120
2315
|
.workspaces=${this.state.workspaces}
|
|
2121
2316
|
.selectedWorkspace=${this.state.selectedWorkspace}
|
|
2122
|
-
.deletingWorkspaceIds=${
|
|
2317
|
+
.deletingWorkspaceIds=${Qh(this.state.workspaceDeletionRuns)}
|
|
2123
2318
|
.sessions=${this.state.sessions}
|
|
2124
2319
|
.sessionStatuses=${this.state.sessionStatuses}
|
|
2125
2320
|
.sessionActivities=${this.state.sessionActivities}
|
|
2321
|
+
.sendingPrompts=${this.state.sendingPrompts}
|
|
2126
2322
|
.selectedSession=${this.state.selectedSession}
|
|
2127
2323
|
.canStartSession=${!!this.state.selectedWorkspace}
|
|
2128
2324
|
.canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
|
|
2325
|
+
.canReloadSessions=${this.canReloadSessions()}
|
|
2129
2326
|
.archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
|
|
2130
2327
|
.collapsible=${!0}
|
|
2131
2328
|
.compact=${this.appShell.isMobileNavigationLayout}
|
|
@@ -2153,17 +2350,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2153
2350
|
.onDeleteArchivedSession=${e=>this.sessions.deleteArchivedSessions([e])}
|
|
2154
2351
|
.onDeleteArchivedSessions=${e=>this.sessions.deleteArchivedSessions(e)}
|
|
2155
2352
|
.onDetachParentSession=${e=>this.sessions.detachParent(e)}
|
|
2353
|
+
.onReloadSession=${e=>this.sessions.reloadSession(e)}
|
|
2156
2354
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
2157
2355
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
2158
2356
|
></app-navigation-panel>
|
|
2159
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!
|
|
2357
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,o=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},o),o()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ai(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await gs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=en(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>ys.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=en(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return ju({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},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,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Pf(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>fr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>fr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>Lu({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!lh(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Kn(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
|
|
2160
2358
|
|
|
2161
2359
|
This will run git worktree remove and delete:
|
|
2162
2360
|
${e.path}
|
|
2163
2361
|
|
|
2164
|
-
The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await
|
|
2362
|
+
The Git branch will not be deleted.`))return;const s=g(this.state);try{const o=await ys.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${pw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=Is(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(Vh(t.id));if(g(this.state)!==e)return;const s=Gh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))Si(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(Si);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=on(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Is(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:hw(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
|
|
2165
2363
|
|
|
2166
|
-
This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?
|
|
2364
|
+
This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ current":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?Yr:hs;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${ti}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${ti}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hs||e===Yr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===hs},this.applyPreferredTheme(!0);return}if(!e.startsWith(ti))return;const t=e.slice(ti.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Lh(t),e&&Oh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return jh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return qn(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("auto pair"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:t,options:e.map(i=>{const s=uw(i);return{value:i,label:`${i}${i===t?" ✓ current":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
|
|
2167
2365
|
<app-context-bar
|
|
2168
2366
|
.machines=${this.state.machines}
|
|
2169
2367
|
.machine=${this.state.selectedMachine}
|
|
@@ -2184,14 +2382,14 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
|
|
|
2184
2382
|
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
|
|
2185
2383
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
2186
2384
|
${this.renderNavigationPanelEdgeControl()}
|
|
2187
|
-
<main class=${
|
|
2385
|
+
<main class=${Xn(e.mainView)}>
|
|
2188
2386
|
${this.renderContextBar()}
|
|
2189
2387
|
${this.renderMobileMainTabs()}
|
|
2190
2388
|
${e.error?l`<div class="error">${e.error}</div>`:null}
|
|
2191
2389
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
2192
2390
|
${e.selectedSession?l`
|
|
2193
|
-
<chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
2194
|
-
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .onSend=${(t,i)=>{this.sendPrompt(t,i)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
|
|
2391
|
+
<chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
2392
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${(t,i,s,o)=>{this.sendPrompt(t,i,s,o)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
|
|
2195
2393
|
<status-bar .status=${e.status}></status-bar>
|
|
2196
2394
|
${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
|
|
2197
2395
|
${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
|
|
@@ -2207,4 +2405,4 @@ This only removes it from this PI WEB gateway.`))return;const t=this.state.selec
|
|
|
2207
2405
|
${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
|
|
2208
2406
|
${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
|
|
2209
2407
|
</div>
|
|
2210
|
-
`}};
|
|
2408
|
+
`}};de.styles=zf;Me([w()],de.prototype,"state",2);Me([B("chat-view")],de.prototype,"chatView",2);Me([B("prompt-editor")],de.prototype,"promptEditor",2);Me([B("app-navigation-panel")],de.prototype,"navigationPanel",2);Me([B("#navigation-panel")],de.prototype,"navigationPanelFrame",2);Me([B("#workspace-panel")],de.prototype,"workspacePanelFrame",2);Me([w()],de.prototype,"activeThemeId",2);Me([w()],de.prototype,"isRefreshingApp",2);Me([w()],de.prototype,"settingsSection",2);Me([w()],de.prototype,"shortcutConfig",2);de=Me([D("pi-web-app")],de);function rw(){const e=new _u;return e.register({id:"core",plugin:bu}),e.register({id:"themes",plugin:xu}),e}function en(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function nw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function aw(e,t){return Wa(e,t)}function Wa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function lw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function tn(e){return Ye(e.status,e.activity)}function cw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function sn(){return{}}function on(e,t){return JSON.stringify([e,t])}function dw(e){const t=Math.min(e,Os.length-1);return Os[t]??3e4}function pw(e){return e instanceof Error?e.message:String(e)}function hw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function uw(e){switch(e){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)";default:return}}export{O as a,l as b,pt as c,Rw as d,B as e,$w as f,C as i,d as n,w as r,Pw as s,D as t};
|