@chainingintention/pi-web-cn 1.202607.4 → 1.202607.5-dev.0
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/dist/client/assets/{CodeViewer-DssF-c9D.js → CodeViewer-_Lzl-tA7.js} +1 -1
- package/dist/client/assets/{TerminalPanel-8Or6pbwb.js → TerminalPanel-BVBJC-6w.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-D_OLq3Q4.js → UnifiedDiffViewer-BwONrl2w.js} +1 -1
- package/dist/client/assets/{index-B06LjBQ0.js → index-Ce8_7l5M.js} +201 -202
- package/dist/client/index.html +2 -2
- package/dist/client/manifest.webmanifest +1 -1
- package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +6 -1
- package/dist/plugin-api.d.ts +2 -0
- package/dist/server/app.js +16 -15
- package/dist/server/app.js.map +1 -1
- package/dist/server/gitRoutes.js +3 -16
- package/dist/server/gitRoutes.js.map +1 -1
- package/dist/server/httpSessions.js +34 -0
- package/dist/server/httpSessions.js.map +1 -0
- package/dist/server/managementEmbed.js +8 -40
- package/dist/server/managementEmbed.js.map +1 -1
- package/dist/server/normalAuth.js +90 -30
- package/dist/server/normalAuth.js.map +1 -1
- package/dist/server/piWebStatus.js +14 -2
- package/dist/server/piWebStatus.js.map +1 -1
- package/dist/server/requestLogging.js +47 -0
- package/dist/server/requestLogging.js.map +1 -0
- package/dist/server/sessiond/sessionProxyRoutes.js +1 -6
- package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
- package/dist/server/sessiond.js +2 -1
- package/dist/server/sessiond.js.map +1 -1
- package/dist/server/sessions/sessionCleanup.js +1 -13
- package/dist/server/sessions/sessionCleanup.js.map +1 -1
- package/dist/server/sessions/sessionUiEvents.js +2 -29
- package/dist/server/sessions/sessionUiEvents.js.map +1 -1
- package/dist/server/sessions/subsessionTranscript.js +1 -29
- package/dist/server/sessions/subsessionTranscript.js.map +1 -1
- package/dist/server/sessions/toolSummary.js +37 -0
- package/dist/server/sessions/toolSummary.js.map +1 -0
- package/dist/server/terminalProxyRoutes.js +3 -11
- package/dist/server/terminalProxyRoutes.js.map +1 -1
- package/dist/server/workspaceExplorerRoutes.js +8 -41
- package/dist/server/workspaceExplorerRoutes.js.map +1 -1
- package/dist/server/workspaces/workspaceContext.js +3 -0
- package/dist/server/workspaces/workspaceContext.js.map +1 -1
- package/dist/server/workspaces/workspaceDeletionRoutes.js +1 -6
- package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -1
- package/dist/server/workspaces/workspaceRouteContext.js +13 -0
- package/dist/server/workspaces/workspaceRouteContext.js.map +1 -0
- package/dist/shared/apiTypes.d.ts +0 -16
- package/dist/shared/federatedRoutes.js +0 -1
- package/dist/shared/federatedRoutes.js.map +1 -1
- package/package.json +1 -2
- package/dist/server/workspaces/fileUploadService.js +0 -43
- package/dist/server/workspaces/fileUploadService.js.map +0 -1
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-
|
|
2
|
-
import{Q as
|
|
3
|
-
\f\r]`,Kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
|
|
4
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),No=/'/g,qo=/"/g,il=/^(?:script|style|textarea|title)$/i,sl=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=sl(1),$e=sl(2),ct=Symbol.for("lit-noChange"),B=Symbol.for("lit-nothing"),Ho=new WeakMap,wt=kt.createTreeWalker(kt,129);function rl(e,t){if(!Ur(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Uo!==void 0?Uo.createHTML(t):t}const Id=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Kt;for(let a=0;a<i;a++){const d=e[a];let p,u,h=-1,g=0;for(;g<d.length&&(n.lastIndex=g,u=n.exec(d),u!==null);)g=n.lastIndex,n===Kt?u[1]==="!--"?n=Bo:u[1]!==void 0?n=zo:u[2]!==void 0?(il.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ft):u[3]!==void 0&&(n=ft):n===ft?u[0]===">"?(n=r??Kt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?ft:u[3]==='"'?qo:No):n===qo||n===No?n=ft:n===Bo||n===zo?n=Kt:(n=ft,r=void 0);const S=n===ft&&e[a+1].startsWith("/>")?" ":"";o+=n===Kt?d+Cd:h>=0?(s.push(p),d.slice(0,h)+el+d.slice(h)+lt+S):d+lt+(h===-2?a:S)}return[rl(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class ui{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,d=this.parts,[p,u]=Id(t,i);if(this.el=ui.createElement(p,s),wt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=wt.nextNode())!==null&&d.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(el)){const g=u[n++],S=r.getAttribute(h).split(lt),P=/([.?@])?(.*)/.exec(g);d.push({type:1,index:o,name:P[2],strings:S,ctor:P[1]==="."?Md:P[1]==="?"?Td:P[1]==="@"?Ed:ys}),r.removeAttribute(h)}else h.startsWith(lt)&&(d.push({type:6,index:o}),r.removeAttribute(h));if(il.test(r.tagName)){const h=r.textContent.split(lt),g=h.length-1;if(g>0){r.textContent=Qi?Qi.emptyScript:"";for(let S=0;S<g;S++)r.append(h[S],pi()),wt.nextNode(),d.push({type:2,index:++o});r.append(h[g],pi())}}}else if(r.nodeType===8)if(r.data===tl)d.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(lt,h+1))!==-1;)d.push({type:7,index:o}),h+=lt.length-1}o++}}static createElement(t,i){const s=kt.createElement("template");return s.innerHTML=t,s}}function _t(e,t,i=e,s){if(t===ct)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=hi(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=_t(e,r._$AS(e,t.values),r,s)),t}class Ad{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,r=(t?.creationScope??kt).importNode(i,!0);wt.currentNode=r;let o=wt.nextNode(),n=0,a=0,d=s[0];for(;d!==void 0;){if(n===d.index){let p;d.type===2?p=new zt(o,o.nextSibling,this,t):d.type===1?p=new d.ctor(o,d.name,d.strings,this,t):d.type===6&&(p=new Dd(o,this,t)),this._$AV.push(p),d=s[++a]}n!==d?.index&&(o=wt.nextNode(),n++)}return wt.currentNode=kt,r}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 zt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=B,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.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=_t(this,t,i),hi(t)?t===B||t==null||t===""?(this._$AH!==B&&this._$AR(),this._$AH=B):t!==this._$AH&&t!==ct&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Rd(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!==B&&hi(this._$AH)?this._$AA.nextSibling.data=t:this.T(kt.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=ui.createElement(rl(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Ad(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Ho.get(t.strings);return i===void 0&&Ho.set(t.strings,i=new ui(t)),i}k(t){Ur(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new zt(this.O(pi()),this.O(pi()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=jo(t).nextSibling;jo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let ys=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=B,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=B}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=_t(this,t,i,0),n=!hi(t)||t!==this._$AH&&t!==ct,n&&(this._$AH=t);else{const a=t;let d,p;for(t=o[0],d=0;d<o.length-1;d++)p=_t(this,a[s+d],i,d),p===ct&&(p=this._$AH[d]),n||=!hi(p)||p!==this._$AH[d],p===B?t=B:t!==B&&(t+=(p??"")+o[d+1]),this._$AH[d]=p}n&&!r&&this.j(t)}j(t){t===B?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Md=class extends ys{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===B?void 0:t}},Td=class extends ys{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==B)}},Ed=class extends ys{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=_t(this,t,i,0)??B)===ct)return;const s=this._$AH,r=t===B&&s!==B||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==B&&(s===B||r);r&&this.element.removeEventListener(this.name,this,s),o&&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)}},Dd=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){_t(this,t)}};const Wd={I:zt},Ld=jr.litHtmlPolyfillSupport;Ld?.(ui,zt),(jr.litHtmlVersions??=[]).push("3.3.3");const Od=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new zt(t.insertBefore(pi(),o),o,void 0,i??{})}return r._$AI(e),r};const Br=globalThis;let I=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=Od(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ct}};I._$litElement$=!0,I.finalized=!0,Br.litElementHydrateSupport?.({LitElement:I});const Fd=Br.litElementPolyfillSupport;Fd?.({LitElement:I});(Br.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const _d={attribute:!0,type:String,converter:Gi,reflect:!1,hasChanged:_r},jd=(e=_d,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const d=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,d,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 d=this[n];t.call(this,a),this.requestUpdate(n,d,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function c(e){return(t,i)=>typeof i=="object"?jd(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function v(e){return c({...e,state:!0,attribute:!1})}const Ud=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function q(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Ud(i,s,{get(){return o(this)}})}}function zr(e=qr()){return Nr(e)===void 0?"normal":"management"}function Ss(e,t=qr(),i="management"){if(i==="normal"||t===void 0)return e;const s=Nr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}${r.hash}`}function ol(e,t=qr(),i="management"){if(i==="normal"||t===void 0)return e;const s=Nr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}`}function Nr(e){if(e===void 0)return;const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function qr(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}let nl=zr();function Bd(e){nl=e}function Hr(e){return Ss(e,void 0,nl)}async function b(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(Hr(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(al(n)??r.statusText)}const o=await r.json();return t(o)}async function zd(e,t){const i=await fetch(Hr(e));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(al(s)??i.statusText)}return t(await i.json())}}function al(e){if(Nd(e))return typeof e.error=="string"?e.error:void 0}function Nd(e){return typeof e=="object"&&e!==null}function Ke(e){return typeof e=="object"&&e!==null}function y(e){if(!Ke(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 V(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function he(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 T(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function pt(e,t){if(y(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function w(e,t){return t===void 0?{}:{[e]:t}}const we={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",sessionsPersistedState:"sessions.persistedState",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},qd=Object.values(we),Hd=new Set(qd);function Kd(e){return typeof e=="string"&&Hd.has(e)}function Pe(e,t){return e?.capabilities?.includes(t)===!0}function Vd(e){if(!(!Array.isArray(e)||!e.every(t=>typeof t=="string")))return e.filter(Kd)}function Ko(e){const t=y(e);return{path:m(t,"path"),exists:T(t,"exists"),config:Vo(t.config),effectiveConfig:Vo(t.effectiveConfig),envOverrides:tp(t.envOverrides)}}function Vo(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",he(t,"port")),...w("allowedHosts",Qd(t.allowedHosts)),...w("shortcuts",Yd(t.shortcuts)),...w("plugins",ep(t.plugins)),...w("normalAuth",Gd(t.normalAuth)),...w("pathAccess",Jd(t.pathAccess)),...w("uploads",Xd(t.uploads)),...w("maxUploadBytes",he(t,"maxUploadBytes")),...w("spawnSessions",Qo(t,"spawnSessions")),...w("subsessions",Qo(t,"subsessions"))}}function Gd(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB normalAuth field");return{...w("passwordHash",$(e,"passwordHash"))}}}function Qd(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 Jd(e){if(e===void 0)return;if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...w("allowedPaths",Zd(t,"pathAccess.allowedPaths"))}}function Zd(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function Xd(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function Yd(e){if(e!==void 0){if(!Ke(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 ep(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Ke(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 r=i.settings;if(r!==void 0&&(!Ke(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function tp(e){const t=y(e);return{host:T(t,"host"),port:T(t,"port"),allowedHosts:T(t,"allowedHosts"),spawnSessions:T(t,"spawnSessions"),subsessions:T(t,"subsessions")}}function ip(e){const t=y(e);return{plugins:j(sp)(t.plugins)}}function sp(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:rp(t.scope),machineSpecific:up(t.machineSpecific,"machineSpecific")??!1,enabled:T(t,"enabled")}}function rp(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function op(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:ap(t.components),release:cp(t.release),commands:dp(t.commands),messages:j(pp)(t.messages)}}function np(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:ll(t.components),capabilities:Kr(t.capabilities)}}function ap(e){const t=y(e);return{web:Ji(t.web),sessiond:Ji(t.sessiond)}}function ll(e){const t=y(e);return{web:Go(t.web),sessiond:Go(t.sessiond)}}function Go(e){const t=y(e);return{component:cl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:T(t,"available"),capabilities:Kr(t.capabilities),...w("error",$(t,"error"))}}function Ji(e){const t=y(e);return{component:cl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:T(t,"stale"),available:T(t,"available"),...w("installation",lp(t.installation)),...w("error",$(t,"error"))}}function lp(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="docker"&&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");const r=t.dockerMode;if(r!==void 0&&r!=="runtime"&&r!=="dev")throw new Error("Invalid PI WEB Docker mode");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot")),...r===void 0?{}:{dockerMode:r}}}function cp(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:T(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function dp(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 pp(e){const t=y(e);return{id:m(t,"id"),severity:hp(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function cl(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Kr(e){const t=Vd(e);if(t===void 0)throw new Error("Invalid PI WEB capabilities");return t}function hp(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function up(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Qo(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 fp(e){const t=y(e);return j(dl)(t.machines)}function dl(e){const t=y(e),i=vp(t,"kind"),s=$(t,"baseUrl"),r=pl(t,"status"),o=$(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"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function gp(e){const t=y(e),i=pl(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Ji(t.web)},...t.sessiond===void 0?{}:{sessiond:Ji(t.sessiond)},...s===void 0?{}:{error:s}}}function mp(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:ll(t.components)},...t.capabilities===void 0?{}:{capabilities:Kr(t.capabilities)},...i===void 0?{}:{error:i}}}function vp(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function pl(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 bp(e){const t=y(e);return{configured:T(t,"configured"),authenticated:T(t,"authenticated")}}function wp(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function jt(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Vr(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function yp(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:wp(t.messages),start:V(t,"start"),total:V(t,"total")}}function Jo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Sp(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:T(t,"isMain"),isGitRepo:T(t,"isGitRepo"),isGitWorktree:T(t,"isGitWorktree"),...w("effectiveConfig",xp(t.effectiveConfig))}}function xp(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...w("uploads",lh(e.uploads))}}}function mr(e){const t=y(e);return{path:m(t,"path"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Zo(e){const t=y(e);return{path:m(t,"path")}}function kp(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function vr(e){const t=y(e),i=$(t,"name"),s=Vr(t.persisted,"persisted"),r=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...s===void 0?{}:{persisted:s},...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:V(t,"messageCount"),firstMessage:m(t,"firstMessage"),...r===void 0?{}:{parentSessionPath:r},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function Vt(e){const t=y(e);return{sessionId:m(t,"sessionId"),...w("persisted",Vr(t.persisted,"persisted")),isStreaming:T(t,"isStreaming"),isCompacting:T(t,"isCompacting"),isBashRunning:T(t,"isBashRunning"),pendingMessageCount:V(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Mp)(t.queuedMessages),...w("messageCount",he(t,"messageCount")),tokens:Tp(t.tokens),cost:V(t,"cost"),...Wp(t.model),...Vp(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function hl(e){const t=y(e),i=t.skippedBusySessionIds===void 0?void 0:jt(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:Rp(t.thresholds),projects:j(Ip)(t.projects),totals:Ap(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function $p(e){const t=y(e);return{...hl(t),archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds")}}function Pp(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),failures:j(ul)(t.failures),generatedAt:m(t,"generatedAt")}}function Cp(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds"),failures:j(ul)(t.failures),generatedAt:m(t,"generatedAt")}}function ul(e){const t=y(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function Rp(e){const t=y(e);return{...w("archiveIdleDays",he(t,"archiveIdleDays")),...w("deleteArchivedDays",he(t,"deleteArchivedDays"))}}function Ip(e){const t=y(e);return{cwd:m(t,"cwd"),archiveCount:V(t,"archiveCount"),deleteCount:V(t,"deleteCount")}}function Ap(e){const t=y(e);return{archiveCount:V(t,"archiveCount"),deleteCount:V(t,"deleteCount")}}function Mp(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"),...w("imageCount",he(t,"imageCount"))}}function Tp(e){const t=y(e);return{input:V(t,"input"),output:V(t,"output"),cacheRead:V(t,"cacheRead"),cacheWrite:V(t,"cacheWrite"),total:V(t,"total")}}function fl(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",he(t,"contextWindow")),...w("reasoning",t.reasoning),...w("input",Ep(t.input))}}function Ep(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Dp)}}function Dp(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Wp(e){return e===void 0?{}:{model:fl(e)}}function Lp(e){const t=y(e);return{models:j(fl)(t.models)}}function Op(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Fp(e){const t=y(e);return{levels:j(Op)(t.levels)}}function _p(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function jp(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 Up(e){const t=y(e),i=t.source===void 0?void 0:jp(t.source);return{configured:T(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Bp(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:_p(t.authType),status:Up(t.status)}}function zp(e){const t=y(e);return{providers:j(Bp)(t.providers)}}function $i(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Np(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",qp(t.auth)),...w("prompt",Hp(t.prompt)),...w("select",Kp(t.select))}}function Np(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function qp(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Hp(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 Kp(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(bl)(t.options)}}function Vp(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:tn(t,"tokens"),contextWindow:V(t,"contextWindow"),percent:tn(t,"percent")}}}function Gp(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 br(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 Qp(e){const t=y(e);return{path:m(t,"path"),entries:j(Jp)(t.entries),scannedAt:m(t,"scannedAt"),truncated:T(t,"truncated")}}function Jp(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",he(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function Zp(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",eh(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:V(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:T(t,"truncated"),binary:T(t,"binary")}}function gl(e){const t=y(e);return{path:m(t,"path"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt"),created:T(t,"created")}}function Xp(e){const t=y(e);return{path:m(t,"path"),existed:T(t,"existed")}}function Yp(e){const t=y(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt")}}function eh(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function th(e){const t=y(e);return{isGitRepo:T(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",he(t,"ahead")),...w("behind",he(t,"behind")),files:j(ih)(t.files)}}function ih(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Xo(t.index),workingTree:Xo(t.workingTree)}}function Xo(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 sh(e){const t=y(e);return{...w("path",$(t,"path")),staged:T(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:T(t,"truncated")}}function Us(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:T(t,"exited"),...w("exitCode",he(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function ci(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:rh(t.status),...w("exitCode",he(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:oh(t.metadata,"metadata")}}function rh(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function oh(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function nh(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:T(t,"hasSessionActivity"),hasTerminalActivity:T(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ah(e){const t=y(e);return{workspaces:j(nh)(t.workspaces),generatedAt:m(t,"generatedAt")}}function lh(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function ch(e){const t=y(e);return{packages:j(ml)(t.packages)}}function Bs(e){const t=y(e),i=$(t,"source"),s=t.scope===void 0?void 0:vl(t.scope),r=Vr(t.removed,"removed");return{action:dh(t.action),...w("source",i),...w("scope",s),...w("removed",r),packages:j(ml)(t.packages)}}function ml(e){const t=y(e);return{source:m(t,"source"),scope:vl(t.scope),filtered:T(t,"filtered"),...w("installedPath",$(t,"installedPath"))}}function vl(e){if(e!=="user"&&e!=="project")throw new Error("Invalid Pi package scope");return e}function dh(e){if(e!=="install"&&e!=="remove"&&e!=="update")throw new Error("Invalid Pi package mutation action");return e}function Yo(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:j(bl)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...ph(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function bl(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function ph(e){return e===void 0?{}:{session:vr(e)}}function yt(e){return{accepted:pt(e,"accepted")}}function hh(e){const t=y(e);return j(uh)(t.attachments)}function uh(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:V(t,"size")}}function wr(e){return{closed:pt(e,"closed")}}function fh(e){return{aborted:pt(e,"aborted")}}function gh(e){return{stopped:pt(e,"stopped")}}function en(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:jt(t.sessionIds,"sessionIds"),s=he(t,"archivedCount"),r=he(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function mh(e){return{restored:pt(e,"restored")}}function vh(e){return{deleted:pt(e,"deleted")}}function bh(e){return{detached:pt(e,"detached")}}function wh(e){return{reloaded:pt(e,"reloaded")}}function tn(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 yh(e){return typeof e=="string"?e:e.id}function Sh(e){return typeof e=="string"?void 0:e.cwd}function xh(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function kh(e,t,i="local"){const s=new URLSearchParams,r=Sh(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(yh(e))}/messages${o===""?"":`?${o}`}`}function $h(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Ph(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function wl(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function yl(e){return typeof e=="string"?e:e.id}function Gr(e){return typeof e=="string"?void 0:e.cwd}function Sl(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(yl(e))}`}function ee(e,t,i="local"){return`${Sl(e,i)}/${t}`}function Pi(e,t,i="local"){return`${ee(e,t,i)}${xl(e)}`}function Ch(e,t="local"){return`${Sl(e,t)}${xl(e)}`}function xl(e){const t=Gr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function se(e,t={}){const i=Gr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function sn(e){return JSON.stringify({sessions:e.map(Rh)})}function Rh(e){const t=yl(e),i=Gr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const kl={piWebStatus:(e="local")=>b(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,op),piWebRuntime:()=>b("/api/pi-web/runtime",np)},Ih={machines:()=>b("/api/machines",fp),addMachine:e=>b("/api/machines",dl,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>b(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>b(`/api/machines/${encodeURIComponent(e)}/health`,gp),runtime:e=>b(`/api/machines/${encodeURIComponent(e)}/runtime`,mp)};function rn(e){return e===void 0?"/api/config":`${R(e)}/config`}function Ah(e){return e===void 0?"/api/plugins":`${R(e)}/plugins`}const Ne={config:e=>b(rn(e),Ko),saveConfig:(e,t)=>b(rn(t),Ko,{method:"PUT",body:JSON.stringify({config:e})})},Wt={status:()=>b("/api/normal-auth/status",bp),setup:e=>b("/api/normal-auth/setup",yt,{method:"POST",body:JSON.stringify({password:e})}),login:e=>b("/api/normal-auth/login",yt,{method:"POST",body:JSON.stringify({password:e})}),changePassword:(e,t)=>b("/api/normal-auth/change-password",yt,{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t})})},si={plugins:e=>b(Ah(e),ip)};function Ci(e="",t){const i=t===void 0?"/api/pi-packages":`${R(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const ri={packages:e=>b(Ci("",e),ch),install:(e,t)=>{const i={source:e};return b(Ci("install",t),Bs,{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return b(Ci("remove",i),Bs,{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return b(Ci("update",t),Bs,{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},$l={workspaceActivity:(e="local")=>b(`${R(e)}/activity`,ah)},Mh={projects:(e="local")=>b(`${R(e)}/projects`,j(Jo)),addProject:(e,t,i,s="local")=>b(`${R(s)}/projects`,Jo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>b(`${R(t)}/projects/${encodeURIComponent(e)}`,wr,{method:"DELETE"}),projectDirectories:(e,t="local")=>b(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,j(br))},Lt={workspaces:(e,t="local")=>b(`${R(t)}/projects/${e}/workspaces`,j(Sp)),deleteWorkspace:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ci,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Qp),workspaceFile:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Zp),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?Lh(e,t,i,s):b(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,mr,{method:"POST",body:JSON.stringify({path:i,contentBase64:await Dh(s)})}),createWorkspaceFile:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,mr,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,d=a?new Uint8Array(s):new TextEncoder().encode(s);return b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,gl,{method:"PUT",body:d,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,Xp,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,Yp,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zo,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>b(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zo,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,kp,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>wl(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>Oh(e,t,i,s)},yr={sessions:(e,t="local")=>b(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(vr)),startSession:(e,t="local")=>b(`${R(t)}/sessions`,vr,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>b(`${R(t)}/sessions/cleanup/preview`,hl,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>b(`${R(t)}/sessions/cleanup`,$p,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/archive`,Pp,{method:"POST",body:sn(e)}),deleteArchivedMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/delete-archived`,Cp,{method:"POST",body:sn(e)}),messages:(e,t,i="local")=>b(kh(e,t,i),yp),status:(e,t="local")=>b(Pi(e,"status",t),Vt),models:(e,t="local")=>b(Pi(e,"models",t),Lp),setModel:(e,t,i,s="local")=>b(ee(e,"model",s),Vt,{method:"POST",body:se(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>b(ee(e,"model/cycle",i),Vt,{method:"POST",body:se(e,{direction:t})}),thinkingLevels:(e,t="local")=>b(Pi(e,"thinking-levels",t),Fp),setThinkingLevel:(e,t,i="local")=>b(ee(e,"thinking-level",i),Vt,{method:"POST",body:se(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>b(ee(e,"thinking-level/cycle",t),Vt,{method:"POST",body:se(e)}),commands:(e,t="local")=>b(Pi(e,"commands",t),j(Gp)),prompt:(e,t,i,s="local",r)=>b(ee(e,"prompt",s),yt,{method:"POST",body:se(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>b(ee(e,"attachments",i),hh,{method:"POST",body:se(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>b(ee(e,"shell",i),yt,{method:"POST",body:se(e,{text:t})}),runCommand:(e,t,i="local")=>b(ee(e,"commands/run",i),Yo,{method:"POST",body:se(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>b(ee(e,"commands/respond",s),Yo,{method:"POST",body:se(e,{requestId:t,value:i})}),abort:(e,t="local")=>b(ee(e,"abort",t),fh,{method:"POST",body:se(e)}),stop:(e,t="local")=>b(ee(e,"stop",t),gh,{method:"POST",body:se(e)}),archive:(e,t="local")=>b(ee(e,"archive",t),en,{method:"POST",body:se(e)}),archiveWithDescendants:(e,t="local")=>b(ee(e,"archive-tree",t),en,{method:"POST",body:se(e)}),restore:(e,t="local")=>b(ee(e,"restore",t),mh,{method:"POST",body:se(e)}),deleteArchived:(e,t="local")=>b(Ch(e,t),vh,{method:"DELETE"}),detachParent:(e,t="local")=>b(ee(e,"detach-parent",t),bh,{method:"POST",body:se(e)}),reloadSession:(e,t="local")=>b(ee(e,"reload",t),wh,{method:"POST",body:se(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 b(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,zp)},saveApiKey:(e,t,i="local")=>b(`${R(i)}/auth/api-key`,yt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>b(`${R(t)}/auth/logout`,yt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>b(`${R(t)}/auth/oauth`,$i,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,$i),respondOAuthFlow:(e,t,i,s="local")=>b(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,$i,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,$i,{method:"POST"})},Ot={terminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Us)),startTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Us,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,wr,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,wr,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Us,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ci,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>b(`${R(t)}/terminal-command-runs${Eh(e)}`,j(ci)),getCommandRun:(e,t="local")=>Th(e,t),cancelCommandRun:(e,t="local")=>b(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ci,{method:"POST"})};async function Th(e,t){return zd(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`,ci)}function Eh(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 Pl(e){if(!Fh(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Dh(e){return Wh(await e.arrayBuffer())}function Wh(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function Lh(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(Hr(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Pl(n)??o.statusText)}return mr(await o.json())}async function Oh(e,t,i,s){const r=await fetch(wl(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Pl(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const d=i.split("/").pop();a.download=d===void 0||d===""?"download":d,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function Fh(e){return typeof e=="object"&&e!==null}const _h={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?b(`${R(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(br)):(s.set("cwd",e),b(`${R(i.machineId)}/files?${s.toString()}`,j(br)))}},jh={gitStatus:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,th),gitDiff:(e,t,i,s="local")=>b(xh(s,e,t,i),sh)},K={...kl,...Ih,...Ne,...Wt,...si,...ri,...$l,...Mh,...Lt,...yr,...Ot,..._h,...jh};function Uh(e,t="local",i=zr()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=ol(`${Qr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${Jr()}${n}`)}function ck(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Jr()}${Qr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Bh(e="local",t=zr()){const i=ol(`${Qr(e)}/events`,void 0,t);return new WebSocket(`${Jr()}${i}`)}function Qr(e){return`/api/machines/${encodeURIComponent(e)}`}function Jr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const di=".pi-web/uploads";class xs extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Cl extends Error{constructor(t,i){super(Qh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function on(e){return e?.uploads?.defaultFolder??di}function zh(e,t){return e?.uploads?.defaultFolder??t}function Zr(e,t){const i=nn(e,"upload destination",{allowEmpty:!0}),s=nn(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Nh(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((d,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,d(g))};r.open("PUT",$h(e,t,i.path,Kh(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Vh(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(gl(Rl(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Yh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new xs(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function qh(e,t,i,s={}){const r=s.destinationFolder??di,o=i.map((h,g)=>({index:g,name:h.name,path:Zr(r,h.name),loaded:0,total:h.size,percent:Xr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const d={requested:!1},p=()=>{s.onProgress?.(Gh(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let S=0;S<i.length;S+=1){if(d.requested)throw new xs;a=S;const P=i[S],C=o[S];if(!(P===void 0||C===void 0)){n=Nh(e,t,{path:C.path,file:P},{...Hh(s),onProgress:X=>{C.total=X.total,C.loaded=Math.min(X.loaded,C.total),C.percent=X.percent,C.lengthComputable=X.lengthComputable,p()}});try{const X=await n.promise;C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,h.push(X),p()}catch(X){if(Zh(X,d))throw X;const ot=Jh(X);C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,C.error=ot,g.push({index:S,name:P.name,path:C.path,error:ot}),p()}finally{n=void 0}}}if(g.length>0)throw new Cl(g,h);return h})(),cancel:()=>{d.requested=!0,n?.cancel()}}}function Hh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Kh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Vh(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Xr(e.loaded,i),lengthComputable:e.lengthComputable}}function Gh(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Xr(r,s),done:i}}function Xr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Qh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Jh(e){return e instanceof Error?e.message:String(e)}function Zh(e,t){return t.requested||e instanceof xs}function nn(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Xh(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function Xh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Rl(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Yh(e){const t=eu(e);return tu(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function eu(e){try{return Rl(e)}catch{return}}function tu(e){return typeof e=="object"&&e!==null}function _i(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function iu(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function dt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Il(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Al="local";function zs(e,t){return`${e}:${t}`}function oi(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Al}class su{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??$l}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,ru(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),r=f(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=ou(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function ru(e){const t={};for(const i of e.workspaces)Il(i)&&(t[i.cwd]=i);return t}function ou(e,t){const i={...e};return Il(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class nu{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??K,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=au(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:f(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 r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.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(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}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 r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,f(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,f(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:f(this.getState())}),s=i.filter(o=>o.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 r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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,f(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 r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!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??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",d=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:d}})}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,f(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,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function au(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 r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function vi(e){return e.replaceAll(":",".")}function lu(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function Ns(e,t){const i=lu(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function be(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));cu(r,s)}function cu(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function du(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Zr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:ln(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:ln(0,i),status:"uploading",startedAt:e.startedAt}}function pu(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function hu(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Yr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function uu(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Yr(s),status:"error",error:t,completedAt:i}}function an(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Yr(s),status:"cancelled",error:i,completedAt:t}}function Yr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ln(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const Ri=vi("core:workspace.files");class fu{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??K,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??qh,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const d=await this.api.workspaceTree(t.id,i.id,a,s);return[a,d.entries]}catch(d){if(cn(d))return;throw d}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:dn(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),be(Ri,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),be(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}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 r=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(cn(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),be(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());qs(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const r=f(this.getState());qs(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,r):await this.api.deleteWorkspaceFile(t.id,i.id,s,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||qs(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),be(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let d;try{d=du({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(d);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(d.id,h)}})}catch(h){return this.failUploadBatch(d.id,h),{batchId:d.id,done:Promise.resolve()}}this.uploadTasks.set(d.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(d.id,h,i)}).catch(async h=>{await this.handleUploadFailure(d.id,h,i)}).finally(()=>{this.uploadTasks.delete(d.id)});return{batchId:d.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(an(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:dn(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(pu(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(hu(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Cl)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(gu(i)){const n=an(s,this.now());return this.setUploadBatch(n),n}const r=mu(i),o=uu(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function cn(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function gu(e){return e instanceof xs}function mu(e){return e instanceof Error?e.message:String(e)}function dn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qs(e){const t=e.selectedFilePath;return t===void 0?"file":vu(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function vu(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const pn=vi("core:workspace.git");class bu{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 K.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),be(pn,"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"}),be(pn,"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[r,o]=await Promise.all([K.gitDiff(i.id,s.id,{path:t},f(this.getState())),K.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}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 wu{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await K.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:hn(this.getState().machineActivities,r),machineRuntimes:hn(this.getState().machineRuntimes,r)}),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,..._i()}),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 K.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 K.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:Hs(this.getState().machineStatuses,t.id),machineRuntimes:Hs(this.getState().machineRuntimes,t.id),machineActivities:Hs(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await K.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 K.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(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await K.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(r=>K.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>K.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Hs(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function hn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class yu{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await K.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await K.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await K.closeProject(t,f(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 Sr="pi-web:cached-new-sessions:v1",Su="browserCachedNew",Nt="local";function bi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function un(e,t=Nt,i=bi()){if(e.messageCount!==0||e.archived===!0)return;const s=eo(i).filter(r=>r.id!==e.id||r.machineId!==t);to([xr(e,t),...s],i)}function xr(e,t=Nt){return{...e,browserCachedNew:!0,machineId:t}}function fn(e,t=Nt,i=bi()){const s=eo(i).filter(r=>r.id!==e||r.machineId!==t);to(s,i)}function Ml(e,t,i=Nt,s=bi()){const r=new Set(t.map(d=>d.id)),o=eo(s),n=o.filter(d=>d.machineId!==i||!r.has(d.id));return n.length!==o.length&&to(n,s),[...n.filter(d=>d.machineId===i&&d.cwd===e),...t]}function Zi(e){return e===void 0?!1:$u(e)&&e.browserCachedNew===!0}function xu(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:Nt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function eo(e=bi()){try{const t=e?.getItem(Sr);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>ku(s)):[]}catch{return[]}}function to(e,t=bi()){try{e.length===0?t?.removeItem(Sr):t?.setItem(Sr,JSON.stringify(e))}catch{}}function ku(e){if(!Pu(e))return[];const t=At(e,"id"),i=At(e,"path"),s=At(e,"cwd"),r=At(e,"created"),o=At(e,"modified"),n=At(e,"firstMessage"),a=Cu(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const d=Ks(e,"name"),p=Ks(e,"parentSessionPath"),u=Ks(e,"machineId")??Nt;return[{id:t,path:i,cwd:s,...d===void 0?{}:{name:d},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function $u(e){return Su in e}function Pu(e){return typeof e=="object"&&e!==null}function At(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ks(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Cu(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Ru(e){return Nu(e.flatMap(io)).filter(t=>t.parts.length>0)}function qe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Gt(e,t){const i=Lu(t);return i===void 0?e:{...e,meta:i}}function Iu(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,qe(t,i)]}function Au(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 io(e){if(Tu(e))return[e];if(_(e,"role")==="bashExecution")return[Gt(_u(e),e)];const t=ju(_(e,"role")),i=Uu(Re(e,"content"),e),s=t==="user"?Eu(i):void 0;if(s!==void 0)return s.map(p=>Gt(p,e));const r=Wu(e);if(t==="tool")return[Gt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[Gt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],d=Mu(e);return d===void 0?a:[...a,Gt(d,e)]}function Mu(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return qe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Tu(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Re(e,"parts"))}function Eu(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Du(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 Du(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 Wu(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Lu(e){const t=Ou(Re(e,"timestamp")),i=Fu(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Ou(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 Fu(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 _u(e){const t=_(e,"command")??"",i=ji(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Re(e,"output");s!=null&&i.push("",Yi(s));const r=Re(e,"exitCode");r!=null&&i.push("",`exit ${Yi(r)}`),ji(e,"cancelled")===!0&&i.push("","cancelled"),ji(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{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-_Lzl-tA7.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-BwONrl2w.js","assets/TerminalPanel-BVBJC-6w.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as Ao,v as ut,J as _s,R as nd,S as ad,G as ld,U as cd,V as dd,W as pd,A as hd,X as ud,Y as fd,Z as Mo,w as To,_ as gd}from"./vendor-editor-core-C7aWiQy0.js";import{m as md,d as vd,i as bd}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Fi=globalThis,Lr=Fi.ShadowRoot&&(Fi.ShadyCSS===void 0||Fi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Or=Symbol(),Eo=new WeakMap;let Xa=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Or)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(Lr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Eo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Eo.set(i,t))}return t}toString(){return this.cssText}};const wd=e=>new Xa(typeof e=="string"?e:e+"",void 0,Or),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>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.")})(r)+e[o+1],e[0]);return new Xa(i,e,Or)},yd=(e,t)=>{if(Lr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Fi.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},Do=Lr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return wd(i)})(e):e;const{is:Sd,defineProperty:xd,getOwnPropertyDescriptor:kd,getOwnPropertyNames:$d,getOwnPropertySymbols:Pd,getPrototypeOf:Cd}=Object,ws=globalThis,Wo=ws.trustedTypes,Rd=Wo?Wo.emptyScript:"",Id=ws.reactiveElementPolyfillSupport,li=(e,t)=>e,Gi={toAttribute(e,t){switch(t){case Boolean:e=e?Rd: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}},Fr=(e,t)=>!Sd(e,t),Lo={attribute:!0,type:String,converter:Gi,reflect:!1,useDefault:!1,hasChanged:Fr};Symbol.metadata??=Symbol("metadata"),ws.litPropertyMetadata??=new WeakMap;let Wt=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=Lo){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(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&xd(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=kd(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Lo}static _$Ei(){if(this.hasOwnProperty(li("elementProperties")))return;const t=Cd(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(li("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(li("properties"))){const i=this.properties,s=[...$d(i),...Pd(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,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 r of s)i.unshift(Do(r))}else t!==void 0&&i.push(Do(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 yd(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),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:Gi).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Gi;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Fr)(o,i)||s.useDefault&&s.reflect&&o===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:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!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[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,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){}};Wt.elementStyles=[],Wt.shadowRootOptions={mode:"open"},Wt[li("elementProperties")]=new Map,Wt[li("finalized")]=new Map,Id?.({ReactiveElement:Wt}),(ws.reactiveElementVersions??=[]).push("2.1.2");const _r=globalThis,Oo=e=>e,Qi=_r.trustedTypes,Fo=Qi?Qi.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ya="$lit$",lt=`lit$${Math.random().toFixed(9).slice(2)}$`,el="?"+lt,Ad=`<${el}>`,$t=document,pi=()=>$t.createComment(""),hi=e=>e===null||typeof e!="object"&&typeof e!="function",jr=Array.isArray,Md=e=>jr(e)||typeof e?.[Symbol.iterator]=="function",js=`[
|
|
3
|
+
\f\r]`,Kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_o=/-->/g,jo=/>/g,ft=RegExp(`>|${js}(?:([^\\s"'>=/]+)(${js}*=${js}*(?:[^
|
|
4
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Uo=/'/g,Bo=/"/g,tl=/^(?:script|style|textarea|title)$/i,il=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=il(1),$e=il(2),ct=Symbol.for("lit-noChange"),B=Symbol.for("lit-nothing"),zo=new WeakMap,yt=$t.createTreeWalker($t,129);function sl(e,t){if(!jr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fo!==void 0?Fo.createHTML(t):t}const Td=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Kt;for(let a=0;a<i;a++){const d=e[a];let p,u,h=-1,g=0;for(;g<d.length&&(n.lastIndex=g,u=n.exec(d),u!==null);)g=n.lastIndex,n===Kt?u[1]==="!--"?n=_o:u[1]!==void 0?n=jo:u[2]!==void 0?(tl.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ft):u[3]!==void 0&&(n=ft):n===ft?u[0]===">"?(n=r??Kt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?ft:u[3]==='"'?Bo:Uo):n===Bo||n===Uo?n=ft:n===_o||n===jo?n=Kt:(n=ft,r=void 0);const S=n===ft&&e[a+1].startsWith("/>")?" ":"";o+=n===Kt?d+Ad:h>=0?(s.push(p),d.slice(0,h)+Ya+d.slice(h)+lt+S):d+lt+(h===-2?a:S)}return[sl(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class ui{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,d=this.parts,[p,u]=Td(t,i);if(this.el=ui.createElement(p,s),yt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=yt.nextNode())!==null&&d.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(Ya)){const g=u[n++],S=r.getAttribute(h).split(lt),P=/([.?@])?(.*)/.exec(g);d.push({type:1,index:o,name:P[2],strings:S,ctor:P[1]==="."?Dd:P[1]==="?"?Wd:P[1]==="@"?Ld:ys}),r.removeAttribute(h)}else h.startsWith(lt)&&(d.push({type:6,index:o}),r.removeAttribute(h));if(tl.test(r.tagName)){const h=r.textContent.split(lt),g=h.length-1;if(g>0){r.textContent=Qi?Qi.emptyScript:"";for(let S=0;S<g;S++)r.append(h[S],pi()),yt.nextNode(),d.push({type:2,index:++o});r.append(h[g],pi())}}}else if(r.nodeType===8)if(r.data===el)d.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(lt,h+1))!==-1;)d.push({type:7,index:o}),h+=lt.length-1}o++}}static createElement(t,i){const s=$t.createElement("template");return s.innerHTML=t,s}}function _t(e,t,i=e,s){if(t===ct)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=hi(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=_t(e,r._$AS(e,t.values),r,s)),t}class Ed{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,r=(t?.creationScope??$t).importNode(i,!0);yt.currentNode=r;let o=yt.nextNode(),n=0,a=0,d=s[0];for(;d!==void 0;){if(n===d.index){let p;d.type===2?p=new zt(o,o.nextSibling,this,t):d.type===1?p=new d.ctor(o,d.name,d.strings,this,t):d.type===6&&(p=new Od(o,this,t)),this._$AV.push(p),d=s[++a]}n!==d?.index&&(o=yt.nextNode(),n++)}return yt.currentNode=$t,r}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 zt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=B,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.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=_t(this,t,i),hi(t)?t===B||t==null||t===""?(this._$AH!==B&&this._$AR(),this._$AH=B):t!==this._$AH&&t!==ct&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Md(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!==B&&hi(this._$AH)?this._$AA.nextSibling.data=t:this.T($t.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=ui.createElement(sl(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Ed(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=zo.get(t.strings);return i===void 0&&zo.set(t.strings,i=new ui(t)),i}k(t){jr(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new zt(this.O(pi()),this.O(pi()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Oo(t).nextSibling;Oo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let ys=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=B,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=B}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=_t(this,t,i,0),n=!hi(t)||t!==this._$AH&&t!==ct,n&&(this._$AH=t);else{const a=t;let d,p;for(t=o[0],d=0;d<o.length-1;d++)p=_t(this,a[s+d],i,d),p===ct&&(p=this._$AH[d]),n||=!hi(p)||p!==this._$AH[d],p===B?t=B:t!==B&&(t+=(p??"")+o[d+1]),this._$AH[d]=p}n&&!r&&this.j(t)}j(t){t===B?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Dd=class extends ys{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===B?void 0:t}},Wd=class extends ys{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==B)}},Ld=class extends ys{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=_t(this,t,i,0)??B)===ct)return;const s=this._$AH,r=t===B&&s!==B||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==B&&(s===B||r);r&&this.element.removeEventListener(this.name,this,s),o&&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)}},Od=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){_t(this,t)}};const Fd={I:zt},_d=_r.litHtmlPolyfillSupport;_d?.(ui,zt),(_r.litHtmlVersions??=[]).push("3.3.3");const jd=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new zt(t.insertBefore(pi(),o),o,void 0,i??{})}return r._$AI(e),r};const Ur=globalThis;let I=class extends Wt{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=jd(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ct}};I._$litElement$=!0,I.finalized=!0,Ur.litElementHydrateSupport?.({LitElement:I});const Ud=Ur.litElementPolyfillSupport;Ud?.({LitElement:I});(Ur.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Bd={attribute:!0,type:String,converter:Gi,reflect:!1,hasChanged:Fr},zd=(e=Bd,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const d=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,d,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 d=this[n];t.call(this,a),this.requestUpdate(n,d,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function c(e){return(t,i)=>typeof i=="object"?zd(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function v(e){return c({...e,state:!0,attribute:!1})}const Nd=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function q(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Nd(i,s,{get(){return o(this)}})}}const rl="management";function ol(e=qd()){return cl(e)===rl}function Br(e=zr()){return ll(e)===void 0?"normal":"management"}function Ss(e,t=zr(),i="management"){return al(e,t,i,!0)}function nl(e,t=zr(),i="management"){return al(e,t,i,!1)}function al(e,t,i,s){if(i==="normal"||t===void 0)return e;const r=ll(t);if(r===void 0)return e;const o=new URL(e,t.origin);return o.searchParams.set("embed",r.embed),o.searchParams.set("token",r.token),`${o.pathname}${o.search}${s?o.hash:""}`}function ll(e){if(e===void 0)return;const t=cl(e.search),i=e.searchParams.get("token")?.trim();if(!(t!==rl||i===void 0||i===""))return{embed:t,token:i}}function cl(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function qd(){return typeof window>"u"?void 0:window.location.search}function zr(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}let dl=Br();function Hd(e){dl=e}function pl(e){return Ss(e,void 0,dl)}async function b(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(pl(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(ul(n)??r.statusText)}const o=await r.json();return t(o)}async function hl(e,t){const i=await fetch(pl(e));if(!(i.status===204||i.status===404)){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(ul(s)??i.statusText)}return t(await i.json())}}function ul(e){if(Kd(e))return typeof e.error=="string"?e.error:void 0}function Kd(e){return typeof e=="object"&&e!==null}function Ke(e){return typeof e=="object"&&e!==null}function y(e){if(!Ke(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 G(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function we(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 T(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function pt(e,t){if(y(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function w(e,t){return t===void 0?{}:{[e]:t}}const be={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",sessionsPersistedState:"sessions.persistedState",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},Vd=Object.values(be),Gd=new Set(Vd);function Qd(e){return typeof e=="string"&&Gd.has(e)}function Pe(e,t){return e?.capabilities?.includes(t)===!0}function Jd(e){if(!(!Array.isArray(e)||!e.every(t=>typeof t=="string")))return e.filter(Qd)}function No(e){const t=y(e);return{path:m(t,"path"),exists:T(t,"exists"),config:qo(t.config),effectiveConfig:qo(t.effectiveConfig),envOverrides:rp(t.envOverrides)}}function qo(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",we(t,"port")),...w("allowedHosts",Xd(t.allowedHosts)),...w("shortcuts",ip(t.shortcuts)),...w("plugins",sp(t.plugins)),...w("normalAuth",Zd(t.normalAuth)),...w("pathAccess",Yd(t.pathAccess)),...w("uploads",tp(t.uploads)),...w("maxUploadBytes",we(t,"maxUploadBytes")),...w("spawnSessions",Ko(t,"spawnSessions")),...w("subsessions",Ko(t,"subsessions"))}}function Zd(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB normalAuth field");return{...w("passwordHash",$(e,"passwordHash"))}}}function Xd(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 Yd(e){if(e===void 0)return;if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...w("allowedPaths",ep(t,"pathAccess.allowedPaths"))}}function ep(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function tp(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function ip(e){if(e!==void 0){if(!Ke(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 sp(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Ke(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 r=i.settings;if(r!==void 0&&(!Ke(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function rp(e){const t=y(e);return{host:T(t,"host"),port:T(t,"port"),allowedHosts:T(t,"allowedHosts"),spawnSessions:T(t,"spawnSessions"),subsessions:T(t,"subsessions")}}function op(e){const t=y(e);return{plugins:j(np)(t.plugins)}}function np(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:ap(t.scope),machineSpecific:mp(t.machineSpecific,"machineSpecific")??!1,enabled:T(t,"enabled")}}function ap(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function lp(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:dp(t.components),release:hp(t.release),commands:up(t.commands),messages:j(fp)(t.messages)}}function cp(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fl(t.components),capabilities:Nr(t.capabilities)}}function dp(e){const t=y(e);return{web:Ji(t.web),sessiond:Ji(t.sessiond)}}function fl(e){const t=y(e);return{web:Ho(t.web),sessiond:Ho(t.sessiond)}}function Ho(e){const t=y(e);return{component:gl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:T(t,"available"),capabilities:Nr(t.capabilities),...w("error",$(t,"error"))}}function Ji(e){const t=y(e);return{component:gl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:T(t,"stale"),available:T(t,"available"),...w("installation",pp(t.installation)),...w("error",$(t,"error"))}}function pp(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="docker"&&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");const r=t.dockerMode;if(r!==void 0&&r!=="runtime"&&r!=="dev")throw new Error("Invalid PI WEB Docker mode");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot")),...r===void 0?{}:{dockerMode:r}}}function hp(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:T(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function up(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 fp(e){const t=y(e);return{id:m(t,"id"),severity:gp(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function gl(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Nr(e){const t=Jd(e);if(t===void 0)throw new Error("Invalid PI WEB capabilities");return t}function gp(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function mp(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Ko(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 vp(e){const t=y(e);return j(ml)(t.machines)}function ml(e){const t=y(e),i=yp(t,"kind"),s=$(t,"baseUrl"),r=vl(t,"status"),o=$(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"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function bp(e){const t=y(e),i=vl(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Ji(t.web)},...t.sessiond===void 0?{}:{sessiond:Ji(t.sessiond)},...s===void 0?{}:{error:s}}}function wp(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:fl(t.components)},...t.capabilities===void 0?{}:{capabilities:Nr(t.capabilities)},...i===void 0?{}:{error:i}}}function yp(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function vl(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 Sp(e){const t=y(e);return{configured:T(t,"configured"),authenticated:T(t,"authenticated")}}function xp(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function jt(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function qr(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function kp(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:xp(t.messages),start:G(t,"start"),total:G(t,"total")}}function Vo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function $p(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:T(t,"isMain"),isGitRepo:T(t,"isGitRepo"),isGitWorktree:T(t,"isGitWorktree"),...w("effectiveConfig",Pp(t.effectiveConfig))}}function Pp(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...w("uploads",lh(e.uploads))}}}function Go(e){const t=y(e);return{path:m(t,"path")}}function Cp(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function mr(e){const t=y(e),i=$(t,"name"),s=qr(t.persisted,"persisted"),r=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...s===void 0?{}:{persisted:s},...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:G(t,"messageCount"),firstMessage:m(t,"firstMessage"),...r===void 0?{}:{parentSessionPath:r},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function Vt(e){const t=y(e);return{sessionId:m(t,"sessionId"),...w("persisted",qr(t.persisted,"persisted")),isStreaming:T(t,"isStreaming"),isCompacting:T(t,"isCompacting"),isBashRunning:T(t,"isBashRunning"),pendingMessageCount:G(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Dp)(t.queuedMessages),...w("messageCount",we(t,"messageCount")),tokens:Wp(t.tokens),cost:G(t,"cost"),...Lp(t.model),...Gp(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function bl(e){const t=y(e),i=t.skippedBusySessionIds===void 0?void 0:jt(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:Mp(t.thresholds),projects:j(Tp)(t.projects),totals:Ep(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function Rp(e){const t=y(e);return{...bl(t),archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds")}}function Ip(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),failures:j(wl)(t.failures),generatedAt:m(t,"generatedAt")}}function Ap(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds"),failures:j(wl)(t.failures),generatedAt:m(t,"generatedAt")}}function wl(e){const t=y(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function Mp(e){const t=y(e);return{...w("archiveIdleDays",we(t,"archiveIdleDays")),...w("deleteArchivedDays",we(t,"deleteArchivedDays"))}}function Tp(e){const t=y(e);return{cwd:m(t,"cwd"),archiveCount:G(t,"archiveCount"),deleteCount:G(t,"deleteCount")}}function Ep(e){const t=y(e);return{archiveCount:G(t,"archiveCount"),deleteCount:G(t,"deleteCount")}}function Dp(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 Wp(e){const t=y(e);return{input:G(t,"input"),output:G(t,"output"),cacheRead:G(t,"cacheRead"),cacheWrite:G(t,"cacheWrite"),total:G(t,"total")}}function yl(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",we(t,"contextWindow")),...w("reasoning",t.reasoning)}}function Lp(e){return e===void 0?{}:{model:yl(e)}}function Op(e){const t=y(e);return{models:j(yl)(t.models)}}function Fp(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function _p(e){const t=y(e);return{levels:j(Fp)(t.levels)}}function jp(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Up(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 Bp(e){const t=y(e),i=t.source===void 0?void 0:Up(t.source);return{configured:T(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function zp(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:jp(t.authType),status:Bp(t.status)}}function Np(e){const t=y(e);return{providers:j(zp)(t.providers)}}function $i(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:qp(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Hp(t.auth)),...w("prompt",Kp(t.prompt)),...w("select",Vp(t.select))}}function qp(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Hp(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Kp(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 Vp(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j($l)(t.options)}}function Gp(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Yo(t,"tokens"),contextWindow:G(t,"contextWindow"),percent:Yo(t,"percent")}}}function Qp(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 vr(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 Jp(e){const t=y(e);return{path:m(t,"path"),entries:j(Zp)(t.entries),scannedAt:m(t,"scannedAt"),truncated:T(t,"truncated")}}function Zp(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",we(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function Qo(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",eh(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:G(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:T(t,"truncated"),binary:T(t,"binary")}}function Sl(e){const t=y(e);return{path:m(t,"path"),size:G(t,"size"),modifiedAt:m(t,"modifiedAt"),created:T(t,"created")}}function Xp(e){const t=y(e);return{path:m(t,"path"),existed:T(t,"existed")}}function Yp(e){const t=y(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:G(t,"size"),modifiedAt:m(t,"modifiedAt")}}function eh(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function th(e){const t=y(e);return{isGitRepo:T(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",we(t,"ahead")),...w("behind",we(t,"behind")),files:j(ih)(t.files)}}function ih(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Jo(t.index),workingTree:Jo(t.workingTree)}}function Jo(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 sh(e){const t=y(e);return{...w("path",$(t,"path")),staged:T(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:T(t,"truncated")}}function Us(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:T(t,"exited"),...w("exitCode",we(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function ci(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:rh(t.status),...w("exitCode",we(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:oh(t.metadata,"metadata")}}function rh(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function oh(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function nh(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:T(t,"hasSessionActivity"),hasTerminalActivity:T(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ah(e){const t=y(e);return{workspaces:j(nh)(t.workspaces),generatedAt:m(t,"generatedAt")}}function lh(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function ch(e){const t=y(e);return{packages:j(xl)(t.packages)}}function Bs(e){const t=y(e),i=$(t,"source"),s=t.scope===void 0?void 0:kl(t.scope),r=qr(t.removed,"removed");return{action:dh(t.action),...w("source",i),...w("scope",s),...w("removed",r),packages:j(xl)(t.packages)}}function xl(e){const t=y(e);return{source:m(t,"source"),scope:kl(t.scope),filtered:T(t,"filtered"),...w("installedPath",$(t,"installedPath"))}}function kl(e){if(e!=="user"&&e!=="project")throw new Error("Invalid Pi package scope");return e}function dh(e){if(e!=="install"&&e!=="remove"&&e!=="update")throw new Error("Invalid Pi package mutation action");return e}function Zo(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:j($l)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...ph(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function $l(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function ph(e){return e===void 0?{}:{session:mr(e)}}function St(e){return{accepted:pt(e,"accepted")}}function hh(e){const t=y(e);return j(uh)(t.attachments)}function uh(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:G(t,"size")}}function br(e){return{closed:pt(e,"closed")}}function fh(e){return{aborted:pt(e,"aborted")}}function gh(e){return{stopped:pt(e,"stopped")}}function Xo(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:jt(t.sessionIds,"sessionIds"),s=we(t,"archivedCount"),r=we(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function mh(e){return{restored:pt(e,"restored")}}function vh(e){return{deleted:pt(e,"deleted")}}function bh(e){return{detached:pt(e,"detached")}}function wh(e){return{reloaded:pt(e,"reloaded")}}function Yo(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 yh(e){return typeof e=="string"?e:e.id}function Sh(e){return typeof e=="string"?void 0:e.cwd}function xh(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function kh(e,t,i="local"){const s=new URLSearchParams,r=Sh(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(yh(e))}/messages${o===""?"":`?${o}`}`}function $h(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Ph(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function Ch(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Pl(e){return typeof e=="string"?e:e.id}function Hr(e){return typeof e=="string"?void 0:e.cwd}function Cl(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(Pl(e))}`}function ee(e,t,i="local"){return`${Cl(e,i)}/${t}`}function Pi(e,t,i="local"){return`${ee(e,t,i)}${Rl(e)}`}function Rh(e,t="local"){return`${Cl(e,t)}${Rl(e)}`}function Rl(e){const t=Hr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function se(e,t={}){const i=Hr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function en(e){return JSON.stringify({sessions:e.map(Ih)})}function Ih(e){const t=Pl(e),i=Hr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const Il={piWebStatus:(e="local")=>b(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,lp),piWebRuntime:()=>b("/api/pi-web/runtime",cp)},Ah={machines:()=>b("/api/machines",vp),addMachine:e=>b("/api/machines",ml,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>b(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>b(`/api/machines/${encodeURIComponent(e)}/health`,bp),runtime:e=>b(`/api/machines/${encodeURIComponent(e)}/runtime`,wp)};function tn(e){return e===void 0?"/api/config":`${R(e)}/config`}function Mh(e){return e===void 0?"/api/plugins":`${R(e)}/plugins`}const Ne={config:e=>b(tn(e),No),saveConfig:(e,t)=>b(tn(t),No,{method:"PUT",body:JSON.stringify({config:e})})},Lt={status:()=>b("/api/normal-auth/status",Sp),setup:e=>b("/api/normal-auth/setup",St,{method:"POST",body:JSON.stringify({password:e})}),login:e=>b("/api/normal-auth/login",St,{method:"POST",body:JSON.stringify({password:e})}),changePassword:(e,t)=>b("/api/normal-auth/change-password",St,{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t})})},si={plugins:e=>b(Mh(e),op)};function Ci(e="",t){const i=t===void 0?"/api/pi-packages":`${R(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const ri={packages:e=>b(Ci("",e),ch),install:(e,t)=>{const i={source:e};return b(Ci("install",t),Bs,{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return b(Ci("remove",i),Bs,{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return b(Ci("update",t),Bs,{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},Al={workspaceActivity:(e="local")=>b(`${R(e)}/activity`,ah)},Th={projects:(e="local")=>b(`${R(e)}/projects`,j(Vo)),addProject:(e,t,i,s="local")=>b(`${R(s)}/projects`,Vo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>b(`${R(t)}/projects/${encodeURIComponent(e)}`,br,{method:"DELETE"}),projectDirectories:(e,t="local")=>b(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,j(vr))};function sn(e,t,i,s,r,o="local"){const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,d=a?new Uint8Array(s):new TextEncoder().encode(s);return b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,Sl,{method:"PUT",body:d,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})}const bt={workspaces:(e,t="local")=>b(`${R(t)}/projects/${e}/workspaces`,j($p)),deleteWorkspace:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ci,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Jp),workspaceFile:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Qo),optionalWorkspaceFile:(e,t,i,s="local")=>hl(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}&optional=true`,Qo),createWorkspaceFile:(e,t,i,s="local")=>sn(e,t,i,new Uint8Array,void 0,s),writeWorkspaceFile:sn,deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,Xp,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,Yp,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Go,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>b(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Go,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Cp,{method:"DELETE"}),downloadWorkspaceFile:(e,t,i,s="local")=>Lh(e,t,i,s)},wr={sessions:(e,t="local")=>b(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(mr)),startSession:(e,t="local")=>b(`${R(t)}/sessions`,mr,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>b(`${R(t)}/sessions/cleanup/preview`,bl,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>b(`${R(t)}/sessions/cleanup`,Rp,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/archive`,Ip,{method:"POST",body:en(e)}),deleteArchivedMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/delete-archived`,Ap,{method:"POST",body:en(e)}),messages:(e,t,i="local")=>b(kh(e,t,i),kp),status:(e,t="local")=>b(Pi(e,"status",t),Vt),models:(e,t="local")=>b(Pi(e,"models",t),Op),setModel:(e,t,i,s="local")=>b(ee(e,"model",s),Vt,{method:"POST",body:se(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>b(ee(e,"model/cycle",i),Vt,{method:"POST",body:se(e,{direction:t})}),thinkingLevels:(e,t="local")=>b(Pi(e,"thinking-levels",t),_p),setThinkingLevel:(e,t,i="local")=>b(ee(e,"thinking-level",i),Vt,{method:"POST",body:se(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>b(ee(e,"thinking-level/cycle",t),Vt,{method:"POST",body:se(e)}),commands:(e,t="local")=>b(Pi(e,"commands",t),j(Qp)),prompt:(e,t,i,s="local",r)=>b(ee(e,"prompt",s),St,{method:"POST",body:se(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>b(ee(e,"attachments",i),hh,{method:"POST",body:se(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>b(ee(e,"shell",i),St,{method:"POST",body:se(e,{text:t})}),runCommand:(e,t,i="local")=>b(ee(e,"commands/run",i),Zo,{method:"POST",body:se(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>b(ee(e,"commands/respond",s),Zo,{method:"POST",body:se(e,{requestId:t,value:i})}),abort:(e,t="local")=>b(ee(e,"abort",t),fh,{method:"POST",body:se(e)}),stop:(e,t="local")=>b(ee(e,"stop",t),gh,{method:"POST",body:se(e)}),archive:(e,t="local")=>b(ee(e,"archive",t),Xo,{method:"POST",body:se(e)}),archiveWithDescendants:(e,t="local")=>b(ee(e,"archive-tree",t),Xo,{method:"POST",body:se(e)}),restore:(e,t="local")=>b(ee(e,"restore",t),mh,{method:"POST",body:se(e)}),deleteArchived:(e,t="local")=>b(Rh(e,t),vh,{method:"DELETE"}),detachParent:(e,t="local")=>b(ee(e,"detach-parent",t),bh,{method:"POST",body:se(e)}),reloadSession:(e,t="local")=>b(ee(e,"reload",t),wh,{method:"POST",body:se(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 b(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Np)},saveApiKey:(e,t,i="local")=>b(`${R(i)}/auth/api-key`,St,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>b(`${R(t)}/auth/logout`,St,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>b(`${R(t)}/auth/oauth`,$i,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,$i),respondOAuthFlow:(e,t,i,s="local")=>b(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,$i,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,$i,{method:"POST"})},Ot={terminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Us)),startTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Us,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,br,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,br,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Us,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ci,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>b(`${R(t)}/terminal-command-runs${Dh(e)}`,j(ci)),getCommandRun:(e,t="local")=>Eh(e,t),cancelCommandRun:(e,t="local")=>b(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ci,{method:"POST"})};async function Eh(e,t){return hl(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`,ci)}function Dh(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 Wh(e){if(!Oh(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Lh(e,t,i,s){const r=await fetch(Ch(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Wh(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const d=i.split("/").pop();a.download=d===void 0||d===""?"download":d,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function Oh(e){return typeof e=="object"&&e!==null}const Fh={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?b(`${R(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(vr)):(s.set("cwd",e),b(`${R(i.machineId)}/files?${s.toString()}`,j(vr)))}},_h={gitStatus:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,th),gitDiff:(e,t,i,s="local")=>b(xh(s,e,t,i),sh)},K={...Il,...Ah,...Ne,...Lt,...si,...ri,...Al,...Th,...bt,...wr,...Ot,...Fh,..._h};function jh(e,t="local",i=Br()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=nl(`${Kr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${Vr()}${n}`)}function ok(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Vr()}${Kr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Uh(e="local",t=Br()){const i=nl(`${Kr(e)}/events`,void 0,t);return new WebSocket(`${Vr()}${i}`)}function Kr(e){return`/api/machines/${encodeURIComponent(e)}`}function Vr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const di=".pi-web/uploads";class xs extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Ml extends Error{constructor(t,i){super(Gh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function rn(e){return e?.uploads?.defaultFolder??di}function Bh(e,t){return e?.uploads?.defaultFolder??t}function Gr(e,t){const i=on(e,"upload destination",{allowEmpty:!0}),s=on(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function zh(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((d,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,d(g))};r.open("PUT",$h(e,t,i.path,Hh(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Kh(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(Sl(Tl(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Xh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new xs(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Nh(e,t,i,s={}){const r=s.destinationFolder??di,o=i.map((h,g)=>({index:g,name:h.name,path:Gr(r,h.name),loaded:0,total:h.size,percent:Qr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const d={requested:!1},p=()=>{s.onProgress?.(Vh(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let S=0;S<i.length;S+=1){if(d.requested)throw new xs;a=S;const P=i[S],C=o[S];if(!(P===void 0||C===void 0)){n=zh(e,t,{path:C.path,file:P},{...qh(s),onProgress:X=>{C.total=X.total,C.loaded=Math.min(X.loaded,C.total),C.percent=X.percent,C.lengthComputable=X.lengthComputable,p()}});try{const X=await n.promise;C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,h.push(X),p()}catch(X){if(Jh(X,d))throw X;const ot=Qh(X);C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,C.error=ot,g.push({index:S,name:P.name,path:C.path,error:ot}),p()}finally{n=void 0}}}if(g.length>0)throw new Ml(g,h);return h})(),cancel:()=>{d.requested=!0,n?.cancel()}}}function qh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Hh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Kh(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Qr(e.loaded,i),lengthComputable:e.lengthComputable}}function Vh(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Qr(r,s),done:i}}function Qr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Gh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Qh(e){return e instanceof Error?e.message:String(e)}function Jh(e,t){return t.requested||e instanceof xs}function on(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Zh(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function Zh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Tl(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Xh(e){const t=Yh(e);return eu(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function Yh(e){try{return Tl(e)}catch{return}}function eu(e){return typeof e=="object"&&e!==null}function _i(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function tu(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function dt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function El(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Dl="local";function zs(e,t){return`${e}:${t}`}function oi(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Dl}class iu{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Al}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,su(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),r=f(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=ru(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function su(e){const t={};for(const i of e.workspaces)El(i)&&(t[i.cwd]=i);return t}function ru(e,t){const i={...e};return El(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class ou{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??K,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=nu(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:f(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 r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.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(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}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 r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,f(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,f(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:f(this.getState())}),s=i.filter(o=>o.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 r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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,f(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 r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!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??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",d=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:d}})}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,f(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,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function nu(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 r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function vi(e){return e.replaceAll(":",".")}function au(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function Ns(e,t){const i=au(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ve(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));lu(r,s)}function lu(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function cu(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Gr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:an(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:an(0,i),status:"uploading",startedAt:e.startedAt}}function du(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function pu(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Jr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function hu(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Jr(s),status:"error",error:t,completedAt:i}}function nn(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Jr(s),status:"cancelled",error:i,completedAt:t}}function Jr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function an(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const Ri=vi("core:workspace.files");class uu{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??K,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Nh,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const d=await this.api.workspaceTree(t.id,i.id,a,s);return[a,d.entries]}catch(d){if(ln(d))return;throw d}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:cn(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ve(Ri,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ve(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}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 r=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(ln(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ve(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());qs(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const r=f(this.getState());qs(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,r):await this.api.deleteWorkspaceFile(t.id,i.id,s,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||qs(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ve(Ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let d;try{d=cu({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(d);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(d.id,h)}})}catch(h){return this.failUploadBatch(d.id,h),{batchId:d.id,done:Promise.resolve()}}this.uploadTasks.set(d.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(d.id,h,i)}).catch(async h=>{await this.handleUploadFailure(d.id,h,i)}).finally(()=>{this.uploadTasks.delete(d.id)});return{batchId:d.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(nn(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:cn(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(du(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(pu(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Ml)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(fu(i)){const n=nn(s,this.now());return this.setUploadBatch(n),n}const r=gu(i),o=hu(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function ln(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function fu(e){return e instanceof xs}function gu(e){return e instanceof Error?e.message:String(e)}function cn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qs(e){const t=e.selectedFilePath;return t===void 0?"file":mu(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function mu(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const dn=vi("core:workspace.git");class vu{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 K.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ve(dn,"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"}),ve(dn,"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[r,o]=await Promise.all([K.gitDiff(i.id,s.id,{path:t},f(this.getState())),K.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}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 bu{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await K.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:pn(this.getState().machineActivities,r),machineRuntimes:pn(this.getState().machineRuntimes,r)}),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,..._i()}),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 K.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 K.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:Hs(this.getState().machineStatuses,t.id),machineRuntimes:Hs(this.getState().machineRuntimes,t.id),machineActivities:Hs(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await K.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 K.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(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await K.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(r=>K.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>K.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Hs(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function pn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class wu{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await K.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await K.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await K.closeProject(t,f(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 yr="pi-web:cached-new-sessions:v1",yu="browserCachedNew",Nt="local";function bi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function hn(e,t=Nt,i=bi()){if(e.messageCount!==0||e.archived===!0)return;const s=Zr(i).filter(r=>r.id!==e.id||r.machineId!==t);Xr([Sr(e,t),...s],i)}function Sr(e,t=Nt){return{...e,browserCachedNew:!0,machineId:t}}function un(e,t=Nt,i=bi()){const s=Zr(i).filter(r=>r.id!==e||r.machineId!==t);Xr(s,i)}function Wl(e,t,i=Nt,s=bi()){const r=new Set(t.map(d=>d.id)),o=Zr(s),n=o.filter(d=>d.machineId!==i||!r.has(d.id));return n.length!==o.length&&Xr(n,s),[...n.filter(d=>d.machineId===i&&d.cwd===e),...t]}function Zi(e){return e===void 0?!1:ku(e)&&e.browserCachedNew===!0}function Su(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:Nt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Zr(e=bi()){try{const t=e?.getItem(yr);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>xu(s)):[]}catch{return[]}}function Xr(e,t=bi()){try{e.length===0?t?.removeItem(yr):t?.setItem(yr,JSON.stringify(e))}catch{}}function xu(e){if(!$u(e))return[];const t=Mt(e,"id"),i=Mt(e,"path"),s=Mt(e,"cwd"),r=Mt(e,"created"),o=Mt(e,"modified"),n=Mt(e,"firstMessage"),a=Pu(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const d=Ks(e,"name"),p=Ks(e,"parentSessionPath"),u=Ks(e,"machineId")??Nt;return[{id:t,path:i,cwd:s,...d===void 0?{}:{name:d},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function ku(e){return yu in e}function $u(e){return typeof e=="object"&&e!==null}function Mt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ks(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Pu(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Cu(e){return zu(e.flatMap(Yr)).filter(t=>t.parts.length>0)}function qe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Gt(e,t){const i=Wu(t);return i===void 0?e:{...e,meta:i}}function Ru(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,qe(t,i)]}function Iu(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 Yr(e){if(Mu(e))return[e];if(_(e,"role")==="bashExecution")return[Gt(Fu(e),e)];const t=_u(_(e,"role")),i=ju(Re(e,"content"),e),s=t==="user"?Tu(i):void 0;if(s!==void 0)return s.map(p=>Gt(p,e));const r=Du(e);if(t==="tool")return[Gt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[Gt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],d=Au(e);return d===void 0?a:[...a,Gt(d,e)]}function Au(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return qe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Mu(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Re(e,"parts"))}function Tu(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Eu(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 Eu(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 Du(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Wu(e){const t=Lu(Re(e,"timestamp")),i=Ou(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Lu(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 Ou(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 Fu(e){const t=_(e,"command")??"",i=ji(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Re(e,"output");s!=null&&i.push("",Yi(s));const r=Re(e,"exitCode");r!=null&&i.push("",`exit ${Yi(r)}`),ji(e,"cancelled")===!0&&i.push("","cancelled"),ji(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
+
`)}]}}function _u(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function ju(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=Re(i,"arguments"),a=_(i,"id"),d=o==="read"?Bu(_(n,"path")):void 0;return d!==void 0?[{type:"skillRead",...d,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:wi(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return fn(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?Uu(i.text,t):i):fn(e)}function Uu(e,t){const i=_(t,"toolCallId"),s=Re(t,"content"),r=Re(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:ji(t,"isError")===!0}}function Bu(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 zu(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const d=Nu(a),p=t.length;t.push({role:"tool",parts:[d],...o}),d.toolCallId!==void 0&&i.set(d.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const d=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(d!==void 0&&qu(t,d,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Nu(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 qu(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Xi(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Xi(e){const t=Re(e,"preview");if(!eo(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Ku(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function fn(e){return e==null?[]:typeof e=="object"?[{type:"text",text:wi(e)}]:[{type:"text",text:Yi(e)}]}function wi(e){if(!eo(e))return Yi(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(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(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Hu(n)}`).join(" · ")}function Hu(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 eo(e){return typeof e=="object"&&e!==null}function Re(e,t){return eo(e)?e[t]:void 0}function _(e,t){const i=Re(e,t);return typeof i=="string"?i:void 0}function ji(e,t){const i=Re(e,t);return typeof i=="boolean"?i:void 0}function Ku(e,t){const i=Re(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Yi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Vu="pi-web:prompt-draft:";function es(e){return`${Vu}${e}`}function ks(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ll(e,t=ks()){try{return t?.getItem(es(e))??""}catch{return""}}function ts(e,t,i=ks()){try{t?i?.setItem(es(e),t):i?.removeItem(es(e))}catch{}}function is(e,t=ks()){try{t?.removeItem(es(e))}catch{}}function gn(e,t,i=ks()){const s=Ll(e,i);s!==""&&(ts(t,s,i),is(e,i))}function Gu(e,t){return qe("bash",`${t===!0?`不加入上下文
|
|
6
6
|
|
|
7
|
-
`:""}$ ${e}`)}function
|
|
7
|
+
`:""}$ ${e}`)}function Qu(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,qe("bash",t)];const r=Zu(s.text)?"":`
|
|
8
8
|
|
|
9
|
-
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function
|
|
9
|
+
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Ju(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
|
|
10
10
|
|
|
11
11
|
`)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash 命令失败"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`完整输出:${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
|
|
12
12
|
|
|
13
13
|
${r.join(`
|
|
14
|
-
`)}`}]}]}function
|
|
14
|
+
`)}`}]}]}function Zu(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 Xu(e,t){if(t.type==="message.append")return uf(e,t.message);if(t.type==="assistant.delta")return Ru(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Iu(e,t.text);if(t.type==="tool.start")return rf(e,t);if(t.type==="tool.update")return Fl(e,t.toolCallId,i=>of(i,t));if(t.type==="tool.end")return Ol(e,t.toolCallId,t.toolName,wi(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Gu(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Qu(e,t.chunk);if(t.type==="shell.end")return Ju(e,t);if(t.type==="command.output")return[...e,qe(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,qe("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Yu(e,t.message)}function Yu(e,t){const i=nf(t);if(i!==void 0)return Ol(e,i.toolCallId,i.toolName,wi(i.content),i.text,i.isError,i.content,i.details);const s=Yr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?tf(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>ef(o,n),e)}function ef(e,t){const i=af(e,t);if(i.length>0)return lf(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||hf(s,t)?[...e.slice(0,-1),t]:[...e,t]}function tf(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function sf(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 rf(e,t){const i=t.toolName==="read"?sf(xt(t.args,"path")):void 0;if(i!==void 0)return ff(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||wi(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function of(e,t){const i=Xi(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 Ol(e,t,i,s,r,o,n,a){const d=Fl(e,t,h=>{const g=Xi(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(d!==e)return d;const p=Xi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Fl(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(d=>d.type==="toolExecution"&&d.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function nf(e){if(xt(e,"role")!=="toolResult")return;const t=xt(e,"toolCallId"),i=rs(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:xt(e,"toolName")??"tool",text:_l(i),isError:bf(e,"isError")===!0,content:i,details:rs(e,"details")}}function _l(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(_l).filter(t=>t!=="").join(`
|
|
17
|
+
`);if(typeof e=="object"&&e!==null){const t=xt(e,"text")??xt(e,"content")??xt(e,"output");if(t!==void 0)return t}return""}function af(e,t){const i=ss(t);if(i.length===0)return[];const s=[];let r=i.length;const o=Ul(e)+1;for(let n=e.length-1;n>=o;n--){const a=ss(e[n]);if(a.length===0)continue;const d=r-a.length;if(!(d<0)&&pf(a,i.slice(d,r))&&(s.unshift(n),r=d,r===0))return s}return[]}function lf(e,t,i){const s=cf(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const d=e[a];d!==void 0&&!o.has(a)&&n.push(d)}return n}function cf(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return df(e[r])?[r,...t]:t}function df(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function ss(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function pf(e,t){return e.length===t.length&&e.every((i,s)=>jl(i,t[s]))}function jl(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:mn(e.path)===mn(t.path)||e.name===t.name}function mn(e){return e.replace(/\\/g,"/")}function hf(e,t){return vn(e)===vn(t)}function vn(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
18
18
|
|
|
19
|
-
`)}function
|
|
20
|
-
`))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function
|
|
21
|
-
`)+1,s=e.slice(i),r=
|
|
22
|
-
`))+1;return e.slice(t)}class jl{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,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),Bl(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=Uh(this.session,this.machineId,this.scope);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 Ul(t);Ff(i)&&this.onEvent?.(i)}}class kn{constructor(t="normal"){this.scope=t,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),Bl(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Bh(this.machineId,this.scope);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 Ul(t);jf(i)&&this.onEvent?.(i)}}function Ff(e){const t=ro(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 _f(e){const t=ro(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function jf(e){const t=ro(e);return _f(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function ro(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Ul(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 Bl(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 zl(e){return e?.ok===!0&&Pe(e,we.sessionsPersistedState)}function Nl(e){return{authoritative:zl(e)}}function ql(e,t,i={}){if(e===void 0)return"unknown";const r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?"persisted":r===!1||Zi(e)?"transient":i.authoritative!==!0?"persisted":"unknown"}function He(e,t,i){return e!==void 0&&e.archived!==!0&&ql(e,t,i)==="persisted"}function fi(e,t,i){return e!==void 0&&e.archived!==!0&&ql(e,t,i)==="transient"}function yi(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class $s{constructor(t,i,s=yi()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Uf(t,i,s))this.values.set(r,o)}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 oo(e){return typeof e=="string"&&e!==""?e:void 0}function Uf(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Bf(r))return[];const o=[];for(const n of r.entries){const a=n[0],d=t(n[1]);d!==void 0&&o.push([a,d])}return o}catch{return[]}}function Bf(e){return!zf(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 zf(e){return typeof e=="object"&&e!==null}class Nf{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 qf="pi-web:session-selection:v1";class Hf{constructor(t=yi()){this.sessionIdsByCwd=new $s(qf,oo,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Kf(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Gf(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function Vf(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Gf(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Qf(e,t,i){return Ui(e,[t],i)}function Ui(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Jf(e,t,i){return Bi(e,t,[i])}function Bi(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Qt=100,$n=4;class Zf{constructor(t,i,s,r=new Nf,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.socket=o.socket??new jl,this.api=o.api??K,this.transcripts=o.transcripts??new Tf}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),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();Vf(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(!t)return;const i=f(this.getState()),s=this.createPendingSessionStart(t,i);this.pendingSessionStarts.set(s.tempId,s),this.insertAndSelectPendingSession(s.session);try{const r=await this.api.startSession(t.path,i);await this.resolvePendingSessionStart(s.tempId,r)}catch(r){this.failPendingSessionStart(s.tempId,r)}}preferredSession(t,i,s){return Kf(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){if(gt(t)){this.selectClientPendingStartSession(t,i);return}this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,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:Qt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,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)},f(this.getState()));const[a,d]=await Promise.all([this.api.messages(t,{limit:Qt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(d.isStreaming?t.id:void 0),status:d,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(d),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(Zi(t)&&lg(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:Qt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=this.getState().selectedSession;if(!o||o.archived===!0)return;const n=t.trim(),a=s!==void 0&&s.length>0;if(gt(o)){!a&&n.startsWith("/")?this.enqueuePendingSessionSend(o,{type:"command",text:t}):!a&&xn(t)?this.enqueuePendingSessionSend(o,{type:"shell",text:t}):this.enqueuePendingSessionSend(o,{type:"prompt",text:t,streamingBehavior:i,attachments:s,delivery:r});return}if(!a&&n.startsWith("/"))return this.runCommand(t);if(!a&&xn(t))return this.runShell(t);await this.deliverPromptToSession(o,t,i,s,r,f(this.getState()),{markSending:a})}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Xe(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"shell",text:t});return}await this.deliverShellToSession(i,t,f(this.getState()),{optimisticLine:!0})}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"command",text:t});return}await this.deliverCommandToSession(i,t,f(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(t,i){const s=this.pendingSessionStarts.get(t.id);if(s===void 0||s.discarded){this.setState({error:"The backend session is not ready for queued sends. Copy your message before discarding this failed start."});return}const r={...i,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};s.queuedSends.push(r);const o=this.getState(),n=o.clientQueuedSessionMessages[t.id]??[],a=Gs(t.id,s.queuedSends.length);this.setState({clientQueuedSessionMessages:{...o.clientQueuedSessionMessages,[t.id]:[...n,eg(r)]},sessionActivities:{...o.sessionActivities,[t.id]:a},activity:o.selectedSession?.id===t.id?a:o.activity,error:""})}async flushQueuedPendingSends(t,i,s){for(const r of s){if(!await this.deliverQueuedPendingSend(t,i,r))return;this.dropNextQueuedSessionMessage(t.id)}}async deliverQueuedPendingSend(t,i,s){return s.type==="prompt"?this.deliverPromptToSession(t,s.text,s.streamingBehavior,s.attachments,s.delivery,i,{markSending:!0}):s.type==="shell"?this.deliverShellToSession(t,s.text,i,{optimisticLine:!0}):this.deliverCommandToSession(t,s.text,i,{applyResult:!0})}async deliverPromptToSession(t,i,s,r,o,n,a){const d=r!==void 0&&r.length>0;a.markSending&&this.markSendingPrompt(t.id,!0);try{if(d&&o==="folder"){const u=(await this.api.saveAttachments(t,r,n)).map(g=>_l(g.path,!1)).join(" "),h=i===""?u:`${i}
|
|
19
|
+
`)}function uf(e,t){const i=Yr(t);return i.length===0?e:[...e,...i]}function ff(e,t){const i=e.at(-1);return gf(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function gf(e,t){const i=ss(t);if(t.role!=="skill"||i.length===0)return!1;const s=Ul(e)+1;return i.every(r=>mf(e,r,s))}function mf(e,t,i){for(let s=e.length-1;s>=i;s--)if(ss(e[s]).some(r=>jl(r,t)))return!0;return!1}function Ul(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function vf(e){return typeof e=="object"&&e!==null}function rs(e,t){return vf(e)?e[t]:void 0}function xt(e,t){const i=rs(e,t);return typeof i=="string"?i:void 0}function bf(e,t){const i=rs(e,t);return typeof i=="boolean"?i:void 0}const wf="pi-web:chat-history:v2:",yf=1800*1e3;function Sf(e){try{const t=sessionStorage.getItem(os(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Rf(i))return;if(Date.now()-i.savedAt>yf){sessionStorage.removeItem(os(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function xf(e,t){try{sessionStorage.setItem(os(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function kf(e){try{sessionStorage.removeItem(os(e))}catch{}}function $f(e,t){if(e===void 0||!xr(e))return t;if(!xr(t))return e;if(Pf(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),r=new Array(s-i);return bn(r,i,e),bn(r,i,t),Cf(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Pf(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Cf(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function bn(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function os(e){return`${wf}${e}`}function Rf(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:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&xr({messages:t,start:i,total:s})}function xr(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(If)}function If(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 Af={read:Sf,write:xf,remove:kf};class Mf{constructor(t=Af){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return wn(this.rawHistoryPage(t))}mergeHistory(t,i){const s=$f(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),wn(s)}applyLiveEvent(t,i){return Xu(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 wn(e){const t=e?.start??0;return{messages:Cu(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Bl(e,t=e.length){const i=e.slice(0,t),s=Tf(i,t);if(s!==void 0)return s;const r=Ef(i,t);if(r!==void 0)return r;const o=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
|
|
20
|
+
`))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function zl(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Tf(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 Ef(e,t){const i=e.lastIndexOf(`
|
|
21
|
+
`)+1,s=e.slice(i),r=yn(s,"@ "),o=yn(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",d=i+n,p=d+a.length;return{kind:"file",query:e.slice(p),from:d,to:t,fileScope:"all",allPrefix:a}}function yn(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Df(e[i-1]))return i;return-1}function Df(e){return e===" "||e===" "}function ns(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Lf(e).startsWith("/")?{kind:"command"}:Bl(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Sn(e){return ns(e).kind==="shell"}function Wf(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Lf(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
22
|
+
`))+1;return e.slice(t)}class Nl{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,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),Hl(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=jh(this.session,this.machineId,this.scope);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 ql(t);Of(i)&&this.onEvent?.(i)}}class xn{constructor(t="normal"){this.scope=t,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),Hl(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Uh(this.machineId,this.scope);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 ql(t);_f(i)&&this.onEvent?.(i)}}function Of(e){const t=to(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 Ff(e){const t=to(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function _f(e){const t=to(e);return Ff(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function to(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function ql(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 Hl(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 Kl(e){return e?.ok===!0&&Pe(e,be.sessionsPersistedState)}function Vl(e){return{authoritative:Kl(e)}}function Gl(e,t,i={}){if(e===void 0)return"unknown";const r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?"persisted":r===!1||Zi(e)?"transient":i.authoritative!==!0?"persisted":"unknown"}function He(e,t,i){return e!==void 0&&e.archived!==!0&&Gl(e,t,i)==="persisted"}function fi(e,t,i){return e!==void 0&&e.archived!==!0&&Gl(e,t,i)==="transient"}function yi(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class $s{constructor(t,i,s=yi()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of jf(t,i,s))this.values.set(r,o)}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 io(e){return typeof e=="string"&&e!==""?e:void 0}function jf(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Uf(r))return[];const o=[];for(const n of r.entries){const a=n[0],d=t(n[1]);d!==void 0&&o.push([a,d])}return o}catch{return[]}}function Uf(e){return!Bf(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 Bf(e){return typeof e=="object"&&e!==null}class zf{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 Nf="pi-web:session-selection:v1";class qf{constructor(t=yi()){this.sessionIdsByCwd=new $s(Nf,io,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Hf(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Vf(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function Kf(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Vf(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Gf(e,t,i){return Ui(e,[t],i)}function Ui(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Qf(e,t,i){return Bi(e,t,[i])}function Bi(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Qt=100,kn=4;class Jf{constructor(t,i,s,r=new zf,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.socket=o.socket??new Nl,this.api=o.api??K,this.transcripts=o.transcripts??new Mf}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),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();Kf(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(!t)return;const i=f(this.getState()),s=this.createPendingSessionStart(t,i);this.pendingSessionStarts.set(s.tempId,s),this.insertAndSelectPendingSession(s.session);try{const r=await this.api.startSession(t.path,i);await this.resolvePendingSessionStart(s.tempId,r)}catch(r){this.failPendingSessionStart(s.tempId,r)}}preferredSession(t,i,s){return Hf(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){if(gt(t)){this.selectClientPendingStartSession(t,i);return}this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,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:Qt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,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)},f(this.getState()));const[a,d]=await Promise.all([this.api.messages(t,{limit:Qt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(d.isStreaming?t.id:void 0),status:d,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(d),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(Zi(t)&&ag(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:Qt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=this.getState().selectedSession;if(!o||o.archived===!0)return;const n=t.trim(),a=s!==void 0&&s.length>0;if(gt(o)){!a&&n.startsWith("/")?this.enqueuePendingSessionSend(o,{type:"command",text:t}):!a&&Sn(t)?this.enqueuePendingSessionSend(o,{type:"shell",text:t}):this.enqueuePendingSessionSend(o,{type:"prompt",text:t,streamingBehavior:i,attachments:s,delivery:r});return}if(!a&&n.startsWith("/"))return this.runCommand(t);if(!a&&Sn(t))return this.runShell(t);await this.deliverPromptToSession(o,t,i,s,r,f(this.getState()),{markSending:a})}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Xe(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"shell",text:t});return}await this.deliverShellToSession(i,t,f(this.getState()),{optimisticLine:!0})}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"command",text:t});return}await this.deliverCommandToSession(i,t,f(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(t,i){const s=this.pendingSessionStarts.get(t.id);if(s===void 0||s.discarded){this.setState({error:"The backend session is not ready for queued sends. Copy your message before discarding this failed start."});return}const r={...i,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};s.queuedSends.push(r);const o=this.getState(),n=o.clientQueuedSessionMessages[t.id]??[],a=Gs(t.id,s.queuedSends.length);this.setState({clientQueuedSessionMessages:{...o.clientQueuedSessionMessages,[t.id]:[...n,Yf(r)]},sessionActivities:{...o.sessionActivities,[t.id]:a},activity:o.selectedSession?.id===t.id?a:o.activity,error:""})}async flushQueuedPendingSends(t,i,s){for(const r of s){if(!await this.deliverQueuedPendingSend(t,i,r))return;this.dropNextQueuedSessionMessage(t.id)}}async deliverQueuedPendingSend(t,i,s){return s.type==="prompt"?this.deliverPromptToSession(t,s.text,s.streamingBehavior,s.attachments,s.delivery,i,{markSending:!0}):s.type==="shell"?this.deliverShellToSession(t,s.text,i,{optimisticLine:!0}):this.deliverCommandToSession(t,s.text,i,{applyResult:!0})}async deliverPromptToSession(t,i,s,r,o,n,a){const d=r!==void 0&&r.length>0;a.markSending&&this.markSendingPrompt(t.id,!0);try{if(d&&o==="folder"){const u=(await this.api.saveAttachments(t,r,n)).map(g=>zl(g.path,!1)).join(" "),h=i===""?u:`${i}
|
|
23
23
|
|
|
24
|
-
${u}`;await this.api.prompt(t,h,s,n)}else await this.api.prompt(t,i,s,n,r);return this.markCachedNewSessionPersisted(t),!0}catch(p){return this.setState({error:String(p)}),!1}finally{a.markSending&&this.markSendingPrompt(t.id,!1)}}async deliverShellToSession(t,i,s,r){r.optimisticLine&&this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("user",i)]});try{return await this.api.shell(t,i,s),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}}async deliverCommandToSession(t,i,s,r){this.markSendingPrompt(t.id,!0);try{const o=await this.api.runCommand(t,i,s);return r.applyResult&&this.getState().selectedSession?.id===t.id?this.applyCommandResult(o):o.type==="select"&&this.setState({error:`Queued command “${i}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}finally{this.markSendingPrompt(t.id,!1)}}dropNextQueuedSessionMessage(t){const i=this.getState(),s=i.clientQueuedSessionMessages[t]??[];if(s.length===0)return;const r=s.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Xe(i.clientQueuedSessionMessages,t):{...i.clientQueuedSessionMessages,[t]:r}})}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,f(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(!t)return;const i=this.statusForSession(t),s=this.sessionPersistenceOptions();if(fi(t,i,s)){await this.deleteCachedNewSession(t);return}if(He(t,i,s))try{await this.api.archive(t,f(this.getState()));const r=this.getState(),o=Qf(r.sessions,t.id,new Date().toISOString()),n=Jf(o,r.selectedSession?.id,t.id);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(r){this.setState({error:String(r)})}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(t===void 0||!He(t,this.statusForSession(t),this.sessionPersistenceOptions())))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Ui(r.sessions,s,new Date().toISOString()),n=Bi(o,r.selectedSession?.id,s);this.setState({sessions:o}),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=this.sessionPersistenceOptions(),s=Rn(t).filter(r=>He(r,this.statusForSession(r),i));if(s.length!==0)try{const r=f(this.getState()),{succeededIds:o,failures:n,generatedAt:a}=await this.archiveSessionBatch(s,r);if(o.length>0){const d=this.getState(),p=Ui(d.sessions,o,a??new Date().toISOString()),u=Bi(p,d.selectedSession?.id,o);this.setState({sessions:p}),u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",n)}catch(r){this.setState({error:`Archive failed: ${zi(r)}`})}}async deleteArchivedSessions(t){const i=Rn(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok===!0&&!Pe(r,we.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),d=this.getState(),p=d.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),d.selectedSession!==void 0&&a.has(d.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${zi(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,we.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:An(o.failures),generatedAt:o.generatedAt}}const r=await Tn(t,$n,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:In(r),failures:Mn(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,we.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:An(o.failures)}}const r=await Tn(t,$n,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:In(r),failures:Mn(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],d=Ui(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:d,sessionStatuses:Pn(o.sessionStatuses,a),sessionActivities:Pn(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=d.find(h=>h.archived!==!0)??d[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Bi(d,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ml(i.path,await this.api.sessions(i.path,t),t).filter(d=>!this.isSuppressedCreatedSession(d,t));if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.mergePendingStartSessions(i.path,s,t),o=this.getState().selectedSession;if(this.setState({sessions:r}),o===void 0)return;const n=r.find(d=>d.id===o.id);if(n!==void 0){n!==o&&this.setState({selectedSession:n});return}const a=r.find(d=>d.archived!==!0)??r[0];a!==void 0?await this.selectSession(a):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(t===void 0||!fi(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=gt(t)?this.pendingSessionStarts.get(t.id):void 0;i!==void 0?(i.discarded=!0,i.queuedSends=[]):this.api.stop(t,f(this.getState())).catch(()=>{}),fn(t.id,f(this.getState())),is(this.sessionCacheKey(t.id));const s=this.getState(),r=s.sessions.filter(n=>n.id!==t.id);if(this.setState({sessions:r,sessionStatuses:Xe(s.sessionStatuses,t.id),sessionActivities:Vs(s.sessionActivities,t.id),sendingPrompts:Xe(s.sendingPrompts,t.id),clientQueuedSessionMessages:Xe(s.clientQueuedSessionMessages,t.id)}),this.getState().selectedSession?.id!==t.id)return;const o=r.find(n=>n.archived!==!0)??r[0];o!==void 0?await this.selectSession(o):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(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||!He(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Pe(s,we.sessionsReload)){this.setState({error:"Reloading sessions from disk 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(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(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,f(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,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(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,f(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,f(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,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(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||gt(i)))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Qt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return oi(f(this.getState()),t)}statusForSession(t){if(t===void 0)return;const i=this.getState();return i.status?.sessionId===t.id&&i.selectedSession?.id===t.id?i.status:i.sessionStatuses[t.id]}sessionPersistenceOptions(){const t=this.getState();return Nl(t.machineRuntimes[f(t)])}workspaceSelectionKey(t){return`${f(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})}createPendingSessionStart(t,i){const s=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),o={id:s,path:`pi-web://pending-session/${s}`,cwd:t.path,persisted:!1,name:"New session",created:r,modified:r,messageCount:0,firstMessage:"",clientPendingStart:!0,machineId:i};return{tempId:s,workspaceId:t.id,cwd:t.path,machineId:i,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(t){const i=this.getState();this.selectClientPendingStartSession(t,{activity:Gs(t.id),sessions:[t,...i.sessions.filter(s=>s.id!==t.id)]})}selectClientPendingStartSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)}),this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const s=this.getState(),r=this.pendingSessionStarts.get(t.id),o=i?.activity??s.sessionActivities[t.id]??(r!==void 0?Gs(t.id,r.queuedSends.length):void 0);this.setState({...i?.sessions===void 0?{}:{sessions:i.sessions},selectedSession:t,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:o,availableThinkingLevels:[],...o===void 0?{}:{sessionActivities:{...s.sessionActivities,[t.id]:o}},error:""}),i?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=s.queuedSends.splice(0),o=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId,i.id);if(s.discarded){is(oi(s.machineId,t)),this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),this.applyReleasedCreatedSessions(o,s.machineId),this.api.stop(i,s.machineId).catch(()=>{});return}un(i,s.machineId),mn(oi(s.machineId,t),oi(s.machineId,i.id));const n=xr(i,s.machineId);if(!this.isCurrentPendingStart(s)){this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),await this.flushQueuedPendingSends(n,s.machineId,r);return}const a=this.getState(),d=a.selectedSession?.id===t;this.setState({sessions:Xf(a.sessions,t,n),sessionActivities:Vs(a.sessionActivities,t),sendingPrompts:Cn(a.sendingPrompts,t,n.id),clientQueuedSessionMessages:Cn(a.clientQueuedSessionMessages,t,n.id),...d?{selectedSession:n,status:a.sessionStatuses[n.id],activity:a.sessionActivities[n.id]}:{},error:""}),this.applyReleasedCreatedSessions(o,s.machineId),d&&(this.updateUrl({replace:!0}),await this.selectSession(n,{updateUrl:!1})),await this.flushQueuedPendingSends(n,s.machineId,r)}failPendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId),o=this.isCurrentPendingStart(s);if(s.discarded||!o){o&&this.applyReleasedCreatedSessions(r,s.machineId);return}const n=this.getState(),a=zi(i),d=Yf(t,a,s.queuedSends.length),p=n.sessions.some(u=>u.id===t);this.setState({sessions:p?n.sessions:[s.session,...n.sessions],sessionActivities:{...n.sessionActivities,[t]:d},activity:n.selectedSession?.id===t?d:n.activity,error:`Failed to start session: ${a}`}),this.applyReleasedCreatedSessions(r,s.machineId)}isCurrentPendingStart(t){const i=this.getState();return f(i)===t.machineId&&i.selectedWorkspace?.id===t.workspaceId}hasPendingStartFor(t,i){return Array.from(this.pendingSessionStarts.values()).some(s=>s.cwd===t&&s.machineId===i)}isSuppressedCreatedSession(t,i){const s=this.suppressedCreatedSessions.get(t.id);return s?.session.cwd===t.cwd&&s.machineId===i}takeSuppressedCreatedSessionsFor(t,i,s){if(s!==void 0&&this.suppressedCreatedSessions.delete(s),this.hasPendingStartFor(t,i))return[];const r=[];for(const[o,n]of this.suppressedCreatedSessions)n.session.cwd!==t||n.machineId!==i||(this.suppressedCreatedSessions.delete(o),r.push(n.session));return r}applyReleasedCreatedSessions(t,i){if(t.length===0||f(this.getState())!==i)return;const s=this.getState();if(s.selectedWorkspace===void 0)return;const r=new Set(s.sessions.map(n=>n.id)),o=t.filter(n=>n.cwd===s.selectedWorkspace?.path&&!r.has(n.id));o.length!==0&&this.setState({sessions:[...o.reverse(),...s.sessions]})}mergePendingStartSessions(t,i,s){const r=this.getState().sessions.filter(n=>gt(n)&&n.cwd===t&&n.machineId===s);if(r.length===0)return i;const o=new Set(r.map(n=>n.id));return[...r,...i.filter(n=>!o.has(n.id))]}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),r=await this.api.startSession(t.cwd,s);un(r,s),mn(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),fn(t.id,s);const o=xr(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Zi(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(xu(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,qe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ts(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();if(i.selectedWorkspace?.path!==t.cwd||i.sessions.some(r=>r.id===t.id))return;const s=f(i);if(this.hasPendingStartFor(t.cwd,s)){this.suppressedCreatedSessions.set(t.id,{session:t,machineId:s});return}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"&&!dt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...og(i,t.sessionId,t.messageCount),...s?{sessionActivities:Vs(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=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}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(ng(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(ag(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){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})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=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:Qt},f(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 Vs(e,t){return Xe(e,t)}function Xe(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Pn(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function Cn(e,t,i){if(t===i||!(t in e))return e;const s=e[t];return s===void 0?e:{...Xe(e,t),[i]:s}}function Xf(e,t,i){const s=[];let r=!1;for(const o of e){if(o.id===t){r||(s.push(i),r=!0);continue}o.id!==i.id&&s.push(o)}return r?s:[i,...s]}function gt(e){return e!==void 0&&"clientPendingStart"in e&&e.clientPendingStart===!0}function Gs(e,t=0){return{sessionId:e,phase:"active",label:"Creating session",detail:t>0?`${String(t)} queued ${t===1?"message":"messages"} will send when the backend session is ready`:"Waiting for the backend session to be ready",at:new Date().toISOString()}}function Yf(e,t,i=0){const s=i>0?` · ${String(i)} queued ${i===1?"message":"messages"} kept below`:"";return{sessionId:e,phase:"error",label:"Session creation failed",detail:`${t}${s}`,at:new Date().toISOString()}}function eg(e){return e.type==="prompt"?{kind:e.streamingBehavior==="steer"?"steer":"followUp",text:tg(e.text,e.attachments)}:{kind:"followUp",text:e.text}}function tg(e,t){const i=ig(t);return i===void 0?e:e.trim()===""?i:`${e}
|
|
24
|
+
${u}`;await this.api.prompt(t,h,s,n)}else await this.api.prompt(t,i,s,n,r);return this.markCachedNewSessionPersisted(t),!0}catch(p){return this.setState({error:String(p)}),!1}finally{a.markSending&&this.markSendingPrompt(t.id,!1)}}async deliverShellToSession(t,i,s,r){r.optimisticLine&&this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("user",i)]});try{return await this.api.shell(t,i,s),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}}async deliverCommandToSession(t,i,s,r){this.markSendingPrompt(t.id,!0);try{const o=await this.api.runCommand(t,i,s);return r.applyResult&&this.getState().selectedSession?.id===t.id?this.applyCommandResult(o):o.type==="select"&&this.setState({error:`Queued command “${i}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}finally{this.markSendingPrompt(t.id,!1)}}dropNextQueuedSessionMessage(t){const i=this.getState(),s=i.clientQueuedSessionMessages[t]??[];if(s.length===0)return;const r=s.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Xe(i.clientQueuedSessionMessages,t):{...i.clientQueuedSessionMessages,[t]:r}})}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,f(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(!t)return;const i=this.statusForSession(t),s=this.sessionPersistenceOptions();if(fi(t,i,s)){await this.deleteCachedNewSession(t);return}if(He(t,i,s))try{await this.api.archive(t,f(this.getState()));const r=this.getState(),o=Gf(r.sessions,t.id,new Date().toISOString()),n=Qf(o,r.selectedSession?.id,t.id);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(r){this.setState({error:String(r)})}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(t===void 0||!He(t,this.statusForSession(t),this.sessionPersistenceOptions())))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Ui(r.sessions,s,new Date().toISOString()),n=Bi(o,r.selectedSession?.id,s);this.setState({sessions:o}),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=this.sessionPersistenceOptions(),s=Cn(t).filter(r=>He(r,this.statusForSession(r),i));if(s.length!==0)try{const r=f(this.getState()),{succeededIds:o,failures:n,generatedAt:a}=await this.archiveSessionBatch(s,r);if(o.length>0){const d=this.getState(),p=Ui(d.sessions,o,a??new Date().toISOString()),u=Bi(p,d.selectedSession?.id,o);this.setState({sessions:p}),u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",n)}catch(r){this.setState({error:`Archive failed: ${zi(r)}`})}}async deleteArchivedSessions(t){const i=Cn(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok===!0&&!Pe(r,be.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),d=this.getState(),p=d.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),d.selectedSession!==void 0&&a.has(d.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${zi(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,be.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:In(o.failures),generatedAt:o.generatedAt}}const r=await Mn(t,kn,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:Rn(r),failures:An(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,be.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:In(o.failures)}}const r=await Mn(t,kn,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:Rn(r),failures:An(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],d=Ui(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:d,sessionStatuses:$n(o.sessionStatuses,a),sessionActivities:$n(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=d.find(h=>h.archived!==!0)??d[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Bi(d,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Wl(i.path,await this.api.sessions(i.path,t),t).filter(d=>!this.isSuppressedCreatedSession(d,t));if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.mergePendingStartSessions(i.path,s,t),o=this.getState().selectedSession;if(this.setState({sessions:r}),o===void 0)return;const n=r.find(d=>d.id===o.id);if(n!==void 0){n!==o&&this.setState({selectedSession:n});return}const a=r.find(d=>d.archived!==!0)??r[0];a!==void 0?await this.selectSession(a):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(t===void 0||!fi(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=gt(t)?this.pendingSessionStarts.get(t.id):void 0;i!==void 0?(i.discarded=!0,i.queuedSends=[]):this.api.stop(t,f(this.getState())).catch(()=>{}),un(t.id,f(this.getState())),is(this.sessionCacheKey(t.id));const s=this.getState(),r=s.sessions.filter(n=>n.id!==t.id);if(this.setState({sessions:r,sessionStatuses:Xe(s.sessionStatuses,t.id),sessionActivities:Vs(s.sessionActivities,t.id),sendingPrompts:Xe(s.sendingPrompts,t.id),clientQueuedSessionMessages:Xe(s.clientQueuedSessionMessages,t.id)}),this.getState().selectedSession?.id!==t.id)return;const o=r.find(n=>n.archived!==!0)??r[0];o!==void 0?await this.selectSession(o):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(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||!He(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Pe(s,be.sessionsReload)){this.setState({error:"Reloading sessions from disk 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(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(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,f(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,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(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,f(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,f(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,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(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||gt(i)))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Qt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return oi(f(this.getState()),t)}statusForSession(t){if(t===void 0)return;const i=this.getState();return i.status?.sessionId===t.id&&i.selectedSession?.id===t.id?i.status:i.sessionStatuses[t.id]}sessionPersistenceOptions(){const t=this.getState();return Vl(t.machineRuntimes[f(t)])}workspaceSelectionKey(t){return`${f(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})}createPendingSessionStart(t,i){const s=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),o={id:s,path:`pi-web://pending-session/${s}`,cwd:t.path,persisted:!1,name:"New session",created:r,modified:r,messageCount:0,firstMessage:"",clientPendingStart:!0,machineId:i};return{tempId:s,workspaceId:t.id,cwd:t.path,machineId:i,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(t){const i=this.getState();this.selectClientPendingStartSession(t,{activity:Gs(t.id),sessions:[t,...i.sessions.filter(s=>s.id!==t.id)]})}selectClientPendingStartSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)}),this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const s=this.getState(),r=this.pendingSessionStarts.get(t.id),o=i?.activity??s.sessionActivities[t.id]??(r!==void 0?Gs(t.id,r.queuedSends.length):void 0);this.setState({...i?.sessions===void 0?{}:{sessions:i.sessions},selectedSession:t,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:o,availableThinkingLevels:[],...o===void 0?{}:{sessionActivities:{...s.sessionActivities,[t.id]:o}},error:""}),i?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=s.queuedSends.splice(0),o=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId,i.id);if(s.discarded){is(oi(s.machineId,t)),this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),this.applyReleasedCreatedSessions(o,s.machineId),this.api.stop(i,s.machineId).catch(()=>{});return}hn(i,s.machineId),gn(oi(s.machineId,t),oi(s.machineId,i.id));const n=Sr(i,s.machineId);if(!this.isCurrentPendingStart(s)){this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),await this.flushQueuedPendingSends(n,s.machineId,r);return}const a=this.getState(),d=a.selectedSession?.id===t;this.setState({sessions:Zf(a.sessions,t,n),sessionActivities:Vs(a.sessionActivities,t),sendingPrompts:Pn(a.sendingPrompts,t,n.id),clientQueuedSessionMessages:Pn(a.clientQueuedSessionMessages,t,n.id),...d?{selectedSession:n,status:a.sessionStatuses[n.id],activity:a.sessionActivities[n.id]}:{},error:""}),this.applyReleasedCreatedSessions(o,s.machineId),d&&(this.updateUrl({replace:!0}),await this.selectSession(n,{updateUrl:!1})),await this.flushQueuedPendingSends(n,s.machineId,r)}failPendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId),o=this.isCurrentPendingStart(s);if(s.discarded||!o){o&&this.applyReleasedCreatedSessions(r,s.machineId);return}const n=this.getState(),a=zi(i),d=Xf(t,a,s.queuedSends.length),p=n.sessions.some(u=>u.id===t);this.setState({sessions:p?n.sessions:[s.session,...n.sessions],sessionActivities:{...n.sessionActivities,[t]:d},activity:n.selectedSession?.id===t?d:n.activity,error:`Failed to start session: ${a}`}),this.applyReleasedCreatedSessions(r,s.machineId)}isCurrentPendingStart(t){const i=this.getState();return f(i)===t.machineId&&i.selectedWorkspace?.id===t.workspaceId}hasPendingStartFor(t,i){return Array.from(this.pendingSessionStarts.values()).some(s=>s.cwd===t&&s.machineId===i)}isSuppressedCreatedSession(t,i){const s=this.suppressedCreatedSessions.get(t.id);return s?.session.cwd===t.cwd&&s.machineId===i}takeSuppressedCreatedSessionsFor(t,i,s){if(s!==void 0&&this.suppressedCreatedSessions.delete(s),this.hasPendingStartFor(t,i))return[];const r=[];for(const[o,n]of this.suppressedCreatedSessions)n.session.cwd!==t||n.machineId!==i||(this.suppressedCreatedSessions.delete(o),r.push(n.session));return r}applyReleasedCreatedSessions(t,i){if(t.length===0||f(this.getState())!==i)return;const s=this.getState();if(s.selectedWorkspace===void 0)return;const r=new Set(s.sessions.map(n=>n.id)),o=t.filter(n=>n.cwd===s.selectedWorkspace?.path&&!r.has(n.id));o.length!==0&&this.setState({sessions:[...o.reverse(),...s.sessions]})}mergePendingStartSessions(t,i,s){const r=this.getState().sessions.filter(n=>gt(n)&&n.cwd===t&&n.machineId===s);if(r.length===0)return i;const o=new Set(r.map(n=>n.id));return[...r,...i.filter(n=>!o.has(n.id))]}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),r=await this.api.startSession(t.cwd,s);hn(r,s),gn(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),un(t.id,s);const o=Sr(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Zi(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Su(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,qe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ts(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();if(i.selectedWorkspace?.path!==t.cwd||i.sessions.some(r=>r.id===t.id))return;const s=f(i);if(this.hasPendingStartFor(t.cwd,s)){this.suppressedCreatedSessions.set(t.id,{session:t,machineId:s});return}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"&&!dt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...rg(i,t.sessionId,t.messageCount),...s?{sessionActivities:Vs(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=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}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(og(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(ng(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){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})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=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:Qt},f(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 Vs(e,t){return Xe(e,t)}function Xe(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function $n(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function Pn(e,t,i){if(t===i||!(t in e))return e;const s=e[t];return s===void 0?e:{...Xe(e,t),[i]:s}}function Zf(e,t,i){const s=[];let r=!1;for(const o of e){if(o.id===t){r||(s.push(i),r=!0);continue}o.id!==i.id&&s.push(o)}return r?s:[i,...s]}function gt(e){return e!==void 0&&"clientPendingStart"in e&&e.clientPendingStart===!0}function Gs(e,t=0){return{sessionId:e,phase:"active",label:"Creating session",detail:t>0?`${String(t)} queued ${t===1?"message":"messages"} will send when the backend session is ready`:"Waiting for the backend session to be ready",at:new Date().toISOString()}}function Xf(e,t,i=0){const s=i>0?` · ${String(i)} queued ${i===1?"message":"messages"} kept below`:"";return{sessionId:e,phase:"error",label:"Session creation failed",detail:`${t}${s}`,at:new Date().toISOString()}}function Yf(e){return e.type==="prompt"?{kind:e.streamingBehavior==="steer"?"steer":"followUp",text:eg(e.text,e.attachments)}:{kind:"followUp",text:e.text}}function eg(e,t){const i=tg(t);return i===void 0?e:e.trim()===""?i:`${e}
|
|
25
25
|
|
|
26
|
-
${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?.trim()).filter(n=>n!==void 0&&n!==""),i=e.length,s=`${String(i)} ${i===1?"attachment":"attachments"}`;if(t.length===0)return`[${s} queued]`;const r=t.slice(0,3).join(", "),o=t.length>3?`, +${String(t.length-3)} more`:"";return`[${s} queued: ${r}${o}]`}function Rn(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 In(e){return e.filter(sg).map(t=>t.value)}function An(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function Mn(e,t){return t.flatMap((i,s)=>rg(i)?[`${e[s]?.id??"unknown"}: ${zi(i.reason)}`]:[])}async function Tn(e,t,i){const s=e.map((d,p)=>({item:d,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const d=s[o];if(d===void 0)return;o+=1;try{r[d.index]={status:"fulfilled",value:await i(d.item)}}catch(p){r[d.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function sg(e){return e.status==="fulfilled"}function rg(e){return e.status==="rejected"}function zi(e){return e instanceof Error?e.message:String(e)}function og(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function ng(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 ag(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function lg(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class cg{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 dg="pi-web:workspace-selection:v1";class pg{constructor(t=yi()){this.workspaceIdsByProject=new $s(dg,oo,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function hg(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class ug{constructor(t,i,s,r,o=new cg,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??K}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,..._i()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(zs(f(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=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,..._i()});try{const r=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=hg(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(zs(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:zs(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,..._i()});try{const r=Ml(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=gg(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function fg(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function gg(e){return e.find(t=>t.isMain)??e[0]}const mg="pi-web:machine-navigation:v1";class vg{constructor(t=yi()){this.snapshotsByMachine=new $s(mg,wg,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Wn(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Wn(t))}forget(t){this.snapshotsByMachine.delete(t)}}function bg(e){return{machineId:e,surface:{}}}function En(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Al,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 Dn(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 Wn(e){return{...e,surface:{...e.surface}}}function wg(e){if(!Kl(e))return;const t=Ye(e,"machineId");if(t===void 0)return;const i=Hl(Ye(e,"tool")),s=Sg(Ye(e,"view"));return{machineId:t,projectId:Ye(e,"projectId"),workspaceId:Ye(e,"workspaceId"),sessionId:Ye(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:yg(e.surface)}}function yg(e){return Kl(e)?{selectedFilePath:Ye(e,"selectedFilePath"),selectedDiffPath:Ye(e,"selectedDiffPath"),selectedTerminalId:Ye(e,"selectedTerminalId")}:{}}function Sg(e){return e==="navigation"||e==="chat"?e:Hl(e)}function Hl(e){return xg(e)?e:void 0}function xg(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ye(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Kl(e){return typeof e=="object"&&e!==null}const kg="pi-web:terminal-selection:v1";class $g{constructor(t=yi()){this.terminalIdsByCwd=new $s(kg,oo,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 dk(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function pk(e){return e.find(t=>!t.exited)??e[0]}const Vl=1200,Pg=["mod","alt","shift"];class Cg{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Ql(t);if(r===void 0)return!1;const o=no(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,r],o))return!0;if(this.clearPending(),!gi(r))return!1}else if(!gi(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Og(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>ao(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Vl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function no(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Rg(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort($r)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Mg),a=new Map,d=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Tg(u,n)??u;d.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=d.get(p),h=u===p,g=u===void 0||h?void 0:Ln(u),S=h?[...a.get(p)??[]].sort($r).map(Ln):[];return{...p,active:h,shadows:S,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function Qs(e){return Jl(e,{requireFirstChordActivator:!0})}function Gl(e){const t=Jl(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Ni(e){return Gl(e).map(t=>t.split("+").map(Xl).join("+")).join(" ")}function Ql(e){if(e.isComposing)return;const t=Wg(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 gi(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Rg(e,t,i){const s=Ig(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=Gl(r),n=o[0];if(!(n===void 0||!gi(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:Ag(o),order:i}}function Ig(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Ag(e){return e.join("\0")}function Ln(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function $r(e,t){return On(e.source)-On(t.source)||Fn(e.action.id,t.action.id)||Fn(e.action.title,t.action.title)||e.order-t.order}function Mg(e,t){return e.tokens.length-t.tokens.length||$r(e,t)}function Tg(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&ao(e.tokens,i.tokens))}function On(e){switch(e){case"custom":return 0;case"default":return 1}}function Fn(e,t){return e<t?-1:e>t?1:0}function Jl(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=Eg(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!gi(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Eg(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Dg(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${Xl(n)} 修饰键。`};i.add(n);continue}const a=Zl(o);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${o}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...Pg.filter(o=>i.has(o)),s].join("+")}}function Dg(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 Zl(e){const t=Lg(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 Wg(e){if(e===" ")return"space";const t=e.toLowerCase();return Zl(t)}function Lg(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 Xl(e){return e==="mod"?_n()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?_n()?"⌥":"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 Og(e,t){return e.length===t.length&&ao(e,t)}function ao(e,t){return t.every((i,s)=>e[s]===i)}function _n(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Fg={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function ni(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=Bn(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=Bn(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Ut(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function jn(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=ni(e.draft);return!t.ok||Ut(t.request)!==Ut(e.previewRequest)?!1:qi(e.preview)}function qi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Yl(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function Un(e,t){const i=new Set(Yl(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function _g(e,t){return t(jg(e))}function jg(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
|
|
26
|
+
${i}`}function tg(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?.trim()).filter(n=>n!==void 0&&n!==""),i=e.length,s=`${String(i)} ${i===1?"attachment":"attachments"}`;if(t.length===0)return`[${s} queued]`;const r=t.slice(0,3).join(", "),o=t.length>3?`, +${String(t.length-3)} more`:"";return`[${s} queued: ${r}${o}]`}function Cn(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 Rn(e){return e.filter(ig).map(t=>t.value)}function In(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function An(e,t){return t.flatMap((i,s)=>sg(i)?[`${e[s]?.id??"unknown"}: ${zi(i.reason)}`]:[])}async function Mn(e,t,i){const s=e.map((d,p)=>({item:d,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const d=s[o];if(d===void 0)return;o+=1;try{r[d.index]={status:"fulfilled",value:await i(d.item)}}catch(p){r[d.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function ig(e){return e.status==="fulfilled"}function sg(e){return e.status==="rejected"}function zi(e){return e instanceof Error?e.message:String(e)}function rg(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function og(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 ng(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function ag(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class lg{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 cg="pi-web:workspace-selection:v1";class dg{constructor(t=yi()){this.workspaceIdsByProject=new $s(cg,io,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function pg(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class hg{constructor(t,i,s,r,o=new lg,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??K}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,..._i()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(zs(f(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=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,..._i()});try{const r=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=pg(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(zs(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:zs(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,..._i()});try{const r=Wl(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=fg(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function ug(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function fg(e){return e.find(t=>t.isMain)??e[0]}const gg="pi-web:machine-navigation:v1";class mg{constructor(t=yi()){this.snapshotsByMachine=new $s(gg,bg,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Dn(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Dn(t))}forget(t){this.snapshotsByMachine.delete(t)}}function vg(e){return{machineId:e,surface:{}}}function Tn(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Dl,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 En(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 Dn(e){return{...e,surface:{...e.surface}}}function bg(e){if(!Jl(e))return;const t=Ye(e,"machineId");if(t===void 0)return;const i=Ql(Ye(e,"tool")),s=yg(Ye(e,"view"));return{machineId:t,projectId:Ye(e,"projectId"),workspaceId:Ye(e,"workspaceId"),sessionId:Ye(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:wg(e.surface)}}function wg(e){return Jl(e)?{selectedFilePath:Ye(e,"selectedFilePath"),selectedDiffPath:Ye(e,"selectedDiffPath"),selectedTerminalId:Ye(e,"selectedTerminalId")}:{}}function yg(e){return e==="navigation"||e==="chat"?e:Ql(e)}function Ql(e){return Sg(e)?e:void 0}function Sg(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ye(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Jl(e){return typeof e=="object"&&e!==null}const xg="pi-web:terminal-selection:v1";class kg{constructor(t=yi()){this.terminalIdsByCwd=new $s(xg,io,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 nk(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function ak(e){return e.find(t=>!t.exited)??e[0]}const Zl=1200,$g=["mod","alt","shift"];class Pg{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Yl(t);if(r===void 0)return!1;const o=so(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,r],o))return!0;if(this.clearPending(),!gi(r))return!1}else if(!gi(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Lg(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>ro(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Zl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function so(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Cg(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort(kr)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Ag),a=new Map,d=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Mg(u,n)??u;d.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=d.get(p),h=u===p,g=u===void 0||h?void 0:Wn(u),S=h?[...a.get(p)??[]].sort(kr).map(Wn):[];return{...p,active:h,shadows:S,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function Qs(e){return ec(e,{requireFirstChordActivator:!0})}function Xl(e){const t=ec(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Ni(e){return Xl(e).map(t=>t.split("+").map(ic).join("+")).join(" ")}function Yl(e){if(e.isComposing)return;const t=Dg(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 gi(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Cg(e,t,i){const s=Rg(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=Xl(r),n=o[0];if(!(n===void 0||!gi(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:Ig(o),order:i}}function Rg(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Ig(e){return e.join("\0")}function Wn(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function kr(e,t){return Ln(e.source)-Ln(t.source)||On(e.action.id,t.action.id)||On(e.action.title,t.action.title)||e.order-t.order}function Ag(e,t){return e.tokens.length-t.tokens.length||kr(e,t)}function Mg(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&ro(e.tokens,i.tokens))}function Ln(e){switch(e){case"custom":return 0;case"default":return 1}}function On(e,t){return e<t?-1:e>t?1:0}function ec(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=Tg(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!gi(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Tg(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Eg(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${ic(n)} 修饰键。`};i.add(n);continue}const a=tc(o);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${o}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...$g.filter(o=>i.has(o)),s].join("+")}}function Eg(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 tc(e){const t=Wg(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 Dg(e){if(e===" ")return"space";const t=e.toLowerCase();return tc(t)}function Wg(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 ic(e){return e==="mod"?Fn()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Fn()?"⌥":"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 Lg(e,t){return e.length===t.length&&ro(e,t)}function ro(e,t){return t.every((i,s)=>e[s]===i)}function Fn(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Og={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function ni(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=Un(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=Un(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Ut(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function _n(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=ni(e.draft);return!t.ok||Ut(t.request)!==Ut(e.previewRequest)?!1:qi(e.preview)}function qi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function sc(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function jn(e,t){const i=new Set(sc(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function Fg(e,t){return t(_g(e))}function _g(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
|
|
27
27
|
|
|
28
|
-
永久删除只适用于已归档会话,且无法撤销。`}function
|
|
28
|
+
永久删除只适用于已归档会话,且无法撤销。`}function jg(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function Un(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const oo="themes:classic",Ug="themes:pi-web-dark",Bg={themeId:Ug,auto:!0},rc="pi-web-app-theme",zg=["--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"],Ng=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function qg(){try{const e=window.localStorage.getItem(rc);return e===null?void 0:Qg(e)}catch{return}}function Hg(e){try{window.localStorage.setItem(rc,JSON.stringify(e))}catch{}}function Kg(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of zg){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Vg(e){const t=Gg(e.themes,e.fallbackThemeId??oo),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=oc(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function Gg(e,t=oo){return e.find(i=>i.id===t)??e[0]}function oc(e,t){return e.find(i=>i.light===t||i.dark===t)}function Qg(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Jg(i)?i:void 0}catch{return}}function Jg(e){if(!Zg(e))return!1;const t=e.themeId,i=e.auto;return Xg(t)&&typeof i=="boolean"}function Zg(e){return typeof e=="object"&&e!==null}function Xg(e){return typeof e=="string"&&Ng.test(e)}const Yg="workspace.delete",em="pi.operation",tm="target.workspaceId";function im(e){return{...e===void 0?{}:{projectId:e},metadata:{[em]:Yg}}}function sm(e){const t={};for(const i of e){const s=$r(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function rm(e){return Object.entries(e).filter(([,t])=>as(t)).map(([t])=>t)}function nc(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&as(i)}function $r(e){return e.metadata[tm]}function as(e){return e.status==="queued"||e.status==="running"}function Bn(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:Jt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:zn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:Jt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:Jt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:zn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:Jt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:om,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:Jt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:nm,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"关闭并从会话文件重新打开所选会话;如需重载 Pi 运行时资源,请在提示词中使用 /reload",group:"会话",enabled:lm,disabledReason:ac,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选的临时新会话",group:"会话",enabled:am,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&dt(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Jt(e){return e.state.selectedWorkspace!==void 0}function zn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function om(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!nc(e.state,t)}function nm(e){return He(e.state.selectedSession,e.state.status,Ps(e.state))}function am(e){return fi(e.state.selectedSession,e.state.status,Ps(e.state))}function lm(e){return!He(e.state.selectedSession,e.state.status,Ps(e.state))||ac(e)!==void 0?!1:!dt(e.state.status,e.state.activity)}function ac(e){if(He(e.state.selectedSession,e.state.status,Ps(e.state))&&!dt(e.state.status,e.state.activity))return cm(e.state,be.sessionsReload,"reload sessions from disk")}function Ps(e){return Vl(e.machineRuntimes[f(e)])}function cm(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&Pe(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const dm="modulepreload",pm=function(e){return"/"+e},Nn={},no=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let d=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");r=d(i.map(p=>{if(p=pm(p),p in Nn)return;Nn[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":dm,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((S,P)=>{g.addEventListener("load",S),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function hm(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Hi(e)}function Hi(e){switch(e){case"navigation":return $e`
|
|
29
29
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
30
30
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
31
31
|
<path d="M10 7h8"></path>
|
|
@@ -59,7 +59,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
59
59
|
<path d="m7 10 3 3-3 3"></path>
|
|
60
60
|
<path d="M12 16h5"></path>
|
|
61
61
|
</svg>
|
|
62
|
-
`}}const
|
|
62
|
+
`}}const um=10*1024*1024,fm="10 MB",gm=D`
|
|
63
63
|
: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; }
|
|
64
64
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
65
65
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -114,7 +114,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
114
114
|
.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); }
|
|
115
115
|
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; }
|
|
116
116
|
p { margin: 10px; }
|
|
117
|
-
`,
|
|
117
|
+
`,mm=D`
|
|
118
118
|
:host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
119
119
|
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
|
|
120
120
|
footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
@@ -165,7 +165,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
165
165
|
button { padding: 5px 7px; }
|
|
166
166
|
.icon-button { width: 34px; height: 34px; }
|
|
167
167
|
}
|
|
168
|
-
`;var
|
|
168
|
+
`;var vm=Object.defineProperty,bm=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var r=s>1?void 0:s?bm(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vm(t,i,r),r};let _e=class extends I{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=Qn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{Ii(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{Ii(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{Ii(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!Ii(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=Qn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&km(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&Kn(t)!==Kn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=qn(e.fileTree,e.expandedDirs,t),s=xm(t,i),r=t!==void 0&&t!=="";return l`
|
|
169
169
|
<section
|
|
170
170
|
class=${this.dragActive?"files-panel dragging":"files-panel"}
|
|
171
171
|
@dragenter=${this.handleDragEnter}
|
|
@@ -209,22 +209,22 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
209
209
|
<span>${t.name}</span>
|
|
210
210
|
</button>
|
|
211
211
|
${r?s.map(n=>this.renderTreeEntry(e,n,i+1)):null}
|
|
212
|
-
`}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:
|
|
212
|
+
`}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:qn(e.fileTree,e.expandedDirs,e.selectedFilePath)==="directory"?l`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Ft(t.size)}</p>`:(Em(),l`
|
|
213
213
|
<div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
|
|
214
214
|
<code-viewer .content=${t.content} .language=${t.language}></code-viewer>
|
|
215
|
-
`)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Ft(t.size)}`;if(t.size>
|
|
215
|
+
`)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Ft(t.size)}`;if(t.size>um)return l`
|
|
216
216
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
217
|
-
<p class="muted">图片过大,无法预览:${Ft(t.size)} · 限制 ${
|
|
217
|
+
<p class="muted">图片过大,无法预览:${Ft(t.size)} · 限制 ${fm}</p>
|
|
218
218
|
`;const s=Ph(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
|
|
219
219
|
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
220
220
|
<div class="image-preview">
|
|
221
221
|
<img src=${s} alt=${t.path} decoding="async" />
|
|
222
222
|
</div>
|
|
223
|
-
`}renderUploadProgress(e){const t=
|
|
223
|
+
`}renderUploadProgress(e){const t=wm(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
|
|
224
224
|
<section class="upload-progress" aria-label="工作区上传">
|
|
225
225
|
<div class="upload-progress-header">
|
|
226
226
|
<strong>上传</strong>
|
|
227
|
-
<small>${
|
|
227
|
+
<small>${Cm(t)}</small>
|
|
228
228
|
</div>
|
|
229
229
|
${t.map(i=>this.renderUploadBatch(e,i))}
|
|
230
230
|
</section>
|
|
@@ -232,12 +232,12 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
232
232
|
<article class=${`upload-batch ${t.status}`}>
|
|
233
233
|
<div class="upload-batch-heading">
|
|
234
234
|
<div>
|
|
235
|
-
<strong>${
|
|
235
|
+
<strong>${Rm(t)}</strong>
|
|
236
236
|
<small>${t.destinationFolder===""?"工作区根目录":t.destinationFolder}</small>
|
|
237
237
|
</div>
|
|
238
|
-
<span>${
|
|
238
|
+
<span>${Im(t)}</span>
|
|
239
239
|
</div>
|
|
240
|
-
<progress max="1" .value=${
|
|
240
|
+
<progress max="1" .value=${Am(t)}></progress>
|
|
241
241
|
<div class="upload-file-list">
|
|
242
242
|
${t.files.map(i=>this.renderUploadFile(i))}
|
|
243
243
|
</div>
|
|
@@ -245,13 +245,13 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
245
245
|
${t.status==="uploading"?l`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>取消</button>`:l`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>关闭</button>`}
|
|
246
246
|
</div>
|
|
247
247
|
</article>
|
|
248
|
-
`}renderUploadFile(e){const t=
|
|
248
|
+
`}renderUploadFile(e){const t=Tm(e);return l`
|
|
249
249
|
<div class=${`upload-file ${e.status}`}>
|
|
250
250
|
<div class="upload-file-main">
|
|
251
251
|
<span>${e.name}</span>
|
|
252
252
|
<small>${t}</small>
|
|
253
253
|
</div>
|
|
254
|
-
<span class="upload-file-status">${
|
|
254
|
+
<span class="upload-file-status">${Mm(e)}</span>
|
|
255
255
|
</div>
|
|
256
256
|
`}renderUploadDialog(e,t){const i=t.files.length;return l`
|
|
257
257
|
<div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
|
|
@@ -296,7 +296,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
296
296
|
</form>
|
|
297
297
|
</section>
|
|
298
298
|
</div>
|
|
299
|
-
`}promptCreateFile(e,t){const i=
|
|
299
|
+
`}promptCreateFile(e,t){const i=Vn("新建文件路径",Hn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=Vn("新建文件夹路径",Hn(e.selectedFilePath,t,"new-folder"));i!==void 0&&e.onCreateDirectory(i)}confirmDeleteSelectedPath(e){const t=e.selectedFilePath;t===void 0||t===""||window.confirm(`删除 ${t}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){const t=this.context,i=Sm(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=ym(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};_e.styles=[gm,D`
|
|
300
300
|
:host { flex: 1 1 auto; }
|
|
301
301
|
.files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
|
302
302
|
.toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
|
@@ -344,7 +344,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
344
344
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
345
345
|
.dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
|
|
346
346
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
347
|
-
`];it([c({attribute:!1})],_e.prototype,"context",2);it([q("#workspace-upload-input")],_e.prototype,"uploadInput",2);it([v()],_e.prototype,"pendingUpload",2);it([v()],_e.prototype,"destinationFolder",2);it([v()],_e.prototype,"overwrite",2);it([v()],_e.prototype,"createDirs",2);it([v()],_e.prototype,"formError",2);it([v()],_e.prototype,"dragActive",2);_e=it([W("workspace-files-panel")],_e);function
|
|
347
|
+
`];it([c({attribute:!1})],_e.prototype,"context",2);it([q("#workspace-upload-input")],_e.prototype,"uploadInput",2);it([v()],_e.prototype,"pendingUpload",2);it([v()],_e.prototype,"destinationFolder",2);it([v()],_e.prototype,"overwrite",2);it([v()],_e.prototype,"createDirs",2);it([v()],_e.prototype,"formError",2);it([v()],_e.prototype,"dragActive",2);_e=it([W("workspace-files-panel")],_e);function wm(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function ym(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{Gr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function Sm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function qn(e,t,i){if(i!==void 0)return $m(e,t,i)?.type}function xm(e,t){return e!==void 0&&e!==""&&t==="file"}function Hn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return Gn(e,i);const s=Pm(e);return s===""?i:Gn(s,i)}function km(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Kn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Vn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function $m(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}function Pm(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Gn(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function Qn(e){return e==null?[]:Array.from(e)}function Ii(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Cm(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function Rm(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function Im(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return lc(e.percent)}}function Am(e){return e.status==="uploading"?e.percent:1}function Mm(e){switch(e.status){case"pending":return"待处理";case"uploading":return lc(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function Tm(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${Ft(e.loaded)} / ${Ft(e.total)}`}function lc(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Em(){no(()=>import("./CodeViewer-_Lzl-tA7.js"),__vite__mapDeps([0,1,2,3]))}function Ft(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`${Js(t)} KB`;const i=t/1024;return i<1024?`${Js(i)} MB`:`${Js(i/1024)} GB`}function Js(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function Jn(){return[{id:"workspace.files",title:"文件",icon:Hi("files"),order:10,render:Dm},{id:"workspace.git",title:"Git",icon:Hi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Lm},{id:"workspace.terminal",title:"终端",icon:Hi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Wm}]}function Dm(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Wm(e){return jm(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Lm(e){const t=e.gitStatus;return l`
|
|
348
348
|
<section class="toolbar">
|
|
349
349
|
<strong>Git</strong>
|
|
350
350
|
${e.gitStale?l`<span class="stale">过期</span>`:null}
|
|
@@ -353,29 +353,29 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
353
353
|
<section class="split">
|
|
354
354
|
<div class="list">
|
|
355
355
|
${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
|
|
356
|
-
<p class="summary">${
|
|
356
|
+
<p class="summary">${Um(t)}</p>
|
|
357
357
|
${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
|
|
358
358
|
<button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
|
|
359
|
-
<span>${
|
|
359
|
+
<span>${Bm(i.index,i.workingTree)}</span>
|
|
360
360
|
<span>${i.path}</span>
|
|
361
361
|
</button>
|
|
362
362
|
`)}
|
|
363
363
|
`:l`<p class="muted">不是 Git 仓库。</p>`}
|
|
364
364
|
</div>
|
|
365
365
|
<div class="viewer">
|
|
366
|
-
${
|
|
366
|
+
${Om(e)}
|
|
367
367
|
</div>
|
|
368
368
|
</section>
|
|
369
|
-
`}function
|
|
369
|
+
`}function Om(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
|
|
370
370
|
<div class=${s.length===1?"diffs single":"diffs"}>
|
|
371
|
-
${s.map(r=>
|
|
371
|
+
${s.map(r=>Fm(r))}
|
|
372
372
|
</div>
|
|
373
|
-
`}function
|
|
373
|
+
`}function Fm(e){return _m(),l`
|
|
374
374
|
<section class="diff-section">
|
|
375
375
|
<div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
|
|
376
376
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
377
377
|
</section>
|
|
378
|
-
`}function zm(){co(()=>import("./UnifiedDiffViewer-D_OLq3Q4.js"),__vite__mapDeps([4,1,2]))}function Nm(){co(()=>import("./TerminalPanel-8Or6pbwb.js"),__vite__mapDeps([5,6,7,1,2]))}function qm(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Hm(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Km={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!ec();return{contributions:{actions:e?zn():zn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?Zn():Zn().filter(t=>t.id!=="workspace.terminal")}}}},Vm={"--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"},Gm={"--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"},Qm={"--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"},Jm={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Gm},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Qm},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Vm}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Zm=/^[a-z][a-z0-9.-]*$/u;function Xm(e){return Zm.test(e)}const Ym="machine.";function ev(e,t){if(e==="")throw new Error("Machine id is required");if(!Xm(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Ym}${tv(e)}.${t}`}function tv(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Xn(e="/pi-web-plugins/manifest.json",t={}){const i=await iv(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=ov(n,o);s.push({id:t.machineId===void 0?r.id:ev(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function iv(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 sv(await t.json())}}function sv(e){if(!ls(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ls(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:rv(t.machineSpecific)}})}}function rv(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function ov(e,t){if(!ls(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nv(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nv(e){return ls(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ls(e){return typeof e=="object"&&e!==null}const av=/^[a-z][a-z0-9.-]*$/u,lv=/^[a-z][a-z0-9.-]*$/u,nc=new WeakMap,ac=new WeakMap;class cv{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 r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:$e}).contributions;for(const d of a.actions??[])this.actions.push(this.qualifyAction(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,d,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const d of a.themes??[])this.themes.push(this.qualifyTheme(i,d));for(const d of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,d));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&uv(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=gv(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=dv(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}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,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:d=>this.isContributionActive(t,s,d.machine.id,r)&&(a?.(Zs(d,t))??!0),...n===void 0?{}:{badge:d=>this.isContributionActive(t,s,d.machine.id,r)?n(Zs(d,t)):void 0},render:d=>i.render(Zs(d,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:d=>this.isContributionActive(t,s,d.machine.id,r)&&(n?.(d)??!0),items:d=>this.isContributionActive(t,s,d.machine.id,r)?a(d):[]}}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,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,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(!av.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lv.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}: ${fv(i)}`);return i}}function dv(e,t){return nc.get(e)?.(t)??e}function Zs(e,t){return ac.get(e)?.(t)??e}function pv(e,t){return nc.set(e,t),e}function hv(e,t){return ac.set(e,t),e}function uv(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function fv(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 gv(e){return e.state.selectedMachine?.id??"local"}const mv=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vv(){return typeof window>"u"||!("matchMedia"in window)?[]:mv.map(e=>window.matchMedia(e))}function Yn(e,t=bv()){return e.some(i=>i.matches)||wv(t)}function bv(){return typeof navigator>"u"?void 0:navigator}function wv(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yv=250;class Sv{constructor(t=xv()){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()},yv)}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 xv(){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 kv="(max-width: 760px)",$v="(max-width: 1180px)";class Pv{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Yn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Cv(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Rv(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vv(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Sv,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Yn(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);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.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Iv(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Cv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(kv)}function Rv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia($v)}function Iv(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const cs=["machines","projects","workspaces","sessions"];function Av(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function po(e,t){if(e!=="none")return e??Av(t)}function Mv(e,t){return t.isMobileLayout?po(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Tv(e,t,i){return po(e,i.state)===t?"none":t}function Ev(e,t,i){return i?t:e}function Dv(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Ov(i)}function Wv(e){return cs[cs.indexOf(e)+1]}class Lv{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return po(this.expanded,this.getState())}isCollapsed(t){return Mv(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Tv(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Dv(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Ev(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Wv(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){Fv(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Ov(e){const t=new Set(e);return cs.filter(i=>t.has(i))}function Fv(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _v{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",lc(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function lc(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Cr="pi-web:panel-sizes:v1",jv={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Uv{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??ho(),this.panelSizes=qv(this.storage)}hostConnected(){}constraints(t){return Si(t)}panelWidth(t,i){return Ce(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=Ce(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Vv(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Gv(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(){Hv(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${ta(Ce("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${ta(Ce("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Si(e){return jv[e]}function Bv(e,t,i){return e==="navigation"?i-t:t-i}function zv(e,t,i,s,r=Si(e)){return Ce(e,t+Bv(e,i,s),r)}function Nv(e,t,i,s={}){const r=s.constraints??Si(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Qv(e,i,o);if(n!==void 0)return Ce(e,t+n,r)}function Ce(e,t,i=Si(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function qv(e=ho()){try{const t=e?.getItem(Cr);if(t==null||t==="")return{};const i=JSON.parse(t);return Kv(i)}catch{return{}}}function Hv(e,t=ho()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Cr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=Ce("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=Ce("workspace",e.workspacePanelWidth)),t.setItem(Cr,JSON.stringify(i))}catch{}}function Kv(e){if(!Jv(e)||e.version!==1)return{};const t={},i=ea(e.navigationPanelWidth),s=ea(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=Ce("navigation",i)),s!==void 0&&(t.workspacePanelWidth=Ce("workspace",s)),t}function ea(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Vv(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Gv(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Qv(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 ta(e){return`${String(Math.round(e))}px`}function ho(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Jv(e){return typeof e=="object"&&e!==null}function ia(){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:Zv(e.get("tool")),view:Xv(e.get("view"))}}function Xs(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Zv(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":cc(e)?e:void 0}function Xv(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":cc(e)?e:void 0}function cc(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function sa(){return Yv(new URLSearchParams(window.location.search).get("settings"))}function Ys(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function Yv(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="packages"||e==="pi-packages")return"packages";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function eb(e,t){return t===void 0?e:e.map(i=>ib(i,t))}function tb(e,t){const i=new Set(no(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return eb(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?dc(s):s)}function ib(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?dc(e):{...e,shortcut:i}}function dc(e){const t={...e};return delete t.shortcut,t}function sb(e,t){const i=t.api??Ot,s=t.pollIntervalMs??1e3,r=t.setTimeout??ob(),o=t.clearTimeout??nb();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:rb(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function rb(e,t,i,s,r){return ra(e)?Promise.resolve(e):new Promise((o,n)=>{let a,d=!1;const p=g=>{d||(d=!0,a!==void 0&&r(a),o(g))},u=g=>{d||(d=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&ra(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function ra(e){return e.status==="succeeded"||e.status==="failed"}function ob(){return(e,t)=>globalThis.setTimeout(e,t)}function nb(){return e=>{globalThis.clearTimeout(e)}}function ab(e,t){return t[e.path]}function lb(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function cb(e,t,i){return hc(db(e,t,i))}function pc(e){return hc(Object.values(e??{}))}function hc(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function db(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function uc(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Cs(e,t="活跃"){const i=uc(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Ai=0,pb=120;function fc(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?gc():hb(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),d=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ai,g=i.top-d-Ai;return[...h<pb&&g>h?[`bottom: ${Mt(o-i.top+Ai)};`,`max-height: ${Mt(Math.max(0,g))};`]:[`top: ${Mt(i.bottom+Ai)};`,`max-height: ${Mt(Math.max(0,h))};`],`right: ${Mt(Math.max(0,r-u))};`,`max-width: ${Mt(Math.max(0,u-n))};`].join(" ")}function hb(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():gc()}function gc(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Mt(e){return`${String(Math.round(e))}px`}class Rs{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=fc(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const ub=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function mc(e){return e.composedPath().some(t=>fb(t,ub))}function fb(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 Is(e,t){mc(e)||t()}function As(e,t){return mc(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?mt(e,()=>{oa(e.currentTarget,-1)}):e.key==="ArrowDown"?mt(e,()=>{oa(e.currentTarget,1)}):e.key==="Home"?mt(e,()=>{na(e.currentTarget,0)}):e.key==="End"?mt(e,()=>{na(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?mt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?mt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?mt(e,t.cancel):!1}function Ms(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 mt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function oa(e,t){const i=bc(e),s=wc(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||vc(i,r+t)}function na(e,t){const i=bc(e);i.length!==0&&vc(i,t<0?i.length-1:t)}function vc(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function bc(e){const t=wc(e)?.getRootNode();return t===void 0||!gb(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function gb(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function wc(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Ts=D`
|
|
378
|
+
`}function _m(){no(()=>import("./UnifiedDiffViewer-BwONrl2w.js"),__vite__mapDeps([4,1,2]))}function jm(){no(()=>import("./TerminalPanel-BVBJC-6w.js"),__vite__mapDeps([5,6,7,1,2]))}function Um(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Bm(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const zm={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!ol();return{contributions:{actions:e?Bn():Bn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?Jn():Jn().filter(t=>t.id!=="workspace.terminal")}}}},Nm={"--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"},qm={"--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"},Hm={"--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"},Km={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:qm},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Hm},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Nm}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Vm=/^[a-z][a-z0-9.-]*$/u;function Gm(e){return Vm.test(e)}const Qm="machine.";function Jm(e,t){if(e==="")throw new Error("Machine id is required");if(!Gm(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Qm}${Zm(e)}.${t}`}function Zm(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Zn(e="/pi-web-plugins/manifest.json",t={}){const i=await Xm(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=tv(n,o);s.push({id:t.machineId===void 0?r.id:Jm(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function Xm(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 Ym(await t.json())}}function Ym(e){if(!ls(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ls(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:ev(t.machineSpecific)}})}}function ev(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function tv(e,t){if(!ls(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!iv(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function iv(e){return ls(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ls(e){return typeof e=="object"&&e!==null}const sv=/^[a-z][a-z0-9.-]*$/u,rv=/^[a-z][a-z0-9.-]*$/u,cc=new WeakMap,dc=new WeakMap;class ov{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 r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:$e}).contributions;for(const d of a.actions??[])this.actions.push(this.qualifyAction(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,d,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const d of a.themes??[])this.themes.push(this.qualifyTheme(i,d));for(const d of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,d));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&cv(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=pv(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=nv(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}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,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:d=>this.isContributionActive(t,s,d.machine.id,r)&&(a?.(Zs(d,t))??!0),...n===void 0?{}:{badge:d=>this.isContributionActive(t,s,d.machine.id,r)?n(Zs(d,t)):void 0},render:d=>i.render(Zs(d,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:d=>this.isContributionActive(t,s,d.machine.id,r)&&(n?.(d)??!0),items:d=>this.isContributionActive(t,s,d.machine.id,r)?a(d):[]}}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,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,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(!sv.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!rv.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}: ${dv(i)}`);return i}}function nv(e,t){return cc.get(e)?.(t)??e}function Zs(e,t){return dc.get(e)?.(t)??e}function av(e,t){return cc.set(e,t),e}function lv(e,t){return dc.set(e,t),e}function cv(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function dv(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 pv(e){return e.state.selectedMachine?.id??"local"}const hv=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function uv(){return typeof window>"u"||!("matchMedia"in window)?[]:hv.map(e=>window.matchMedia(e))}function Xn(e,t=fv()){return e.some(i=>i.matches)||gv(t)}function fv(){return typeof navigator>"u"?void 0:navigator}function gv(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const mv=250;class vv{constructor(t=bv()){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()},mv)}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 bv(){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 wv="(max-width: 760px)",yv="(max-width: 1180px)";class Sv{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Xn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??xv(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??kv(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??uv(),this.viewportPositionRepairer=i.viewportPositionRepairer??new vv,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Xn(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);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.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return $v(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function xv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(wv)}function kv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(yv)}function $v(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const cs=["machines","projects","workspaces","sessions"];function Pv(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function ao(e,t){if(e!=="none")return e??Pv(t)}function Cv(e,t){return t.isMobileLayout?ao(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Rv(e,t,i){return ao(e,i.state)===t?"none":t}function Iv(e,t,i){return i?t:e}function Av(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Ev(i)}function Mv(e){return cs[cs.indexOf(e)+1]}class Tv{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return ao(this.expanded,this.getState())}isCollapsed(t){return Cv(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Rv(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Av(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Iv(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Mv(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){Dv(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Ev(e){const t=new Set(e);return cs.filter(i=>t.has(i))}function Dv(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Wv{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",pc(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function pc(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Pr="pi-web:panel-sizes:v1",Lv={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Ov{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??lo(),this.panelSizes=Uv(this.storage)}hostConnected(){}constraints(t){return Si(t)}panelWidth(t,i){return Ce(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=Ce(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Nv(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=qv(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(){Bv(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${ea(Ce("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${ea(Ce("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Si(e){return Lv[e]}function Fv(e,t,i){return e==="navigation"?i-t:t-i}function _v(e,t,i,s,r=Si(e)){return Ce(e,t+Fv(e,i,s),r)}function jv(e,t,i,s={}){const r=s.constraints??Si(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Hv(e,i,o);if(n!==void 0)return Ce(e,t+n,r)}function Ce(e,t,i=Si(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Uv(e=lo()){try{const t=e?.getItem(Pr);if(t==null||t==="")return{};const i=JSON.parse(t);return zv(i)}catch{return{}}}function Bv(e,t=lo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Pr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=Ce("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=Ce("workspace",e.workspacePanelWidth)),t.setItem(Pr,JSON.stringify(i))}catch{}}function zv(e){if(!Kv(e)||e.version!==1)return{};const t={},i=Yn(e.navigationPanelWidth),s=Yn(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=Ce("navigation",i)),s!==void 0&&(t.workspacePanelWidth=Ce("workspace",s)),t}function Yn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Nv(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function qv(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Hv(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 ea(e){return`${String(Math.round(e))}px`}function lo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Kv(e){return typeof e=="object"&&e!==null}function ta(){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:Vv(e.get("tool")),view:Gv(e.get("view"))}}function Xs(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Vv(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":hc(e)?e:void 0}function Gv(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":hc(e)?e:void 0}function hc(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function ia(){return Qv(new URLSearchParams(window.location.search).get("settings"))}function Ys(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function Qv(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="packages"||e==="pi-packages")return"packages";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Jv(e,t){return t===void 0?e:e.map(i=>Xv(i,t))}function Zv(e,t){const i=new Set(so(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Jv(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?uc(s):s)}function Xv(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?uc(e):{...e,shortcut:i}}function uc(e){const t={...e};return delete t.shortcut,t}function Yv(e,t){const i=t.api??Ot,s=t.pollIntervalMs??1e3,r=t.setTimeout??tb(),o=t.clearTimeout??ib();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:eb(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function eb(e,t,i,s,r){return sa(e)?Promise.resolve(e):new Promise((o,n)=>{let a,d=!1;const p=g=>{d||(d=!0,a!==void 0&&r(a),o(g))},u=g=>{d||(d=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&sa(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function sa(e){return e.status==="succeeded"||e.status==="failed"}function tb(){return(e,t)=>globalThis.setTimeout(e,t)}function ib(){return e=>{globalThis.clearTimeout(e)}}function sb(e,t){return t[e.path]}function rb(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function ob(e,t,i){return gc(nb(e,t,i))}function fc(e){return gc(Object.values(e??{}))}function gc(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function nb(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function mc(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Cs(e,t="活跃"){const i=mc(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Ai=0,ab=120;function vc(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?bc():lb(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),d=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ai,g=i.top-d-Ai;return[...h<ab&&g>h?[`bottom: ${Tt(o-i.top+Ai)};`,`max-height: ${Tt(Math.max(0,g))};`]:[`top: ${Tt(i.bottom+Ai)};`,`max-height: ${Tt(Math.max(0,h))};`],`right: ${Tt(Math.max(0,r-u))};`,`max-width: ${Tt(Math.max(0,u-n))};`].join(" ")}function lb(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():bc()}function bc(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Tt(e){return`${String(Math.round(e))}px`}class Rs{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=vc(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const cb=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function wc(e){return e.composedPath().some(t=>db(t,cb))}function db(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 Is(e,t){wc(e)||t()}function As(e,t){return wc(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?mt(e,()=>{ra(e.currentTarget,-1)}):e.key==="ArrowDown"?mt(e,()=>{ra(e.currentTarget,1)}):e.key==="Home"?mt(e,()=>{oa(e.currentTarget,0)}):e.key==="End"?mt(e,()=>{oa(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?mt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?mt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?mt(e,t.cancel):!1}function Ms(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 mt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function ra(e,t){const i=Sc(e),s=xc(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||yc(i,r+t)}function oa(e,t){const i=Sc(e);i.length!==0&&yc(i,t<0?i.length-1:t)}function yc(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Sc(e){const t=xc(e)?.getRootNode();return t===void 0||!pb(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function pb(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function xc(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Ts=D`
|
|
379
379
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
380
380
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
381
381
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -436,7 +436,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
436
436
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
437
437
|
.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; }
|
|
438
438
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
439
|
-
`;var
|
|
439
|
+
`;var hb=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?ub(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&hb(t,i,r),r};let he=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
440
440
|
<section>
|
|
441
441
|
<h2>${this.renderHeading()}</h2>
|
|
442
442
|
${this.collapsed?null:l`
|
|
@@ -445,7 +445,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
445
445
|
</div>
|
|
446
446
|
`}
|
|
447
447
|
</section>
|
|
448
|
-
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=
|
|
448
|
+
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=kc(e)&&this.onRemove!==void 0;return l`
|
|
449
449
|
<div
|
|
450
450
|
class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
|
|
451
451
|
tabindex="0"
|
|
@@ -458,7 +458,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
458
458
|
</div>
|
|
459
459
|
${s?this.renderMachineMenu(e):null}
|
|
460
460
|
</div>
|
|
461
|
-
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=
|
|
461
|
+
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=fc(this.activities[e.id]);return Cs(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=fb(e.id);return l`
|
|
462
462
|
<div class="action-menu">
|
|
463
463
|
<button
|
|
464
464
|
class="action-menu-toggle"
|
|
@@ -474,13 +474,13 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
474
474
|
</div>
|
|
475
475
|
`:null}
|
|
476
476
|
</div>
|
|
477
|
-
`}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",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?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||As(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};
|
|
477
|
+
`}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",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?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||As(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};he.styles=[Ts,D`
|
|
478
478
|
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
479
479
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
480
480
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
481
481
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
482
482
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
483
|
-
`];Ee([c({attribute:!1})],
|
|
483
|
+
`];Ee([c({attribute:!1})],he.prototype,"machines",2);Ee([c({attribute:!1})],he.prototype,"selected",2);Ee([c({attribute:!1})],he.prototype,"statuses",2);Ee([c({attribute:!1})],he.prototype,"activities",2);Ee([c({type:Boolean,reflect:!0})],he.prototype,"collapsible",2);Ee([c({type:Boolean,reflect:!0})],he.prototype,"collapsed",2);Ee([c({attribute:!1})],he.prototype,"onSelect",2);Ee([c({attribute:!1})],he.prototype,"onRemove",2);Ee([c({attribute:!1})],he.prototype,"onToggleCollapsed",2);Ee([c({attribute:!1})],he.prototype,"onFocusNextSection",2);Ee([c({attribute:!1})],he.prototype,"onCancelKeyboardNavigation",2);he=Ee([W("machine-list")],he);function kc(e){return e.kind==="remote"}function fb(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?mb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gb(t,i,r),r};let le=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
484
484
|
<section>
|
|
485
485
|
<h2>${this.renderHeading()}</h2>
|
|
486
486
|
${this.collapsed?null:l`
|
|
@@ -515,14 +515,14 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
515
515
|
</div>
|
|
516
516
|
`}
|
|
517
517
|
</section>
|
|
518
|
-
`}handleProjectKeydown(e,t){As(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"项目";const e=this.selected?.name??"未选择项目",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?"▸":"▾"} 项目</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=
|
|
518
|
+
`}handleProjectKeydown(e,t){As(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"项目";const e=this.selected?.name??"未选择项目",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?"▸":"▾"} 项目</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=ob(e,this.workspacesByProjectId[e.id]??[],this.activities);return Cs(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
|
|
519
519
|
|
|
520
|
-
这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};le.styles=Ts;Se([c({attribute:!1})],le.prototype,"projects",2);Se([c({attribute:!1})],le.prototype,"selected",2);Se([c({attribute:!1})],le.prototype,"activities",2);Se([c({attribute:!1})],le.prototype,"workspacesByProjectId",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsible",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsed",2);Se([c({attribute:!1})],le.prototype,"onSelect",2);Se([c({attribute:!1})],le.prototype,"onClose",2);Se([c({attribute:!1})],le.prototype,"onToggleCollapsed",2);Se([c({attribute:!1})],le.prototype,"onFocusPreviousSection",2);Se([c({attribute:!1})],le.prototype,"onFocusNextSection",2);Se([c({attribute:!1})],le.prototype,"onCancelKeyboardNavigation",2);le=Se([W("project-list")],le);function
|
|
520
|
+
这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};le.styles=Ts;Se([c({attribute:!1})],le.prototype,"projects",2);Se([c({attribute:!1})],le.prototype,"selected",2);Se([c({attribute:!1})],le.prototype,"activities",2);Se([c({attribute:!1})],le.prototype,"workspacesByProjectId",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsible",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsed",2);Se([c({attribute:!1})],le.prototype,"onSelect",2);Se([c({attribute:!1})],le.prototype,"onClose",2);Se([c({attribute:!1})],le.prototype,"onToggleCollapsed",2);Se([c({attribute:!1})],le.prototype,"onFocusPreviousSection",2);Se([c({attribute:!1})],le.prototype,"onFocusNextSection",2);Se([c({attribute:!1})],le.prototype,"onCancelKeyboardNavigation",2);le=Se([W("project-list")],le);function na(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${vb(t)}`)}function vb(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&bb(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 bb(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var wb=Object.defineProperty,yb=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?yb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&wb(t,i,r),r};let oe=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new Rs(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
521
521
|
<section>
|
|
522
522
|
<h2>${this.renderHeading()}</h2>
|
|
523
523
|
${this.collapsed?null:l`
|
|
524
524
|
<div class="list-body">
|
|
525
|
-
${this.workspaces.map(e=>{const t=
|
|
525
|
+
${this.workspaces.map(e=>{const t=Sb(e),i=this.workspaceLabelItems(e);return l`
|
|
526
526
|
<div
|
|
527
527
|
class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
|
|
528
528
|
tabindex="0"
|
|
@@ -539,18 +539,18 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
539
539
|
</div>
|
|
540
540
|
`}
|
|
541
541
|
</section>
|
|
542
|
-
`}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${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?"▸":"▾"} 工作区</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=
|
|
542
|
+
`}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${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?"▸":"▾"} 工作区</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=rb(sb(e,this.activities));return Cs(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
|
|
543
543
|
<span class="workspace-primary">
|
|
544
544
|
<span class="workspace-primary-label">${e}</span>
|
|
545
545
|
${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
|
|
546
546
|
</span>
|
|
547
547
|
${t.length===0?null:l`
|
|
548
548
|
<small class="workspace-secondary">
|
|
549
|
-
<span class="workspace-label">${
|
|
549
|
+
<span class="workspace-label">${na(t)}</span>
|
|
550
550
|
</small>
|
|
551
551
|
`}
|
|
552
552
|
${this.renderActivity(i)}
|
|
553
|
-
`}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=
|
|
553
|
+
`}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=kb(i.id);return l`
|
|
554
554
|
<div class="action-menu">
|
|
555
555
|
<button
|
|
556
556
|
class="action-menu-toggle"
|
|
@@ -567,7 +567,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
567
567
|
</div>
|
|
568
568
|
`:null}
|
|
569
569
|
</div>
|
|
570
|
-
`}renderWorkspaceActions(e){if(!
|
|
570
|
+
`}renderWorkspaceActions(e){if(!xb(e))return;const t=this.isDeleting(e);return l`
|
|
571
571
|
<div class="workspace-menu-actions">
|
|
572
572
|
<button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
|
|
573
573
|
</div>
|
|
@@ -584,11 +584,11 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
584
584
|
${t.length===0?null:l`
|
|
585
585
|
<div class="workspace-detail-row">
|
|
586
586
|
<dt>详情</dt>
|
|
587
|
-
<dd><span class="workspace-label">${
|
|
587
|
+
<dd><span class="workspace-label">${na(t)}</span></dd>
|
|
588
588
|
</div>
|
|
589
589
|
`}
|
|
590
590
|
</dl>
|
|
591
|
-
`}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||As(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"})}};oe.styles=Ts;
|
|
591
|
+
`}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||As(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"})}};oe.styles=Ts;ge([c({attribute:!1})],oe.prototype,"workspaces",2);ge([c({attribute:!1})],oe.prototype,"selected",2);ge([c({type:Boolean,reflect:!0})],oe.prototype,"collapsible",2);ge([c({type:Boolean,reflect:!0})],oe.prototype,"collapsed",2);ge([c({attribute:!1})],oe.prototype,"workspaceLabelItems",2);ge([c({attribute:!1})],oe.prototype,"activities",2);ge([c({attribute:!1})],oe.prototype,"deletingWorkspaceIds",2);ge([c({attribute:!1})],oe.prototype,"onSelect",2);ge([c({attribute:!1})],oe.prototype,"onDelete",2);ge([c({attribute:!1})],oe.prototype,"onToggleCollapsed",2);ge([c({attribute:!1})],oe.prototype,"onFocusPreviousSection",2);ge([c({attribute:!1})],oe.prototype,"onFocusNextSection",2);ge([c({attribute:!1})],oe.prototype,"onCancelKeyboardNavigation",2);oe=ge([W("workspace-list")],oe);function Sb(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function xb(e){return e.isGitWorktree&&!e.isMain}function kb(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}function $c(e){return e.slice(-8)}var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?Pb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$b(t,i,r),r};function Zt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:$c(e.id)}let A=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);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,Ms(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Ib(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>Xt(o)==="current"),s=Pc(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Cb(this.sessions);return l`
|
|
592
592
|
<section>
|
|
593
593
|
${this.renderHeading(e.length+s.length,i)}
|
|
594
594
|
${this.collapsed?null:l`
|
|
@@ -621,7 +621,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
621
621
|
${this.renderCleanupButton()}
|
|
622
622
|
${this.renderStartButton()}
|
|
623
623
|
</h2>
|
|
624
|
-
`}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭当前会话选择":"选择当前会话"} aria-label=${t?"关闭当前会话选择":"选择当前会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderCleanupButton(){return l`<button class="cleanup-entry" title=${this.canCleanup?"预览会话清理":this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>清理</button>`}renderStartButton(){const e=this.startingCount>0?"
|
|
624
|
+
`}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭当前会话选择":"选择当前会话"} aria-label=${t?"关闭当前会话选择":"选择当前会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderCleanupButton(){return l`<button class="cleanup-entry" title=${this.canCleanup?"预览会话清理":this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>清理</button>`}renderStartButton(){const e=this.startingCount>0?"再启动一个会话":"启动新会话";return l`<button class="start-session-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${t=>{t.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){const e=this.startingCount!==1;return l`
|
|
625
625
|
<div class="pending-session-row starting-session" role="status" aria-live="polite">
|
|
626
626
|
<div class="action-main">
|
|
627
627
|
<span class="action-name"><span class="activity-indicator sending" aria-hidden="true"></span>${e?`Starting ${String(this.startingCount)} sessions…`:"Starting session…"}</span>
|
|
@@ -684,7 +684,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
684
684
|
`:null}
|
|
685
685
|
</div>
|
|
686
686
|
</div>
|
|
687
|
-
`}handleSessionKeydown(e,t,i){As(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)&&Xt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Zt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Zt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=er(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>He(t,this.statuses[t.id],this.sessionPersistenceOptions()));this.selectedSessionIds=er(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=>Xt(i)===e).map(i=>i.id);this.selectedSessionIds=er(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)&&Xt(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")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e,t,i){return fi(e,t,this.sessionPersistenceOptions())?i?.phase==="active"?"创建中 · ":i?.phase==="error"?"错误 · ":"新建 · ":e.archived===!0?"只读 · ":""}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e){const t=
|
|
687
|
+
`}handleSessionKeydown(e,t,i){As(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)&&Xt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Zt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Zt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=er(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>He(t,this.statuses[t.id],this.sessionPersistenceOptions()));this.selectedSessionIds=er(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=>Xt(i)===e).map(i=>i.id);this.selectedSessionIds=er(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)&&Xt(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")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e,t,i){return fi(e,t,this.sessionPersistenceOptions())?i?.phase==="active"?"创建中 · ":i?.phase==="error"?"错误 · ":"新建 · ":e.archived===!0?"只读 · ":""}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e){const t=Rb(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Cs(t,t==="sending"?"正在发送消息":"会话活跃")}};A.styles=[Ts,D`
|
|
688
688
|
h2 { min-height: 30px; }
|
|
689
689
|
h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
690
690
|
.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; }
|
|
@@ -705,7 +705,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
705
705
|
.pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
|
|
706
706
|
.action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
|
|
707
707
|
.session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
|
|
708
|
-
`];M([c({attribute:!1})],A.prototype,"sessions",2);M([c({attribute:!1})],A.prototype,"statuses",2);M([c({attribute:!1})],A.prototype,"activities",2);M([c({attribute:!1})],A.prototype,"sending",2);M([c({attribute:!1})],A.prototype,"selected",2);M([c({type:Number})],A.prototype,"startingCount",2);M([c({type:Boolean})],A.prototype,"canStart",2);M([c({type:Boolean})],A.prototype,"canDeleteArchived",2);M([c({type:Boolean})],A.prototype,"canReload",2);M([c({type:Boolean})],A.prototype,"canCleanup",2);M([c({type:Boolean})],A.prototype,"authoritativeSessionPersistence",2);M([c({type:String})],A.prototype,"archivedDeleteUnavailableMessage",2);M([c({type:String})],A.prototype,"cleanupUnavailableMessage",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsible",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsed",2);M([c({attribute:!1})],A.prototype,"onSelect",2);M([c({attribute:!1})],A.prototype,"onStart",2);M([c({attribute:!1})],A.prototype,"onToggleCollapsed",2);M([c({attribute:!1})],A.prototype,"onArchivedCollapsed",2);M([c({attribute:!1})],A.prototype,"onFocusPreviousSection",2);M([c({attribute:!1})],A.prototype,"onFocusNextSection",2);M([c({attribute:!1})],A.prototype,"onCancelKeyboardNavigation",2);M([c({attribute:!1})],A.prototype,"onArchive",2);M([c({attribute:!1})],A.prototype,"onArchiveWithDescendants",2);M([c({attribute:!1})],A.prototype,"onArchiveMany",2);M([c({attribute:!1})],A.prototype,"onRestore",2);M([c({attribute:!1})],A.prototype,"onDelete",2);M([c({attribute:!1})],A.prototype,"onDeleteArchived",2);M([c({attribute:!1})],A.prototype,"onDeleteArchivedMany",2);M([c({attribute:!1})],A.prototype,"onDetachParent",2);M([c({attribute:!1})],A.prototype,"onReload",2);M([c({attribute:!1})],A.prototype,"onCleanup",2);M([v()],A.prototype,"archivedExpanded",2);M([v()],A.prototype,"selectionScopes",2);M([v()],A.prototype,"selectedSessionIds",2);A=M([W("session-list")],A);function Xt(e){return e.archived===!0?"archived":"current"}function er(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function
|
|
708
|
+
`];M([c({attribute:!1})],A.prototype,"sessions",2);M([c({attribute:!1})],A.prototype,"statuses",2);M([c({attribute:!1})],A.prototype,"activities",2);M([c({attribute:!1})],A.prototype,"sending",2);M([c({attribute:!1})],A.prototype,"selected",2);M([c({type:Number})],A.prototype,"startingCount",2);M([c({type:Boolean})],A.prototype,"canStart",2);M([c({type:Boolean})],A.prototype,"canDeleteArchived",2);M([c({type:Boolean})],A.prototype,"canReload",2);M([c({type:Boolean})],A.prototype,"canCleanup",2);M([c({type:Boolean})],A.prototype,"authoritativeSessionPersistence",2);M([c({type:String})],A.prototype,"archivedDeleteUnavailableMessage",2);M([c({type:String})],A.prototype,"cleanupUnavailableMessage",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsible",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsed",2);M([c({attribute:!1})],A.prototype,"onSelect",2);M([c({attribute:!1})],A.prototype,"onStart",2);M([c({attribute:!1})],A.prototype,"onToggleCollapsed",2);M([c({attribute:!1})],A.prototype,"onArchivedCollapsed",2);M([c({attribute:!1})],A.prototype,"onFocusPreviousSection",2);M([c({attribute:!1})],A.prototype,"onFocusNextSection",2);M([c({attribute:!1})],A.prototype,"onCancelKeyboardNavigation",2);M([c({attribute:!1})],A.prototype,"onArchive",2);M([c({attribute:!1})],A.prototype,"onArchiveWithDescendants",2);M([c({attribute:!1})],A.prototype,"onArchiveMany",2);M([c({attribute:!1})],A.prototype,"onRestore",2);M([c({attribute:!1})],A.prototype,"onDelete",2);M([c({attribute:!1})],A.prototype,"onDeleteArchived",2);M([c({attribute:!1})],A.prototype,"onDeleteArchivedMany",2);M([c({attribute:!1})],A.prototype,"onDetachParent",2);M([c({attribute:!1})],A.prototype,"onReload",2);M([c({attribute:!1})],A.prototype,"onCleanup",2);M([v()],A.prototype,"archivedExpanded",2);M([v()],A.prototype,"selectionScopes",2);M([v()],A.prototype,"selectedSessionIds",2);A=M([W("session-list")],A);function Xt(e){return e.archived===!0?"archived":"current"}function er(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Cb(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Rb(e,t,i,s){if(!(Zi(e)||e.archived===!0))return s?"sending":dt(t,i)?"session":void 0}function Ib(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 r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return Pc(e.filter(s=>i.has(s.id)))}function Pc(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,d=a===void 0?void 0:t.get(a);if(d===void 0){s.push(n);continue}const p=i.get(d.path)??[];p.push(n),i.set(d.path,p)}const r=[],o=(n,a,d)=>{if(d.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(d);u.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var Ab=Object.defineProperty,Mb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ab(t,i,r),r};let te=class extends I{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...Og},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=ni(this.draft),t=this.selectedPreview(),i=_n({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!qi(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
|
|
709
709
|
<div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
|
|
710
710
|
<section role="dialog" aria-modal="true" aria-label="清理会话" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
|
|
711
711
|
<header>
|
|
@@ -734,20 +734,20 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
734
734
|
<label class="toggle-row">
|
|
735
735
|
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:tr(r)})}}>
|
|
736
736
|
<span>归档空闲超过</span>
|
|
737
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:
|
|
737
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:aa(r)})}}>
|
|
738
738
|
<span>天的未归档会话</span>
|
|
739
739
|
</label>
|
|
740
740
|
<label class="toggle-row delete-row">
|
|
741
741
|
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:tr(r)})}}>
|
|
742
742
|
<span>删除已归档超过</span>
|
|
743
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:
|
|
743
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:aa(r)})}}>
|
|
744
744
|
<span>天的已归档会话</span>
|
|
745
745
|
</label>
|
|
746
746
|
</fieldset>
|
|
747
747
|
<p class="warning"><strong>删除是永久操作。</strong>清理只会删除已经归档的会话。</p>
|
|
748
748
|
${e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}
|
|
749
749
|
${s?l`<div class="hint" role="status">阈值已更改。运行清理前请重新预览。</div>`:null}
|
|
750
|
-
`}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=
|
|
750
|
+
`}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=jn(e,t);return l`
|
|
751
751
|
<section class="preview" aria-label="清理预览">
|
|
752
752
|
<h2>预览</h2>
|
|
753
753
|
${e.projects.length===0?l`<p class="empty">没有会话匹配这些阈值。</p>`:l`
|
|
@@ -787,7 +787,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
787
787
|
<h2>清理完成</h2>
|
|
788
788
|
<p>已归档 ${e.archivedSessionIds.length} 个会话;已永久删除 ${e.deletedSessionIds.length} 个已归档会话。</p>
|
|
789
789
|
</section>
|
|
790
|
-
`}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:
|
|
790
|
+
`}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:jn(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:sc(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=ni(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=ni(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!_n({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!qi(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!Fg(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};te.styles=D`
|
|
791
791
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
792
792
|
.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; }
|
|
793
793
|
section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -837,10 +837,10 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
837
837
|
table { min-width: 560px; }
|
|
838
838
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
839
839
|
}
|
|
840
|
-
`;pe([c({type:Boolean})],te.prototype,"canCleanup",2);pe([c({type:String})],te.prototype,"unavailableMessage",2);pe([c({attribute:!1})],te.prototype,"preview",2);pe([c({attribute:!1})],te.prototype,"previewRequest",2);pe([c({attribute:!1})],te.prototype,"result",2);pe([c({type:Boolean})],te.prototype,"loading",2);pe([c({type:Boolean})],te.prototype,"running",2);pe([c({type:String})],te.prototype,"error",2);pe([c({attribute:!1})],te.prototype,"onPreview",2);pe([c({attribute:!1})],te.prototype,"onRun",2);pe([c({attribute:!1})],te.prototype,"onClose",2);pe([v()],te.prototype,"draft",2);pe([v()],te.prototype,"formError",2);pe([v()],te.prototype,"selectedProjectCwds",2);te=pe([W("session-cleanup-dialog")],te);function tr(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function la(e){return e.target instanceof HTMLInputElement?e.target.value:""}const uo={CHILD:2,ELEMENT:6},fo=e=>(...t)=>({_$litDirective$:e,values:t});let go=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:Lb}=Wd,ca=e=>e,da=()=>document.createComment(""),Yt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(da(),r),n=s.insertBefore(da(),r);i=new Lb(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let d;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(d=e._$AU)!==n._$AU&&i._$AP(d)}if(o!==r||a){let d=i._$AA;for(;d!==o;){const p=ca(d).nextSibling;ca(s).insertBefore(d,r),d=p}}}return i},vt=(e,t,i=e)=>(e._$AI(t,i),e),Ob={},Fb=(e,t=Ob)=>e._$AH=t,_b=e=>e._$AH,ir=e=>{e._$AR(),e._$AA.remove()};const pa=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},jb=fo(class extends go{constructor(e){if(super(e),e.type!==uo.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 r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=_b(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],d=[];let p,u,h=0,g=r.length-1,S=0,P=o.length-1;for(;h<=g&&S<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[S])d[S]=vt(r[h],o[S]),h++,S++;else if(a[g]===n[P])d[P]=vt(r[g],o[P]),g--,P--;else if(a[h]===n[P])d[P]=vt(r[h],o[P]),Yt(e,d[P+1],r[h]),h++,P--;else if(a[g]===n[S])d[S]=vt(r[g],o[S]),Yt(e,r[h],r[g]),g--,S++;else if(p===void 0&&(p=pa(n,S,P),u=pa(a,h,g)),p.has(a[h]))if(p.has(a[g])){const C=u.get(n[S]),X=C!==void 0?r[C]:null;if(X===null){const ot=Yt(e,r[h]);vt(ot,o[S]),d[S]=ot}else d[S]=vt(X,o[S]),Yt(e,r[h],X),r[C]=null;S++}else ir(r[g]),g--;else ir(r[h]),h++;for(;S<=P;){const C=Yt(e,d[P+1]);vt(C,o[S]),d[S++]=C}for(;h<=g;){const C=r[h++];C!==null&&ir(C)}return this.ut=n,Fb(e,d),ct}}),Ub="pi-web:chat-groups:",Bb={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(ha(e));return t===null||t===""?void 0:Nb(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(ha(e),JSON.stringify(t))}catch{}}};class zb{constructor(t=Bb){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 r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&ua(o,this.openGroupKeys)&&ua(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,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 ha(e){return`${Ub}${e}`}function Nb(e){if(Array.isArray(e))return{open:sr(e),closedDefaultOpen:[]};if(qb(e))return{open:Array.isArray(e.open)?sr(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?sr(e.closedDefaultOpen):[]}}function sr(e){return e.filter(t=>typeof t=="string")}function ua(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function qb(e){return typeof e=="object"&&e!==null}function Hb(e,t=0){const i=[];let s=[],r=0;const o=(a,d)=>{s.length||(r=d),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,d)=>{const p=a.parts.filter(S=>fa(a,S)),u=a.parts.filter(S=>!fa(a,S)),h=t+d,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const S=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:S,parts:p,...g},index:h})}}),n(),i}function Kb(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${Vb(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Vb(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function fa(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")}async function mo(e,t=Gb()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function Gb(){const e=i=>Jb(i),t=Qb();return t===void 0?{isSecureContext:ga(),fallbackWriteText:e}:{isSecureContext:ga(),writeText:t,fallbackWriteText:e}}function ga(){return typeof window<"u"&&window.isSecureContext}function Qb(){if(!(typeof navigator>"u"||!("clipboard"in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function Jb(e){if(typeof document>"u")return!1;const t=document.activeElement,i=document.getSelection(),s=i===null?[]:Zb(i),r=document.createElement("textarea");r.value=e,r.readOnly=!0,r.setAttribute("aria-hidden","true"),r.style.position="fixed",r.style.top="0",r.style.left="-9999px",r.style.width="1px",r.style.height="1px",r.style.padding="0",r.style.border="0",r.style.opacity="0",r.style.pointerEvents="none",document.body.append(r),r.focus(),r.select(),r.setSelectionRange(0,r.value.length);try{return document.execCommand("copy")}catch{return!1}finally{r.remove(),Xb(i,s),Yb(t)}}function Zb(e){const t=[];for(let i=0;i<e.rangeCount;i+=1)t.push(e.getRangeAt(i));return t}function Xb(e,t){if(e!==null)try{e.removeAllRanges();for(const i of t)e.addRange(i)}catch{}}function Yb(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}const ew=30;function tw(e,t){const i=sw(nw(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function iw(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=rw(s,t.markerOffset);return}e.scrollTop=ow(e.scrollHeight,t.distanceFromBottom)}function sw(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function rw(e,t){return e-t}function ow(e,t){return Math.max(0,e-t)}function nw(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const aw=600,lw=1;function cw(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:dw(e)||pw(e)}function dw(e){return e.scrollTop<(e.topThreshold??Math.max(aw,e.clientHeight))}function pw(e){return e.scrollHeight<=e.clientHeight+lw}const hw="pi-web:chat-scroll:",uw=180,fw=48,gw=2,mw={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)}},vw={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class bw{constructor(t=mw,i=vw){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=uw){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=gw){if(t===""||i===void 0||!or(i))return"skipped";try{if($c(i,r)){const a={mode:"bottom"};return this.storage.setItem(rr(t),JSON.stringify(a)),"saved"}const o=Sw(i,s);if(o===void 0)return"skipped";const n=yw(i,o);return this.storage.setItem(rr(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!or(i))return{status:"skipped"};const o=xw(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(rr(t));if(i===null||i==="")return;const s=JSON.parse(i);return ww(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!or(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function rr(e){return`${hw}${e}`}function ww(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 or(e){return e.clientHeight>0&&e.scrollHeight>0}function kc(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function $c(e,t=fw){return kc(e)<t}function yw(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:vo(t)??"",offset:t.getBoundingClientRect().top-i}}function Sw(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(vo(a)===void 0)continue;const d=a.getBoundingClientRect();if(d.bottom<=d.top||d.bottom<i.top||d.top>i.bottom)continue;const p=d.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function ma(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function xw(e,t){return e.find(i=>vo(i)===t)}function vo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}const kw=D`
|
|
840
|
+
`;pe([c({type:Boolean})],te.prototype,"canCleanup",2);pe([c({type:String})],te.prototype,"unavailableMessage",2);pe([c({attribute:!1})],te.prototype,"preview",2);pe([c({attribute:!1})],te.prototype,"previewRequest",2);pe([c({attribute:!1})],te.prototype,"result",2);pe([c({type:Boolean})],te.prototype,"loading",2);pe([c({type:Boolean})],te.prototype,"running",2);pe([c({type:String})],te.prototype,"error",2);pe([c({attribute:!1})],te.prototype,"onPreview",2);pe([c({attribute:!1})],te.prototype,"onRun",2);pe([c({attribute:!1})],te.prototype,"onClose",2);pe([v()],te.prototype,"draft",2);pe([v()],te.prototype,"formError",2);pe([v()],te.prototype,"selectedProjectCwds",2);te=pe([W("session-cleanup-dialog")],te);function tr(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function aa(e){return e.target instanceof HTMLInputElement?e.target.value:""}const co={CHILD:2,ELEMENT:6},po=e=>(...t)=>({_$litDirective$:e,values:t});let ho=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:Tb}=Fd,la=e=>e,ca=()=>document.createComment(""),Yt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(ca(),r),n=s.insertBefore(ca(),r);i=new Tb(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let d;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(d=e._$AU)!==n._$AU&&i._$AP(d)}if(o!==r||a){let d=i._$AA;for(;d!==o;){const p=la(d).nextSibling;la(s).insertBefore(d,r),d=p}}}return i},vt=(e,t,i=e)=>(e._$AI(t,i),e),Eb={},Db=(e,t=Eb)=>e._$AH=t,Wb=e=>e._$AH,ir=e=>{e._$AR(),e._$AA.remove()};const da=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Lb=po(class extends ho{constructor(e){if(super(e),e.type!==co.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 r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=Wb(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],d=[];let p,u,h=0,g=r.length-1,S=0,P=o.length-1;for(;h<=g&&S<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[S])d[S]=vt(r[h],o[S]),h++,S++;else if(a[g]===n[P])d[P]=vt(r[g],o[P]),g--,P--;else if(a[h]===n[P])d[P]=vt(r[h],o[P]),Yt(e,d[P+1],r[h]),h++,P--;else if(a[g]===n[S])d[S]=vt(r[g],o[S]),Yt(e,r[h],r[g]),g--,S++;else if(p===void 0&&(p=da(n,S,P),u=da(a,h,g)),p.has(a[h]))if(p.has(a[g])){const C=u.get(n[S]),X=C!==void 0?r[C]:null;if(X===null){const ot=Yt(e,r[h]);vt(ot,o[S]),d[S]=ot}else d[S]=vt(X,o[S]),Yt(e,r[h],X),r[C]=null;S++}else ir(r[g]),g--;else ir(r[h]),h++;for(;S<=P;){const C=Yt(e,d[P+1]);vt(C,o[S]),d[S++]=C}for(;h<=g;){const C=r[h++];C!==null&&ir(C)}return this.ut=n,Db(e,d),ct}}),Ob="pi-web:chat-groups:",Fb={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(pa(e));return t===null||t===""?void 0:jb(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(pa(e),JSON.stringify(t))}catch{}}};class _b{constructor(t=Fb){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 r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&ha(o,this.openGroupKeys)&&ha(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,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 pa(e){return`${Ob}${e}`}function jb(e){if(Array.isArray(e))return{open:sr(e),closedDefaultOpen:[]};if(Ub(e))return{open:Array.isArray(e.open)?sr(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?sr(e.closedDefaultOpen):[]}}function sr(e){return e.filter(t=>typeof t=="string")}function ha(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Ub(e){return typeof e=="object"&&e!==null}function Bb(e,t=0){const i=[];let s=[],r=0;const o=(a,d)=>{s.length||(r=d),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,d)=>{const p=a.parts.filter(S=>ua(a,S)),u=a.parts.filter(S=>!ua(a,S)),h=t+d,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const S=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:S,parts:p,...g},index:h})}}),n(),i}function zb(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${Nb(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Nb(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function ua(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")}async function uo(e,t=qb()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function qb(){const e=i=>Kb(i),t=Hb();return t===void 0?{isSecureContext:fa(),fallbackWriteText:e}:{isSecureContext:fa(),writeText:t,fallbackWriteText:e}}function fa(){return typeof window<"u"&&window.isSecureContext}function Hb(){if(!(typeof navigator>"u"||!("clipboard"in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function Kb(e){if(typeof document>"u")return!1;const t=document.activeElement,i=document.getSelection(),s=i===null?[]:Vb(i),r=document.createElement("textarea");r.value=e,r.readOnly=!0,r.setAttribute("aria-hidden","true"),r.style.position="fixed",r.style.top="0",r.style.left="-9999px",r.style.width="1px",r.style.height="1px",r.style.padding="0",r.style.border="0",r.style.opacity="0",r.style.pointerEvents="none",document.body.append(r),r.focus(),r.select(),r.setSelectionRange(0,r.value.length);try{return document.execCommand("copy")}catch{return!1}finally{r.remove(),Gb(i,s),Qb(t)}}function Vb(e){const t=[];for(let i=0;i<e.rangeCount;i+=1)t.push(e.getRangeAt(i));return t}function Gb(e,t){if(e!==null)try{e.removeAllRanges();for(const i of t)e.addRange(i)}catch{}}function Qb(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}const Jb=30;function Zb(e,t){const i=Yb(iw(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Xb(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ew(s,t.markerOffset);return}e.scrollTop=tw(e.scrollHeight,t.distanceFromBottom)}function Yb(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function ew(e,t){return e-t}function tw(e,t){return Math.max(0,e-t)}function iw(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const sw=600,rw=1;function ow(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:nw(e)||aw(e)}function nw(e){return e.scrollTop<(e.topThreshold??Math.max(sw,e.clientHeight))}function aw(e){return e.scrollHeight<=e.clientHeight+rw}const lw="pi-web:chat-scroll:",cw=180,dw=48,pw=2,hw={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)}},uw={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class fw{constructor(t=hw,i=uw){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=cw){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=pw){if(t===""||i===void 0||!or(i))return"skipped";try{if(Rc(i,r)){const a={mode:"bottom"};return this.storage.setItem(rr(t),JSON.stringify(a)),"saved"}const o=vw(i,s);if(o===void 0)return"skipped";const n=mw(i,o);return this.storage.setItem(rr(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!or(i))return{status:"skipped"};const o=bw(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(rr(t));if(i===null||i==="")return;const s=JSON.parse(i);return gw(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!or(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function rr(e){return`${lw}${e}`}function gw(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 or(e){return e.clientHeight>0&&e.scrollHeight>0}function Cc(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Rc(e,t=dw){return Cc(e)<t}function mw(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:fo(t)??"",offset:t.getBoundingClientRect().top-i}}function vw(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(fo(a)===void 0)continue;const d=a.getBoundingClientRect();if(d.bottom<=d.top||d.bottom<i.top||d.top>i.bottom)continue;const p=d.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function ga(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function bw(e,t){return e.find(i=>fo(i)===t)}function fo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}const ww=D`
|
|
841
841
|
:host { position: relative; z-index: 0; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; max-height: 100%; overflow: hidden; contain: size layout; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
842
842
|
.chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
|
|
843
|
-
.chat {
|
|
843
|
+
.chat { position: absolute; inset: 0; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
|
|
844
844
|
.scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
|
|
845
845
|
.activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
|
|
846
846
|
.activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
|
|
@@ -926,7 +926,7 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
926
926
|
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
927
927
|
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
|
|
928
928
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
929
|
-
`;var
|
|
929
|
+
`;var yw=Object.defineProperty,Sw=Object.getOwnPropertyDescriptor,go=(e,t,i,s)=>{for(var r=s>1?void 0:s?Sw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yw(t,i,r),r};let mi=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=ma(this.positionPercent),t=ma(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
|
|
930
930
|
<div
|
|
931
931
|
class="meter"
|
|
932
932
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -949,12 +949,12 @@ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?
|
|
|
949
949
|
.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); }
|
|
950
950
|
.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)); }
|
|
951
951
|
.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%); }
|
|
952
|
-
`;
|
|
953
|
-
]`).replace("lheading",
|
|
952
|
+
`;go([c({type:Number})],mi.prototype,"positionPercent",2);go([c({type:Number})],mi.prototype,"loadedPercent",2);mi=go([W("conversation-meter")],mi);function ma(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Cr extends ho{constructor(t){if(super(t),this.it=B,t.type!==co.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===B||t==null)return this._t=void 0,this.it=t;if(t===ct)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:[]}}}Cr.directiveName="unsafeHTML",Cr.resultType=1;const xw=po(Cr);function mo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Rt=mo();function Ic(e){Rt=e}var wt={exec:()=>null};function Et(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function E(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(re.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var kw=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),re={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:Et(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Et(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Et(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Et(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Et(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Et(e=>new RegExp(`^ {0,${e}}>`))},$w=/^(?:[ \t]*(?:\n|$))+/,Pw=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Cw=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Rw=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,vo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ac=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Mc=E(Ac).replace(/bull/g,vo).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(),Iw=E(Ac).replace(/bull/g,vo).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(),bo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Aw=/^[^\n]+/,wo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mw=E(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Tw=E(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,vo).getRegex(),Es="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",yo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ew=E("^ {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",yo).replace("tag",Es).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Tc=E(bo).replace("hr",xi).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",Es).getRegex(),Dw=E(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Tc).getRegex(),So={blockquote:Dw,code:Pw,def:Mw,fences:Cw,heading:Rw,hr:xi,html:Ew,lheading:Mc,list:Tw,newline:$w,paragraph:Tc,table:wt,text:Aw},va=E("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xi).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",Es).getRegex(),Ww={...So,lheading:Iw,table:va,paragraph:E(bo).replace("hr",xi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",va).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",Es).getRegex()},Lw={...So,html:E(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",yo).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:wt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:E(bo).replace("hr",xi).replace("heading",` *#{1,6} *[^
|
|
953
|
+
]`).replace("lheading",Mc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ow=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Fw=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ec=/^( {2,}|\\)\n(?!\s*$)/,_w=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,qt=/[\p{P}\p{S}]/u,Ds=/[\s\p{P}\p{S}]/u,xo=/[^\s\p{P}\p{S}]/u,jw=E(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ds).getRegex(),Dc=/(?!~)[\p{P}\p{S}]/u,Uw=/(?!~)[\s\p{P}\p{S}]/u,Bw=/(?:[^\s\p{P}\p{S}]|~)/u,zw=E(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",kw?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Wc=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Nw=E(Wc,"u").replace(/punct/g,qt).getRegex(),qw=E(Wc,"u").replace(/punct/g,Dc).getRegex(),Lc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Hw=E(Lc,"gu").replace(/notPunctSpace/g,xo).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),Kw=E(Lc,"gu").replace(/notPunctSpace/g,Bw).replace(/punctSpace/g,Uw).replace(/punct/g,Dc).getRegex(),Vw=E("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,xo).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),Gw=E(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,qt).getRegex(),Qw="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Jw=E(Qw,"gu").replace(/notPunctSpace/g,xo).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),Zw=E(/\\(punct)/,"gu").replace(/punct/g,qt).getRegex(),Xw=E(/^<(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(),Yw=E(yo).replace("(?:-->|$)","-->").getRegex(),ey=E("^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",Yw).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ds=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ty=E(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ds).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Oc=E(/^!?\[(label)\]\[(ref)\]/).replace("label",ds).replace("ref",wo).getRegex(),Fc=E(/^!?\[(ref)\](?:\[\])?/).replace("ref",wo).getRegex(),iy=E("reflink|nolink(?!\\()","g").replace("reflink",Oc).replace("nolink",Fc).getRegex(),ba=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ko={_backpedal:wt,anyPunctuation:Zw,autolink:Xw,blockSkip:zw,br:Ec,code:Fw,del:wt,delLDelim:wt,delRDelim:wt,emStrongLDelim:Nw,emStrongRDelimAst:Hw,emStrongRDelimUnd:Vw,escape:Ow,link:ty,nolink:Fc,punctuation:jw,reflink:Oc,reflinkSearch:iy,tag:ey,text:_w,url:wt},sy={...ko,link:E(/^!?\[(label)\]\((.*?)\)/).replace("label",ds).getRegex(),reflink:E(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ds).getRegex()},Rr={...ko,emStrongRDelimAst:Kw,emStrongLDelim:qw,delLDelim:Gw,delRDelim:Jw,url:E(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ba).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:E(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ba).getRegex()},ry={...Rr,br:E(Ec).replace("{2,}","*").getRegex(),text:E(Rr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:So,gfm:Ww,pedantic:Lw},ei={normal:ko,gfm:Rr,breaks:ry,pedantic:sy},oy={"&":"&","<":"<",">":">",'"':""","'":"'"},wa=e=>oy[e];function ze(e,t){if(t){if(re.escapeTest.test(e))return e.replace(re.escapeReplace,wa)}else if(re.escapeTestNoEncode.test(e))return e.replace(re.escapeReplaceNoEncode,wa);return e}function ya(e){try{e=encodeURI(e).replace(re.percentDecode,"%")}catch{return null}return e}function Sa(e,t){let i=e.replace(re.findPipe,(o,n,a)=>{let d=!1,p=n;for(;--p>=0&&a[p]==="\\";)d=!d;return d?"|":" |"}),s=i.split(re.splitPipe),r=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(;r<s.length;r++)s[r]=s[r].trim().replace(re.slashPipe,"|");return s}function nt(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function xa(e){let t=e.split(`
|
|
954
954
|
`),i=t.length-1;for(;i>=0&&re.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
|
|
955
|
-
`)}function
|
|
955
|
+
`)}function ny(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 ay(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function ka(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let d={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,d}function ly(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
|
|
956
956
|
`).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
|
|
957
|
-
`)}var ps=class{options;rules;lexer;constructor(e){this.options=e||
|
|
957
|
+
`)}var ps=class{options;rules;lexer;constructor(e){this.options=e||Rt}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]:xa(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=ly(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=nt(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:nt(t[0],`
|
|
958
958
|
`),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:nt(t[0],`
|
|
959
959
|
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=nt(t[0],`
|
|
960
960
|
`).split(`
|
|
@@ -967,19 +967,19 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
967
967
|
`),C=this.blockquote(P);o[o.length-1]=C,s=s.substring(0,s.length-S.raw.length)+C.raw,r=r.substring(0,r.length-S.text.length)+C.text;break}else if(g?.type==="list"){let S=g,P=S.raw+`
|
|
968
968
|
`+i.join(`
|
|
969
969
|
`),C=this.list(P);o[o.length-1]=C,s=s.substring(0,s.length-g.raw.length)+C.raw,r=r.substring(0,r.length-S.raw.length)+C.raw,i=P.substring(o.at(-1).raw.length).split(`
|
|
970
|
-
`);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={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 o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let d=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=
|
|
970
|
+
`);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={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 o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let d=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=ay(t[2].split(`
|
|
971
971
|
`,1)[0],t[1].length),g=e.split(`
|
|
972
972
|
`,1)[0],S=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):S?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),S&&this.rules.other.blankLine.test(g)&&(p+=g+`
|
|
973
|
-
`,e=e.substring(g.length+1),d=!0),!d){let C=this.rules.other.nextBulletRegex(P),X=this.rules.other.hrRegex(P),ot=this.rules.other.fencesBeginRegex(P),
|
|
974
|
-
`,1)[0],Ht;if(g=Fs,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Ht=g):Ht=g.replace(this.rules.other.tabCharGlobal," "),ot.test(g)||
|
|
975
|
-
`+Ht.slice(P);else{if(S||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ot.test(h)||
|
|
973
|
+
`,e=e.substring(g.length+1),d=!0),!d){let C=this.rules.other.nextBulletRegex(P),X=this.rules.other.hrRegex(P),ot=this.rules.other.fencesBeginRegex(P),Io=this.rules.other.headingBeginRegex(P),rd=this.rules.other.htmlBeginRegex(P),od=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Fs=e.split(`
|
|
974
|
+
`,1)[0],Ht;if(g=Fs,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Ht=g):Ht=g.replace(this.rules.other.tabCharGlobal," "),ot.test(g)||Io.test(g)||rd.test(g)||od.test(g)||C.test(g)||X.test(g))break;if(Ht.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
|
|
975
|
+
`+Ht.slice(P);else{if(S||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ot.test(h)||Io.test(h)||X.test(h))break;u+=`
|
|
976
976
|
`+g}S=!g.trim(),p+=Fs+`
|
|
977
|
-
`,e=e.substring(Fs.length+1),h=Ht.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let d of r.items){this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]);let p=d.tokens[0];if(d.task&&(p?.type==="text"||p?.type==="paragraph")){d.text=d.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(d.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};d.checked=h.checked,r.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=h.raw+d.tokens[0].raw,d.tokens[0].text=h.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(h)):d.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):d.tokens.unshift(h)}}else d.task&&(d.task=!1);if(!r.loose){let u=d.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let d of r.items){d.loose=!0;for(let p of d.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=
|
|
978
|
-
`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=
|
|
977
|
+
`,e=e.substring(Fs.length+1),h=Ht.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let d of r.items){this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]);let p=d.tokens[0];if(d.task&&(p?.type==="text"||p?.type==="paragraph")){d.text=d.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(d.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};d.checked=h.checked,r.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=h.raw+d.tokens[0].raw,d.tokens[0].text=h.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(h)):d.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):d.tokens.unshift(h)}}else d.task&&(d.task=!1);if(!r.loose){let u=d.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let d of r.items){d.loose=!0;for(let p of d.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=xa(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"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:nt(t[0],`
|
|
978
|
+
`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Sa(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
979
979
|
`):[],o={type:"table",raw:nt(t[0],`
|
|
980
|
-
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(
|
|
980
|
+
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(Sa(n,o.header.length).map((a,d)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[d]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:nt(t[0],`
|
|
981
981
|
`),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)===`
|
|
982
|
-
`?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 o=nt(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=
|
|
982
|
+
`?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 o=nt(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=ny(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=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)),ka(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.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," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return ka(i,r,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 r=[...s[0]].length-1,o,n,a=r,d=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){d+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+d);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let S=h.slice(1,-1);return{type:"em",raw:h,text:S,tokens:this.lexer.inlineTokens(S)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}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),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(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 r=[...s[0]].length-1,o,n,a=r,d=this.rules.inline.delRDelim;for(d.lastIndex=0,t=t.slice(-1*e.length+r);(s=d.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))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,r+s.index+p+n),h=u.slice(r,-r);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 r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==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}}}},Oe=class Ir{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Rt,this.options.tokenizer=this.options.tokenizer||new ps,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:re,block:Mi.normal,inline:ei.normal};this.options.pedantic?(i.block=Mi.pedantic,i.inline=ei.pedantic):this.options.gfm&&(i.block=Mi.gfm,this.options.breaks?i.inline=ei.breaks:i.inline=ei.gfm),this.tokenizer.rules=i}static get rules(){return{block:Mi,inline:ei}}static lex(t,i){return new Ir(i).lex(t)}static lexInline(t,i){return new Ir(i).inlineTokens(t)}lex(t){t=t.replace(re.carriageReturn,`
|
|
983
983
|
`),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(re.tabCharGlobal," ").replace(re.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
|
|
984
984
|
`:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
985
985
|
`)?"":`
|
|
@@ -993,7 +993,7 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
993
993
|
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
994
994
|
`)?"":`
|
|
995
995
|
`)+o.raw,a.text+=`
|
|
996
|
-
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);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,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",d=1/0;for(;t;){if(t.length<d)d=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,g=t.slice(1),S;this.options.extensions.startInline.forEach(P=>{S=P.call({lexer:this},g),typeof S=="number"&&S>=0&&(h=Math.min(h,S))}),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)}},hs=class{options;parser;constructor(e){this.options=e||
|
|
996
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);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,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",d=1/0;for(;t;){if(t.length<d)d=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,g=t.slice(1),S;this.options.extensions.startInline.forEach(P=>{S=P.call({lexer:this},g),typeof S=="number"&&S>=0&&(h=Math.min(h,S))}),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)}},hs=class{options;parser;constructor(e){this.options=e||Rt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(re.notSpaceStart)?.[0],r=e.replace(re.endingNewline,"")+`
|
|
997
997
|
`;return s?'<pre><code class="language-'+ze(s)+'">'+(i?r:ze(r,!0))+`</code></pre>
|
|
998
998
|
`:"<pre><code>"+(i?r:ze(r,!0))+`</code></pre>
|
|
999
999
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
@@ -1011,8 +1011,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
1011
1011
|
`}tablerow({text:e}){return`<tr>
|
|
1012
1012
|
${e}</tr>
|
|
1013
1013
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
|
|
1014
|
-
`}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>${ze(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),r=
|
|
1015
|
-
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+ze(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}}
|
|
1014
|
+
`}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>${ze(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),r=ya(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+ze(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=ya(e);if(r===null)return ze(i);e=r;let o=`<img src="${e}" alt="${ze(i)}"`;return t&&(o+=` title="${ze(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ze(e.text)}},$o=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}},Fe=class Ar{options;renderer;textRenderer;constructor(t){this.options=t||Rt,this.options.renderer=this.options.renderer||new hs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new $o}static parse(t,i){return new Ar(i).parse(t)}static parseInline(t,i){return new Ar(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,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 o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.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 r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;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}},ai=class{options;block;constructor(e){this.options=e||Rt}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?Oe.lex:Oe.lexInline}provideParser(e=this.block){return e?Fe.parse:Fe.parseInline}},cy=class{defaults=mo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fe;Renderer=hs;TextRenderer=$o;Lexer=Oe;Tokenizer=ps;Hooks=ai;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 r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.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(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new hs(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],d=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=d.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new ps(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],d=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=d.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new ai;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],d=r[n];ai.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&ai.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return d.call(r,h)})();let u=a.call(r,p);return d.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await d.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=d.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Oe.lex(e,t??this.defaults)}parser(e,t){return Fe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Oe.lex:Oe.lexInline)(n,r),d=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(d,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Fe.parse:Fe.parseInline)(d,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Oe.lex:Oe.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Fe.parse:Fe.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
|
|
1015
|
+
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+ze(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Pt=new cy;function O(e,t){return Pt.parse(e,t)}O.options=O.setOptions=function(e){return Pt.setOptions(e),O.defaults=Pt.defaults,Ic(O.defaults),O};O.getDefaults=mo;O.defaults=Rt;O.use=function(...e){return Pt.use(...e),O.defaults=Pt.defaults,Ic(O.defaults),O};O.walkTokens=function(e,t){return Pt.walkTokens(e,t)};O.parseInline=Pt.parseInline;O.Parser=Fe;O.parser=Fe.parse;O.Renderer=hs;O.TextRenderer=$o;O.Lexer=Oe;O.lexer=Oe.lex;O.Tokenizer=ps;O.Hooks=ai;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Fe.parse;Oe.lex;const _c=new O.Renderer;_c.html=({text:e})=>hy(e);const dy=300,ti=new Map;function py(e){const t=ti.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:_c}),s=uy(i);if(ti.set(e,s),ti.size>dy){const r=ti.keys().next().value;r!==void 0&&ti.delete(r)}return s}function hy(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function uy(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 r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!fy(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function fy(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var gy=Object.defineProperty,my=Object.getOwnPropertyDescriptor,jc=(e,t,i,s)=>{for(var r=s>1?void 0:s?my(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gy(t,i,r),r};const vy=D`
|
|
1016
1016
|
:host { display: block; }
|
|
1017
1017
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
1018
1018
|
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -1037,18 +1037,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1037
1037
|
table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
|
|
1038
1038
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
1039
1039
|
th { background: var(--pi-surface); }
|
|
1040
|
-
`;let us=class extends I{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" dir="auto" @click=${this.onFormattedClick}>${
|
|
1040
|
+
`;let us=class extends I{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" dir="auto" @click=${this.onFormattedClick}>${xw(py(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="复制代码块",s.setAttribute("aria-label","复制代码块");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await uo(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"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};us.styles=vy;jc([c()],us.prototype,"text",2);us=jc([W("formatted-text")],us);var by=Object.defineProperty,wy=Object.getOwnPropertyDescriptor,ki=(e,t,i,s)=>{for(var r=s>1?void 0:s?wy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&by(t,i,r),r};const $a=180;let Ct=class extends I{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=Sy(e.args),i=xy(e.details),s=e.preview,r=i??s?.diff,o=r===void 0?void 0:ky(r),n=i!==void 0&&s?.diff!==void 0&&i!==s.diff,a=e.status==="error"?e.resultText:s?.error,d=r===void 0?e.resultText:void 0,p=yy(e,t);return l`
|
|
1041
1041
|
<section class=${`tool-card ${e.status}`}>
|
|
1042
1042
|
<div class="tool-header">
|
|
1043
1043
|
<div class="tool-title">
|
|
1044
|
-
<span class="status-icon" aria-hidden="true">${
|
|
1044
|
+
<span class="status-icon" aria-hidden="true">${Py(e.status)}</span>
|
|
1045
1045
|
<strong>${e.toolName}</strong>
|
|
1046
1046
|
${this.renderHeaderTarget(p)}
|
|
1047
1047
|
</div>
|
|
1048
1048
|
<div class="tool-meta">
|
|
1049
|
-
${
|
|
1049
|
+
${Pa(e)===void 0?null:l`<span>${Pa(e)}</span>`}
|
|
1050
1050
|
${o===void 0?null:l`<span class="diff-stats"><b class="added">+${o.added}</b><span>/</span><b class="removed">-${o.removed}</b></span>`}
|
|
1051
|
-
<span class="status-label">${
|
|
1051
|
+
<span class="status-label">${Cy(e.status)}</span>
|
|
1052
1052
|
</div>
|
|
1053
1053
|
</div>
|
|
1054
1054
|
|
|
@@ -1073,7 +1073,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1073
1073
|
`}
|
|
1074
1074
|
</details>
|
|
1075
1075
|
`}renderDiffBody(e,t,i){const s=e.split(`
|
|
1076
|
-
`),r=!this.showFullDiff&&s.length
|
|
1076
|
+
`),r=!this.showFullDiff&&s.length>$a,o=r?s.slice(0,$a):s;return l`
|
|
1077
1077
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${n=>{this.onDiffToggle(n)}}>
|
|
1078
1078
|
<summary>
|
|
1079
1079
|
<span>${t}</span>
|
|
@@ -1084,14 +1084,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1084
1084
|
<span>${r?`显示 ${String(o.length)} / ${String(s.length)} 行`:"完整 diff"}</span>
|
|
1085
1085
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
|
|
1086
1086
|
</div>
|
|
1087
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(n=>l`<span class=${
|
|
1087
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(n=>l`<span class=${$y(n)}>${n}</span>`)}</code></pre>
|
|
1088
1088
|
${r?l`
|
|
1089
1089
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
1090
1090
|
显示全部 ${String(s.length)} 行 diff
|
|
1091
1091
|
</button>
|
|
1092
1092
|
`:null}
|
|
1093
1093
|
</details>
|
|
1094
|
-
`}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await
|
|
1094
|
+
`}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await uo(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}};Ct.styles=D`
|
|
1095
1095
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
1096
1096
|
.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); }
|
|
1097
1097
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -1135,19 +1135,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1135
1135
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
1136
1136
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
1137
1137
|
.show-more { justify-self: start; }
|
|
1138
|
-
`;ki([c({attribute:!1})],
|
|
1139
|
-
`))
|
|
1138
|
+
`;ki([c({attribute:!1})],Ct.prototype,"execution",2);ki([v()],Ct.prototype,"showFullDiff",2);ki([v()],Ct.prototype,"copied",2);ki([v()],Ct.prototype,"diffOpen",2);Ct=ki([W("tool-execution-view")],Ct);function yy(e,t){if(t!==void 0&&t!=="")return{label:"File",text:t};const i=fs(e.args,"command");if(i!==void 0&&i!=="")return{label:"Command",text:i};if(e.summary!=="")return{label:"Input",text:e.summary}}function Sy(e){return fs(e,"path")??fs(e,"file_path")}function Pa(e){if(e.toolName!=="edit")return;const t=Ki(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof Ki(e.args,"oldText")=="string"&&typeof Ki(e.args,"newText")=="string")return"1 处编辑"}function xy(e){return fs(e,"diff")}function ky(e){let t=0,i=0;for(const s of e.split(`
|
|
1139
|
+
`))Uc(s)?t++:Bc(s)&&i++;return{added:t,removed:i}}function $y(e){return Uc(e)?"added":Bc(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Uc(e){return e.startsWith("+")&&!e.startsWith("+++")}function Bc(e){return e.startsWith("-")&&!e.startsWith("---")}function Py(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Cy(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Ry(e){return typeof e=="object"&&e!==null}function Ki(e,t){return Ry(e)?e[t]:void 0}function fs(e,t){const i=Ki(e,t);return typeof i=="string"?i:void 0}var Iy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,H=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ay(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Iy(t,i,r),r};const My=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Ty=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),nr=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Ey={active:"活跃","agent running":"助手运行中","bash complete":"Shell 已完成","bash failed":"Shell 失败","compaction complete":"压缩已完成","compaction failed":"压缩失败",compacting:"正在压缩","duplicate queued message ignored":"已忽略重复排队消息",error:"错误",idle:"空闲","message complete":"消息已完成","message queued":"消息已排队","message queued during compaction":"压缩期间消息已排队","message started":"消息已开始","prompt accepted":"提示已接受",queued:"已排队","receiving response":"正在接收回复","running bash":"Shell 运行中","running tool":"工具运行中","steering queued":"引导已排队",stopped:"已停止","tool complete":"工具已完成","tool failed":"工具失败","turn complete":"回合已完成"};function Ca(){return nr[Math.floor(Math.random()*nr.length)]??nr[0]}function Ra(e){return Vi(e,0,100)}function Vi(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}function Dy(e,t){return[e.length===0?void 0:{heading:"等待会话启动",detail:"后端会话准备好后将自动发送",messages:e},t.length===0?void 0:{heading:"排队消息",detail:`${String(t.length)} 条待处理 · 停止会清空队列`,messages:t}].filter(i=>i!==void 0)}let N=class extends I{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.clientQueuedMessages=[],this.pinnedToBottom=!0,this.disclosures=new _b,this.scrollController=new fw,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`
|
|
1140
1140
|
<div class="chat-wrap">
|
|
1141
1141
|
${this.renderConversationRail()}
|
|
1142
1142
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
|
|
1143
1143
|
${this.renderHistoryBoundary()}
|
|
1144
|
-
${
|
|
1144
|
+
${Lb(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)))}
|
|
1145
1145
|
${this.renderQueuedMessages()}
|
|
1146
1146
|
${this.renderSessionActivity()}
|
|
1147
1147
|
</div>
|
|
1148
1148
|
${this.renderActivityDock()}
|
|
1149
1149
|
</div>
|
|
1150
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
1150
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Bb(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`
|
|
1151
1151
|
<div class="activity-dock active" aria-live="polite">
|
|
1152
1152
|
<span class="dot"></span>
|
|
1153
1153
|
<span class="activity-text">正在发送你的消息…</span>
|
|
@@ -1157,7 +1157,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1157
1157
|
<span class="dot"></span>
|
|
1158
1158
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
1159
1159
|
</div>
|
|
1160
|
-
`}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return l`${
|
|
1160
|
+
`}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return l`${Dy(this.clientQueuedMessages,e).map(t=>this.renderQueuedMessageList(t))}`}renderQueuedMessageList(e){return l`
|
|
1161
1161
|
<aside class="queued-messages" aria-live="polite">
|
|
1162
1162
|
<div class="queued-header">
|
|
1163
1163
|
<strong>${e.heading}</strong>
|
|
@@ -1166,7 +1166,6 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1166
1166
|
${e.messages.map((t,i)=>l`
|
|
1167
1167
|
<div class="queued-message">
|
|
1168
1168
|
<span class="queued-kind">${t.kind==="steer"?"引导":"跟进"} ${String(i+1)}</span>
|
|
1169
|
-
${t.imageCount!==void 0&&t.imageCount>0?l`<small>含 ${t.imageCount} 张图片</small>`:null}
|
|
1170
1169
|
<formatted-text .text=${t.text}></formatted-text>
|
|
1171
1170
|
</div>
|
|
1172
1171
|
`)}
|
|
@@ -1182,7 +1181,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1182
1181
|
<span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
|
|
1183
1182
|
${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
|
|
1184
1183
|
</aside>
|
|
1185
|
-
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?
|
|
1184
|
+
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Ca():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Ca(),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;if(t===void 0||e!=="idle"&&t.phase==="idle")return ar(e);const i=ar(t.label);return t.detail!==void 0&&t.detail!==""?`${i}: ${t.detail}`:i}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?Ra(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=Vi(this.currentConversationIndex??t,0,e-1);return Ra(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
|
|
1186
1185
|
<div class="history-boundary">
|
|
1187
1186
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
|
|
1188
1187
|
<span>向上滚动加载更早的消息</span>
|
|
@@ -1199,7 +1198,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1199
1198
|
<details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
|
|
1200
1199
|
<summary>
|
|
1201
1200
|
<b class="label">${s?"实时事件":"事件"}</b>
|
|
1202
|
-
<span>${
|
|
1201
|
+
<span>${zb(e)}</span>
|
|
1203
1202
|
</summary>
|
|
1204
1203
|
<div class="group-body">
|
|
1205
1204
|
${e.map((n,a)=>{const d=this.isToolExecutionOnlyMessage(n);return l`
|
|
@@ -1212,7 +1211,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1212
1211
|
</details>
|
|
1213
1212
|
`}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
|
|
1214
1213
|
<div class="msg-header">
|
|
1215
|
-
<b class="label">${
|
|
1214
|
+
<b class="label">${Ia(e.role)}</b>
|
|
1216
1215
|
<div class="msg-header-trailing">
|
|
1217
1216
|
${this.renderMessageActions(e,t)}
|
|
1218
1217
|
<span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
|
|
@@ -1220,13 +1219,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1220
1219
|
</div>
|
|
1221
1220
|
`}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
|
|
1222
1221
|
<div class="msg-actions" aria-label="消息操作">
|
|
1223
|
-
<button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${
|
|
1222
|
+
<button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Ia(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
|
|
1224
1223
|
<span aria-hidden="true">${i?"✓":"⧉"}</span>
|
|
1225
1224
|
</button>
|
|
1226
1225
|
</div>
|
|
1227
1226
|
`}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(`
|
|
1228
1227
|
|
|
1229
|
-
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await
|
|
1228
|
+
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await uo(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}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 d={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,d),d}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(d=>d!==void 0&&d!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(d=>d!==void 0&&d!==""),a={short:o.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:My.format(t),full:Ty.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==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
|
|
1230
1229
|
<details class="part skill-invocation">
|
|
1231
1230
|
<summary><b>[技能]</b> ${e.name}</summary>
|
|
1232
1231
|
<small>${e.location}</small>
|
|
@@ -1242,31 +1241,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1242
1241
|
<summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
|
|
1243
1242
|
<formatted-text .text=${e.text}></formatted-text>
|
|
1244
1243
|
</details>
|
|
1245
|
-
`: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&&
|
|
1244
|
+
`: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&&ow({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?Rc(e):!0}isAtBottom(){const e=this.chat;return e?Cc(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 Zb(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 r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(Xb(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Jb){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=Vi(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Vi(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 ga(e,t)??ga(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)}`}};N.styles=ww;H([c({attribute:!1})],N.prototype,"messages",2);H([c()],N.prototype,"sessionId",2);H([c({type:Number})],N.prototype,"messageStart",2);H([c({type:Number})],N.prototype,"messageEnd",2);H([c({type:Number})],N.prototype,"messageTotal",2);H([c({type:Boolean})],N.prototype,"hasMore",2);H([c({type:Boolean})],N.prototype,"loadingMore",2);H([c({type:Boolean})],N.prototype,"isReceivingPartialStream",2);H([c({type:Boolean})],N.prototype,"isSendingPrompt",2);H([c({type:Boolean})],N.prototype,"isCompacting",2);H([c({type:Number})],N.prototype,"pendingMessageCount",2);H([c({attribute:!1})],N.prototype,"clientQueuedMessages",2);H([c({attribute:!1})],N.prototype,"status",2);H([c({attribute:!1})],N.prototype,"activity",2);H([c({attribute:!1})],N.prototype,"onLoadMore",2);H([q(".chat")],N.prototype,"chat",2);H([v()],N.prototype,"pinnedToBottom",2);H([v()],N.prototype,"expandedMetaKey",2);H([v()],N.prototype,"copiedMessageKey",2);H([v()],N.prototype,"currentConversationIndex",2);H([v()],N.prototype,"loadMoreRequested",2);N=H([W("chat-view")],N);function Ia(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function ar(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Ey[e]??e}const Wy=["image/jpeg","image/png","image/gif","image/webp"],Ly=new Set(Wy);function Po(e){return typeof e=="string"&&Ly.has(e)}function Oy(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 Fy="application/octet-stream",_y="读取附件失败。";async function jy(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(By(r,o))}catch{s=_y}return{attachments:i,...s===void 0?{}:{error:s}}}function Mr(e){return e.kind==="image"&&Po(e.mimeType)}function Tr(e){return e.every(t=>Mr(t))}function Uy(e,t){return Tr(t)?e:"folder"}function By(e,t){return Po(e.type)?{kind:"image",name:Aa(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:Aa(e),mimeType:zy(e),data:t,size:e.size}}function zy(e){const t=e.type.trim();return t===""?Fy:t}function Aa(e){return e.name!==""?e.name:Po(e.type)?`pasted-image.${Oy(e.type)}`:"pasted-file.bin"}const zc="pi-web:attachment-delivery";function Nc(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ny(e=Nc()){try{return e?.getItem(zc)==="folder"?"folder":"inline"}catch{return"inline"}}function qy(e,t=Nc()){try{t?.setItem(zc,e)}catch{}}const Hy="(pointer: coarse), (max-width: 760px)",qc="pi-web.promptEnterPreference";function Ws(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(Hy):void 0}function Ky(e){return e==="send"||e==="newline"?e:"auto"}function Ls(e=Hc()){if(e===void 0)return"auto";try{return Ky(e.getItem(qc))}catch{return"auto"}}function Vy(e,t=Hc()){if(t!==void 0)try{t.setItem(qc,e)}catch{}}function Gy(e=Ws(),t=Ls()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Qy(e,t,i=Ws()){return e?i?.matches===!0?t:!0:!1}function Jy(e,t=Ws(),i=Ls()){const s=Gy(t,i);return e?!s:s}function Hc(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Zy(){return $e`
|
|
1246
1245
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1247
1246
|
<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>
|
|
1248
1247
|
</svg>
|
|
1249
|
-
`}function
|
|
1248
|
+
`}function Kc(){return $e`
|
|
1250
1249
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1251
1250
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
1252
1251
|
<path d="M21 3 11.5 12.5"></path>
|
|
1253
1252
|
</svg>
|
|
1254
|
-
`}function
|
|
1253
|
+
`}function Xy(){return $e`
|
|
1255
1254
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1256
1255
|
<path d="M4 7h11"></path>
|
|
1257
1256
|
<path d="M4 12h7"></path>
|
|
1258
1257
|
<path d="M4 17h7"></path>
|
|
1259
1258
|
<path d="m15 14 5 3-5 3z"></path>
|
|
1260
1259
|
</svg>
|
|
1261
|
-
`}function
|
|
1260
|
+
`}function Yy(){return Kc()}function e0(){return $e`
|
|
1262
1261
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1263
1262
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
1264
1263
|
</svg>
|
|
1265
|
-
`}function
|
|
1264
|
+
`}function t0(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},(d,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,S=p<e.filled;return $e`<rect class=${S?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return $e`
|
|
1266
1265
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1267
1266
|
${a}
|
|
1268
1267
|
</svg>
|
|
1269
|
-
`}const
|
|
1268
|
+
`}const i0=["off","minimal","low","medium","high","xhigh"];function Er(e){return e===void 0||e===""?"off":e}function s0(e,t){const i=t.length>=2?t:i0,s=i.length-1,r=Er(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class r0 extends ho{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===co.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 r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const Co=po(r0);var o0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,Os=(e,t,i,s)=>{for(var r=s>1?void 0:s?n0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&o0(t,i,r),r};const a0=D`
|
|
1270
1269
|
:host { display: block; }
|
|
1271
1270
|
.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); }
|
|
1272
1271
|
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; }
|
|
@@ -1277,19 +1276,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1277
1276
|
`;let Bt=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
|
|
1278
1277
|
<div class="menu">
|
|
1279
1278
|
${this.items.map((e,t)=>l`
|
|
1280
|
-
<button class=${t===this.selectedIndex?"selected":""} ${
|
|
1279
|
+
<button class=${t===this.selectedIndex?"selected":""} ${Co(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
|
|
1281
1280
|
<strong>${e.insertText}</strong>
|
|
1282
1281
|
<span>${e.detail}</span>
|
|
1283
1282
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1284
1283
|
</button>
|
|
1285
1284
|
`)}
|
|
1286
1285
|
</div>
|
|
1287
|
-
`:null}};Bt.styles=
|
|
1286
|
+
`:null}};Bt.styles=a0;Os([c({attribute:!1})],Bt.prototype,"items",2);Os([c({type:Number})],Bt.prototype,"selectedIndex",2);Os([c({attribute:!1})],Bt.prototype,"onPick",2);Bt=Os([W("autocomplete-menu")],Bt);var l0=Object.defineProperty,c0=Object.getOwnPropertyDescriptor,z=(e,t,i,s)=>{for(var r=s>1?void 0:s?c0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&l0(t,i,r),r};let U=class extends I{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.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Ny(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Ao,this.readOnlyCompartment=new Ao,this.mobilePromptEnterMedia=Ws(),this.explicitShiftKeyActive=!1}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=Ti(i,t);s!==void 0&&ts(s,this.draft);const r=Ti(this.machineId,this.sessionId);this.draft=r!==void 0?Ll(r):"",this.currentInputMode=ns(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!d0(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
|
|
1288
1287
|
<footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
|
|
1289
1288
|
<div class="editor-wrap">
|
|
1290
1289
|
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
|
|
1291
1290
|
<input class="attachment-input" type="file" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
|
|
1292
|
-
<button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
1291
|
+
<button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${Zy()}</button>
|
|
1293
1292
|
${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
|
|
1294
1293
|
${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
|
|
1295
1294
|
${this.renderAttachments()}
|
|
@@ -1297,20 +1296,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1297
1296
|
</div>
|
|
1298
1297
|
<div class="actions">
|
|
1299
1298
|
${this.renderCompactStatus()}
|
|
1300
|
-
<button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?
|
|
1301
|
-
${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${
|
|
1302
|
-
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${
|
|
1299
|
+
<button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Xy():Kc()}</button>
|
|
1300
|
+
${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Yy()}</button>`:null}
|
|
1301
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${e0()}</button>
|
|
1303
1302
|
</div>
|
|
1304
1303
|
</footer>
|
|
1305
1304
|
`}focusInput(){this.editor?.focus()}get view(){return this.editor}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"无模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
|
|
1306
1305
|
<div class="compact-status" aria-label="会话状态">
|
|
1307
1306
|
<button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
|
|
1308
|
-
<button class="select-thinking icon-button" title=${`思考级别:${
|
|
1307
|
+
<button class="select-thinking icon-button" title=${`思考级别:${Er(e.thinkingLevel)}`} aria-label=${`思考级别:${Er(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${t0(s0(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
1309
1308
|
</div>
|
|
1310
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=
|
|
1309
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=Tr(this.attachments),t=this.effectiveAttachmentDelivery();return l`
|
|
1311
1310
|
<div class="attachments" aria-label="待发送附件">
|
|
1312
1311
|
${this.attachments.map(i=>l`
|
|
1313
|
-
<div class=${`attachment-chip ${
|
|
1312
|
+
<div class=${`attachment-chip ${Mr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
|
|
1314
1313
|
${this.renderAttachmentPreview(i)}
|
|
1315
1314
|
<button type="button" class="attachment-remove" title="移除附件" aria-label=${`移除 ${i.name}`} @click=${()=>{this.removeAttachment(i.id)}}>×</button>
|
|
1316
1315
|
</div>
|
|
@@ -1325,10 +1324,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1325
1324
|
`:null}
|
|
1326
1325
|
${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
|
|
1327
1326
|
</div>
|
|
1328
|
-
`}renderAttachmentPreview(e){return
|
|
1329
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
1327
|
+
`}renderAttachmentPreview(e){return Mr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
|
|
1328
|
+
<div class="attachment-file-preview" aria-hidden="true">${g0(e.name)}</div>
|
|
1330
1329
|
<span class="attachment-file-name">${e.name}</span>
|
|
1331
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!
|
|
1330
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!Tr(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,qy(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Ma(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&u0(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=Ma(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 jy(e,m0);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=>f0(e))}effectiveAttachmentDelivery(){return Uy(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new ut({parent:this.editorHost,state:_s.create({doc:this.draft,extensions:[nd(),md(),ad(),ld.of(" "),cd(dd,{fallback:!0}),ut.lineWrapping,ut.contentAttributes.of(e=>w0(e.state.sliceDoc(0,e.state.selection.main.head))),ut.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),pd("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(ut.editable.of(!this.disabled)),this.readOnlyCompartment.of(_s.readOnly.of(this.disabled)),ut.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),hd.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Mo.shift?.(e)??!1},{key:"Backspace",run:e=>vd(e)},...ud,...fd])]})}))}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:To.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(ut.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(_s.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Ti(this.machineId,this.sessionId);t!==void 0&&ts(t,this.draft);const i=ns(this.draft);Wf(i,this.currentInputMode)||(this.currentInputMode=i),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 K.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(p0);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 K.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(h0);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=zl(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){return Bl(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}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Qy(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return Jy(t,this.mobilePromptEnterMedia,Ls())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):bd(e)||gd(e)}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):Mo.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,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:To.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,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=Ti(this.machineId,this.sessionId);e!==void 0&&is(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};U.styles=mm;z([c({type:Boolean})],U.prototype,"disabled",2);z([c()],U.prototype,"sessionId",2);z([c()],U.prototype,"cwd",2);z([c()],U.prototype,"machineId",2);z([c()],U.prototype,"projectId",2);z([c()],U.prototype,"workspaceId",2);z([c({type:Boolean})],U.prototype,"workspaceScopedFileSuggestions",2);z([c({type:Boolean})],U.prototype,"canSteer",2);z([c({type:Boolean})],U.prototype,"isCompacting",2);z([c({type:Boolean})],U.prototype,"canStop",2);z([c({attribute:!1})],U.prototype,"status",2);z([c({type:Boolean})],U.prototype,"sending",2);z([c({attribute:!1})],U.prototype,"onSend",2);z([c({attribute:!1})],U.prototype,"onStop",2);z([c({attribute:!1})],U.prototype,"onSelectModel",2);z([c({attribute:!1})],U.prototype,"onSelectThinking",2);z([c({attribute:!1})],U.prototype,"availableThinkingLevels",2);z([q(".markdown-editor")],U.prototype,"editorHost",2);z([q(".attachment-input")],U.prototype,"attachmentInput",2);z([v()],U.prototype,"currentInputMode",2);z([v()],U.prototype,"completions",2);z([v()],U.prototype,"selectedIndex",2);z([v()],U.prototype,"attachments",2);z([v()],U.prototype,"attachmentDelivery",2);z([v()],U.prototype,"attachmentError",2);U=z([W("prompt-editor")],U);function d0(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function Ti(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return oi(e,t)}function p0(){return[]}function h0(){return[]}function Ma(e){return e===null?[]:Array.from(e.files)}function u0(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function f0(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function g0(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function m0(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const r=s.result;if(typeof r!="string"){i(new Error("文件读取结果异常"));return}const o=r.indexOf(",");t(o===-1?r:r.slice(o+1))},s.readAsDataURL(e)})}const v0={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},b0={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function w0(e){return ns(e).kind==="normal"?v0:b0}function Ei(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 y0(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var S0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,Vc=(e,t,i,s)=>{for(var r=s>1?void 0:s?x0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&S0(t,i,r),r};const k0=D`
|
|
1332
1331
|
:host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
|
|
1333
1332
|
.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; }
|
|
1334
1333
|
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -1343,10 +1342,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1343
1342
|
<span>↑${Ei(s.input)}</span>
|
|
1344
1343
|
<span>↓${Ei(s.output)}</span>
|
|
1345
1344
|
<span class="context">${i}</span>
|
|
1346
|
-
<span>${
|
|
1345
|
+
<span>${y0(e.cost)}</span>
|
|
1347
1346
|
${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
|
|
1348
1347
|
</div>
|
|
1349
|
-
`}};gs.styles=
|
|
1348
|
+
`}};gs.styles=k0;Vc([c({attribute:!1})],gs.prototype,"status",2);gs=Vc([W("status-bar")],gs);const Gc=D`
|
|
1350
1349
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1351
1350
|
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
1352
1351
|
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; }
|
|
@@ -1360,7 +1359,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1360
1359
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
1361
1360
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
1362
1361
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
1363
|
-
`;var
|
|
1362
|
+
`;var $0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var r=s>1?void 0:s?P0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$0(t,i,r),r};let je=class extends I{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
|
|
1364
1363
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1365
1364
|
<section @mousedown=${t=>{t.stopPropagation()}}>
|
|
1366
1365
|
<header>
|
|
@@ -1370,7 +1369,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1370
1369
|
${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
|
|
1371
1370
|
<div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
|
|
1372
1371
|
${e.map((t,i)=>l`
|
|
1373
|
-
<button class=${i===this.selectedIndex?"selected":""} ${
|
|
1372
|
+
<button class=${i===this.selectedIndex?"selected":""} ${Co(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
|
|
1374
1373
|
<span>${t.label}</span>
|
|
1375
1374
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1376
1375
|
</button>
|
|
@@ -1379,7 +1378,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1379
1378
|
</div>
|
|
1380
1379
|
</section>
|
|
1381
1380
|
</div>
|
|
1382
|
-
`}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)}}};je.styles=
|
|
1381
|
+
`}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)}}};je.styles=Gc;st([c()],je.prototype,"title",2);st([c({type:Boolean})],je.prototype,"searchable",2);st([c({attribute:!1})],je.prototype,"options",2);st([c({attribute:!1})],je.prototype,"selectedValue",2);st([c({attribute:!1})],je.prototype,"onPick",2);st([c({attribute:!1})],je.prototype,"onCancel",2);st([v()],je.prototype,"selectedIndex",2);st([v()],je.prototype,"query",2);je=st([W("command-picker")],je);var C0=Object.defineProperty,R0=Object.getOwnPropertyDescriptor,It=(e,t,i,s)=>{for(var r=s>1?void 0:s?R0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&C0(t,i,r),r};const I0=D`
|
|
1383
1382
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1384
1383
|
.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; }
|
|
1385
1384
|
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; }
|
|
@@ -1410,7 +1409,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1410
1409
|
</header>
|
|
1411
1410
|
<div class="options">
|
|
1412
1411
|
${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
|
|
1413
|
-
<button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${
|
|
1412
|
+
<button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${Co(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
|
|
1414
1413
|
<span class="main">
|
|
1415
1414
|
<strong>${t.title}</strong>
|
|
1416
1415
|
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
@@ -1423,7 +1422,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1423
1422
|
</div>
|
|
1424
1423
|
</section>
|
|
1425
1424
|
</div>
|
|
1426
|
-
`}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(){return
|
|
1425
|
+
`}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(){return A0(this.actions,this.queryText)}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){e.enabled!==!1&&this.onRun?.(e)}};et.styles=I0;It([c({attribute:!1})],et.prototype,"actions",2);It([c({attribute:!1})],et.prototype,"onRun",2);It([c({attribute:!1})],et.prototype,"onCancel",2);It([q("input")],et.prototype,"input",2);It([v()],et.prototype,"queryText",2);It([v()],et.prototype,"selectedIndex",2);et=It([W("action-palette")],et);function A0(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var M0=Object.defineProperty,T0=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?T0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&M0(t,i,r),r};let ue=class extends I{render(){const e=this.state;return e===void 0?null:l`
|
|
1427
1426
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
1428
1427
|
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1429
1428
|
<header>
|
|
@@ -1446,11 +1445,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1446
1445
|
<div class="actions"><button @click=${()=>{this.cancel()}}>取消</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"正在保存…":"保存 API key"}</button></div>
|
|
1447
1446
|
</div>
|
|
1448
1447
|
`;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>l`
|
|
1449
|
-
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${
|
|
1448
|
+
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Ta(t.authType)}</small></button>
|
|
1450
1449
|
`)}</div>`}}renderProviderButton(e){return l`
|
|
1451
1450
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
1452
|
-
<span>${e.name}${e.status.source!==void 0?l` <em>${
|
|
1453
|
-
<small>${e.id} · ${
|
|
1451
|
+
<span>${e.name}${e.status.source!==void 0?l` <em>${D0(e)}</em>`:null}</span>
|
|
1452
|
+
<small>${e.id} · ${Ta(e.authType)}</small>
|
|
1454
1453
|
</button>
|
|
1455
1454
|
`}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
|
|
1456
1455
|
<div class="form">
|
|
@@ -1470,10 +1469,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1470
1469
|
<div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
|
|
1471
1470
|
`:null}
|
|
1472
1471
|
${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
|
|
1473
|
-
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??
|
|
1472
|
+
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??W0(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
|
|
1474
1473
|
${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
|
|
1475
1474
|
</div>
|
|
1476
|
-
`}focusInputIfNeeded(){const e=
|
|
1475
|
+
`}focusInputIfNeeded(){const e=E0(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?.()}};ue.styles=[Gc,D`
|
|
1477
1476
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
1478
1477
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
1479
1478
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -1488,7 +1487,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1488
1487
|
.progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
|
|
1489
1488
|
.inline-options { display: grid; gap: 8px; }
|
|
1490
1489
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
1491
|
-
`];De([c({attribute:!1})],
|
|
1490
|
+
`];De([c({attribute:!1})],ue.prototype,"state",2);De([c({attribute:!1})],ue.prototype,"onChooseMethod",2);De([c({attribute:!1})],ue.prototype,"onSelectProvider",2);De([c({attribute:!1})],ue.prototype,"onApiKeyInput",2);De([c({attribute:!1})],ue.prototype,"onSaveApiKey",2);De([c({attribute:!1})],ue.prototype,"onLogoutProvider",2);De([c({attribute:!1})],ue.prototype,"onOAuthInput",2);De([c({attribute:!1})],ue.prototype,"onOAuthRespond",2);De([c({attribute:!1})],ue.prototype,"onOAuthCancel",2);De([c({attribute:!1})],ue.prototype,"onCancel",2);De([q("input")],ue.prototype,"input",2);ue=De([W("auth-dialog")],ue);function Ta(e){return e==="oauth"?"订阅":"API key"}function E0(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 D0(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ 已配置";case"environment":return`✓ 环境变量${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ 运行时";case"fallback":return"✓ 自定义 key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}function W0(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var L0=Object.defineProperty,O0=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?O0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&L0(t,i,r),r};let Ie=class extends I{constructor(){super(...arguments),this.mode="login",this.loading=!1,this.error="",this.currentPassword="",this.password="",this.confirmPassword="",this.localError=""}render(){return l`
|
|
1492
1491
|
<div class="backdrop">
|
|
1493
1492
|
<section role="dialog" aria-modal="true" aria-label=${this.dialogTitle()} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1494
1493
|
<header>
|
|
@@ -1523,7 +1522,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1523
1522
|
</form>
|
|
1524
1523
|
</section>
|
|
1525
1524
|
</div>
|
|
1526
|
-
`}dialogTitle(){return this.mode==="setup"?"设置进入密码":this.mode==="change"?"修改进入密码":"输入进入密码"}submitLabel(){return this.mode==="setup"?"设置并进入":this.mode==="change"?"保存密码":"进入"}message(){return this.localError||this.error}async submit(e){e.preventDefault();const t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},i=
|
|
1525
|
+
`}dialogTitle(){return this.mode==="setup"?"设置进入密码":this.mode==="change"?"修改进入密码":"输入进入密码"}submitLabel(){return this.mode==="setup"?"设置并进入":this.mode==="change"?"保存密码":"进入"}message(){return this.localError||this.error}async submit(e){e.preventDefault();const t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},i=F0(this.mode,t);if(i!==void 0){this.localError=i;return}this.localError="",await this.onSubmit?.(t)}handleKeyDown(e){e.key!=="Escape"||this.mode!=="change"||(e.preventDefault(),e.stopPropagation(),this.onCancel?.())}};Ie.styles=D`
|
|
1527
1526
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1528
1527
|
.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-bg); }
|
|
1529
1528
|
section { width: min(420px, 100%); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-surface); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -1541,7 +1540,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1541
1540
|
.close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
|
|
1542
1541
|
.message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
|
|
1543
1542
|
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
|
1544
|
-
`;Ge([c()],Ie.prototype,"mode",2);Ge([c({type:Boolean})],Ie.prototype,"loading",2);Ge([c()],Ie.prototype,"error",2);Ge([c({attribute:!1})],Ie.prototype,"onSubmit",2);Ge([c({attribute:!1})],Ie.prototype,"onCancel",2);Ge([v()],Ie.prototype,"currentPassword",2);Ge([v()],Ie.prototype,"password",2);Ge([v()],Ie.prototype,"confirmPassword",2);Ge([v()],Ie.prototype,"localError",2);Ie=Ge([W("normal-auth-dialog")],Ie);function
|
|
1543
|
+
`;Ge([c()],Ie.prototype,"mode",2);Ge([c({type:Boolean})],Ie.prototype,"loading",2);Ge([c()],Ie.prototype,"error",2);Ge([c({attribute:!1})],Ie.prototype,"onSubmit",2);Ge([c({attribute:!1})],Ie.prototype,"onCancel",2);Ge([v()],Ie.prototype,"currentPassword",2);Ge([v()],Ie.prototype,"password",2);Ge([v()],Ie.prototype,"confirmPassword",2);Ge([v()],Ie.prototype,"localError",2);Ie=Ge([W("normal-auth-dialog")],Ie);function F0(e,t){if(e==="change"&&(t.currentPassword??"")==="")return"请输入当前密码。";if(t.password==="")return"请输入密码。";if(e!=="login"&&t.password!==(t.confirmPassword??""))return"两次输入的密码不一致。"}function lr(e){return e.target instanceof HTMLInputElement?e.target.value:""}var _0=Object.defineProperty,j0=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?j0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&_0(t,i,r),r};let Ae=class extends I{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 K.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`
|
|
1545
1544
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1546
1545
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
1547
1546
|
<header>
|
|
@@ -1591,7 +1590,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1591
1590
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1592
1591
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1593
1592
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1594
|
-
`;Qe([c({attribute:!1})],Ae.prototype,"onSubmit",2);Qe([c({attribute:!1})],Ae.prototype,"onCancel",2);Qe([c()],Ae.prototype,"machineId",2);Qe([v()],Ae.prototype,"path",2);Qe([v()],Ae.prototype,"createMissing",2);Qe([v()],Ae.prototype,"suggestions",2);Qe([v()],Ae.prototype,"selected",2);Qe([v()],Ae.prototype,"loading",2);Qe([q("input")],Ae.prototype,"pathInput",2);Ae=Qe([W("project-dialog")],Ae);var
|
|
1593
|
+
`;Qe([c({attribute:!1})],Ae.prototype,"onSubmit",2);Qe([c({attribute:!1})],Ae.prototype,"onCancel",2);Qe([c()],Ae.prototype,"machineId",2);Qe([v()],Ae.prototype,"path",2);Qe([v()],Ae.prototype,"createMissing",2);Qe([v()],Ae.prototype,"suggestions",2);Qe([v()],Ae.prototype,"selected",2);Qe([v()],Ae.prototype,"loading",2);Qe([q("input")],Ae.prototype,"pathInput",2);Ae=Qe([W("project-dialog")],Ae);var U0=Object.defineProperty,B0=Object.getOwnPropertyDescriptor,Je=(e,t,i,s)=>{for(var r=s>1?void 0:s?B0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&U0(t,i,r),r};let Me=class extends I{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=z0(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"&&cr(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===""||cr(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?cr(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
|
|
1595
1594
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1596
1595
|
<section @click=${s=>{s.stopPropagation()}}>
|
|
1597
1596
|
<form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
|
|
@@ -1646,7 +1645,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1646
1645
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1647
1646
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1648
1647
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1649
|
-
`;Je([c({attribute:!1})],Me.prototype,"onSubmit",2);Je([c({attribute:!1})],Me.prototype,"onCancel",2);Je([c()],Me.prototype,"error",2);Je([v()],Me.prototype,"url",2);Je([v()],Me.prototype,"name",2);Je([v()],Me.prototype,"token",2);Je([v()],Me.prototype,"submitting",2);Je([q("input[name='baseUrl']")],Me.prototype,"urlInput",2);Je([q("input[name='name']")],Me.prototype,"nameInput",2);Me=Je([W("machine-dialog")],Me);function
|
|
1648
|
+
`;Je([c({attribute:!1})],Me.prototype,"onSubmit",2);Je([c({attribute:!1})],Me.prototype,"onCancel",2);Je([c()],Me.prototype,"error",2);Je([v()],Me.prototype,"url",2);Je([v()],Me.prototype,"name",2);Je([v()],Me.prototype,"token",2);Je([v()],Me.prototype,"submitting",2);Je([q("input[name='baseUrl']")],Me.prototype,"urlInput",2);Je([q("input[name='name']")],Me.prototype,"nameInput",2);Me=Je([W("machine-dialog")],Me);function z0(e){const t=e.trim();if(t==="")return"";const i=Ea(t)??Ea(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):N0(t)}function cr(e){const t=e.trim();if(t==="")return"必须填写远程 PI WEB URL。";let i;try{i=new URL(t)}catch{return"请输入包含 http:// 或 https:// 的有效 URL。"}if(i.protocol!=="http:"&&i.protocol!=="https:")return"请使用 http:// 或 https:// URL。";if(i.username!==""||i.password!=="")return"机器 URL 中不要包含凭据。";if(i.search!==""||i.hash!=="")return"不要包含查询字符串或片段。"}function Ea(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function N0(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,"")}var q0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,ht=(e,t,i,s)=>{for(var r=s>1?void 0:s?H0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&q0(t,i,r),r};const K0={availability:"error",error:"error",success:"success",security:"warning",warning:"warning",info:"info"};function V0(e){return e.tone??K0[e.type]}let Ve=class extends I{constructor(){super(...arguments),this.heading="",this.description="",this.actionLabel="",this.actionTitle="",this.actionDisabled=!1,this.notices=[]}render(){return l`
|
|
1650
1649
|
<section class="panel" aria-label=${this.heading||"Settings panel"}>
|
|
1651
1650
|
<header class="section-heading">
|
|
1652
1651
|
<div class="heading-copy">
|
|
@@ -1669,7 +1668,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1669
1668
|
<div class="notice-stack" aria-label="Settings notices">
|
|
1670
1669
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
1671
1670
|
</div>
|
|
1672
|
-
`}renderNotice(e){const t=
|
|
1671
|
+
`}renderNotice(e){const t=V0(e),i=e.role??G0(t),s=e.title;return l`
|
|
1673
1672
|
<article class=${`notice ${t}`} role=${i}>
|
|
1674
1673
|
${s===void 0||s===""?B:l`<strong class="notice-title">${s}</strong>`}
|
|
1675
1674
|
<div class="notice-content">${e.content}</div>
|
|
@@ -1702,13 +1701,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1702
1701
|
.section-heading { display: grid; gap: 12px; }
|
|
1703
1702
|
.heading-actions { justify-self: start; }
|
|
1704
1703
|
}
|
|
1705
|
-
`;ht([c()],Ve.prototype,"heading",2);ht([c({attribute:!1})],Ve.prototype,"description",2);ht([c()],Ve.prototype,"actionLabel",2);ht([c()],Ve.prototype,"actionTitle",2);ht([c({type:Boolean})],Ve.prototype,"actionDisabled",2);ht([c({attribute:!1})],Ve.prototype,"notices",2);ht([c({attribute:!1})],Ve.prototype,"onAction",2);Ve=ht([W("settings-panel-frame")],Ve);function
|
|
1706
|
-
`):""}}function
|
|
1707
|
-
`)??"",uploadDefaultFolder:e.uploads?.defaultFolder??""}}function
|
|
1708
|
-
`).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!
|
|
1704
|
+
`;ht([c()],Ve.prototype,"heading",2);ht([c({attribute:!1})],Ve.prototype,"description",2);ht([c()],Ve.prototype,"actionLabel",2);ht([c()],Ve.prototype,"actionTitle",2);ht([c({type:Boolean})],Ve.prototype,"actionDisabled",2);ht([c({attribute:!1})],Ve.prototype,"notices",2);ht([c({attribute:!1})],Ve.prototype,"onAction",2);Ve=ht([W("settings-panel-frame")],Ve);function G0(e){switch(e){case"error":return"alert";case"success":return"status";case"warning":case"info":return"note"}}function Q0(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function J0(){return{allowedPathsText:"",uploadDefaultFolder:""}}function Z0(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(`
|
|
1705
|
+
`):""}}function X0(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
1706
|
+
`)??"",uploadDefaultFolder:e.uploads?.defaultFolder??""}}function Y0(e,t={}){const i=tS(t),s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const o=Number(r);if(!Number.isInteger(o)||o<1||o>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=o}return i.allowedHosts=e.allowedHostsMode==="all"?!0:iS(e.allowedHostsText),i}function eS(e){const t=sS(e.allowedPathsText),i=rS(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:i===""?{}:{defaultFolder:i}}}function tS(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.normalAuth===void 0?{}:{normalAuth:e.normalAuth},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions}}}function iS(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function sS(e){const t=e.split(`
|
|
1707
|
+
`).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!oS(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function rS(e){const t=e.trim();if(t==="")return"";if(nS(t))throw new Error("Upload default folder must be workspace-relative.");const i=t.split(/[\\/]+/u).filter(s=>s!==""&&s!==".");if(i.length===0)return"";if(i.some(s=>s===".."))throw new Error("Upload default folder must not contain path traversal.");return i.join("/")}function oS(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function nS(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}var aS=Object.defineProperty,lS=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var r=s>1?void 0:s?lS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&aS(t,i,r),r};function cS(e){return l`网关服务器字段用于编辑当前本地网关;文件访问和上传默认值用于编辑 ${e}。`}let V=class extends I{constructor(){super(...arguments),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error="",this.machineError="",this.savedMessage="",this.targetLabel="selected machine",this.gatewayDraft=Q0(),this.machineDraft=J0(),this.gatewayLocalError="",this.machineLocalError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.gatewayDraft=Z0(this.configResponse.config),this.gatewayLocalError=""),e.has("machineConfigResponse")&&this.machineConfigResponse!==void 0&&(this.machineDraft=X0(this.machineConfigResponse.config),this.machineLocalError="")}render(){return l`
|
|
1709
1708
|
<settings-panel-frame
|
|
1710
1709
|
heading="通用配置"
|
|
1711
|
-
.description=${
|
|
1710
|
+
.description=${cS(this.targetLabel)}
|
|
1712
1711
|
actionLabel="重新加载"
|
|
1713
1712
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
1714
1713
|
.notices=${this.panelNotices()}
|
|
@@ -1755,11 +1754,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1755
1754
|
<span>允许的 hosts</span>
|
|
1756
1755
|
${this.renderOverrideBadge("allowedHosts")}
|
|
1757
1756
|
</span>
|
|
1758
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${t=>{this.updateGatewayDraft({allowedHostsMode:
|
|
1757
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${t=>{this.updateGatewayDraft({allowedHostsMode:hS(t)==="all"?"all":"list"})}}>
|
|
1759
1758
|
<option value="list">仅允许列出的 hosts</option>
|
|
1760
1759
|
<option value="all">允许所有 host</option>
|
|
1761
1760
|
</select>
|
|
1762
|
-
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateGatewayDraft({allowedHostsText:
|
|
1761
|
+
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateGatewayDraft({allowedHostsText:Da(t)})}}></textarea>
|
|
1763
1762
|
<small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
|
|
1764
1763
|
</div>
|
|
1765
1764
|
|
|
@@ -1789,7 +1788,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1789
1788
|
<span class="field-heading">
|
|
1790
1789
|
<span>外部文件系统根目录</span>
|
|
1791
1790
|
</span>
|
|
1792
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${t=>{this.updateMachineDraft({allowedPathsText:
|
|
1791
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${t=>{this.updateMachineDraft({allowedPathsText:Da(t)})}}></textarea>
|
|
1793
1792
|
<small>${this.targetLabel} 上允许用于绝对路径 <code>@</code> 补全和工作区外文件读取的目录。每行输入一个绝对路径、Windows 绝对路径或以 <code>~</code> 开头的路径。留空则默认禁止外部路径。</small>
|
|
1794
1793
|
</label>
|
|
1795
1794
|
|
|
@@ -1815,18 +1814,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1815
1814
|
<dl>
|
|
1816
1815
|
<div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
|
|
1817
1816
|
<div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
|
|
1818
|
-
<div><dt>允许的 hosts</dt><dd>${
|
|
1817
|
+
<div><dt>允许的 hosts</dt><dd>${dS(e.allowedHosts)}</dd></div>
|
|
1819
1818
|
</dl>
|
|
1820
1819
|
</section>
|
|
1821
1820
|
`}renderMachineEffectiveConfig(){const e=this.machineConfigResponse?.effectiveConfig??{};return l`
|
|
1822
1821
|
<section class="effective-card" aria-label="所选机器最终生效的文件访问和上传摘要">
|
|
1823
1822
|
<h3>所选机器的生效配置</h3>
|
|
1824
1823
|
<dl>
|
|
1825
|
-
<div><dt>外部根目录</dt><dd>${
|
|
1824
|
+
<div><dt>外部根目录</dt><dd>${pS(e.pathAccess?.allowedPaths)}</dd></div>
|
|
1826
1825
|
<div><dt>上传文件夹</dt><dd>${e.uploads?.defaultFolder??l`<span class="muted">默认 ${di}</span>`}</dd></div>
|
|
1827
1826
|
</dl>
|
|
1828
1827
|
</section>
|
|
1829
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError="";try{await this.onSave?.(
|
|
1828
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError="";try{await this.onSave?.(Y0(this.gatewayDraft,this.configResponse?.config??{}))}catch(t){this.gatewayLocalError=Wa(t)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError="";try{await this.onSaveMachineConfig?.(eS(this.machineDraft))}catch(t){this.machineLocalError=Wa(t)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=""}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=""}};V.styles=D`
|
|
1830
1829
|
:host { display: block; }
|
|
1831
1830
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
1832
1831
|
h3, p { margin: 0; }
|
|
@@ -1857,10 +1856,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1857
1856
|
@media (max-width: 760px) {
|
|
1858
1857
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1859
1858
|
}
|
|
1860
|
-
`;Z([c({attribute:!1})],
|
|
1859
|
+
`;Z([c({attribute:!1})],V.prototype,"configResponse",2);Z([c({attribute:!1})],V.prototype,"machineConfigResponse",2);Z([c({type:Boolean})],V.prototype,"loading",2);Z([c({type:Boolean})],V.prototype,"machineLoading",2);Z([c({type:Boolean})],V.prototype,"saving",2);Z([c()],V.prototype,"error",2);Z([c()],V.prototype,"machineError",2);Z([c()],V.prototype,"savedMessage",2);Z([c()],V.prototype,"targetLabel",2);Z([c({attribute:!1})],V.prototype,"onReload",2);Z([c({attribute:!1})],V.prototype,"onReloadMachine",2);Z([c({attribute:!1})],V.prototype,"onSave",2);Z([c({attribute:!1})],V.prototype,"onSaveMachineConfig",2);Z([v()],V.prototype,"gatewayDraft",2);Z([v()],V.prototype,"machineDraft",2);Z([v()],V.prototype,"gatewayLocalError",2);Z([v()],V.prototype,"machineLocalError",2);V=Z([W("settings-general-panel")],V);function dS(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function pS(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function dr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function hS(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Da(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Wa(e){return e instanceof Error?e.message:String(e)}function uS(e){return{spawnSessions:e}}function fS(e){return{subsessions:e}}function gS(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions}}}var mS=Object.defineProperty,vS=Object.getOwnPropertyDescriptor,rt=(e,t,i,s)=>{for(var r=s>1?void 0:s?vS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&mS(t,i,r),r};let Ue=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,r=e?.effectiveConfig.subsessions===!0&&i;return l`
|
|
1861
1860
|
<settings-panel-frame
|
|
1862
1861
|
heading="会话守护进程"
|
|
1863
|
-
.description=${
|
|
1862
|
+
.description=${bS(this.targetLabel)}
|
|
1864
1863
|
actionLabel="重新加载"
|
|
1865
1864
|
.actionDisabled=${this.loading}
|
|
1866
1865
|
.notices=${this.panelNotices(e)}
|
|
@@ -1913,7 +1912,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1913
1912
|
</section>
|
|
1914
1913
|
`}
|
|
1915
1914
|
</settings-panel-frame>
|
|
1916
|
-
`}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.savedMessage!==""&&t.push({type:"success",content:this.savedMessage}),e!==void 0&&t.push({type:"warning",title:`${this.targetLabel} 需要重启`,content:l`更改这些设置后,请在该机器上运行 <code>pi-web restart</code>,或重启其会话守护进程服务。`}),t}renderUnavailableConfigState(){return l`<div class="loading-card">${this.loading?"正在加载配置…":"配置不可用,请重新加载。"}</div>`}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(
|
|
1915
|
+
`}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.savedMessage!==""&&t.push({type:"success",content:this.savedMessage}),e!==void 0&&t.push({type:"warning",title:`${this.targetLabel} 需要重启`,content:l`更改这些设置后,请在该机器上运行 <code>pi-web restart</code>,或重启其会话守护进程服务。`}),t}renderUnavailableConfigState(){return l`<div class="loading-card">${this.loading?"正在加载配置…":"配置不可用,请重新加载。"}</div>`}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(uS(t))}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(fS(t))}};Ue.styles=D`
|
|
1917
1916
|
:host { display: block; }
|
|
1918
1917
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
1919
1918
|
button, input { font: inherit; }
|
|
@@ -1940,10 +1939,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1940
1939
|
@media (max-width: 760px) {
|
|
1941
1940
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1942
1941
|
}
|
|
1943
|
-
`;rt([c({attribute:!1})],Ue.prototype,"configResponse",2);rt([c({type:Boolean})],Ue.prototype,"loading",2);rt([c({type:Boolean})],Ue.prototype,"saving",2);rt([c()],Ue.prototype,"error",2);rt([c()],Ue.prototype,"savedMessage",2);rt([c()],Ue.prototype,"targetLabel",2);rt([c({attribute:!1})],Ue.prototype,"onReload",2);rt([c({attribute:!1})],Ue.prototype,"onSave",2);Ue=rt([W("settings-sessiond-panel")],Ue);function
|
|
1942
|
+
`;rt([c({attribute:!1})],Ue.prototype,"configResponse",2);rt([c({type:Boolean})],Ue.prototype,"loading",2);rt([c({type:Boolean})],Ue.prototype,"saving",2);rt([c()],Ue.prototype,"error",2);rt([c()],Ue.prototype,"savedMessage",2);rt([c()],Ue.prototype,"targetLabel",2);rt([c({attribute:!1})],Ue.prototype,"onReload",2);rt([c({attribute:!1})],Ue.prototype,"onSave",2);Ue=rt([W("settings-sessiond-panel")],Ue);function bS(e){return`这些设置会影响 ${e} 上长生命周期的会话运行时。更改会立即保存,但只有在该机器的会话守护进程重启后才会生效。`}function Qc(e){return{id:"local",name:"local",kind:"local"}}function kt(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function La(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Pe(t,be.piPackagesManage)?{state:"supported"}:{state:"unsupported",message:Jc(e)}}function Oa(e){return`${e.state}:${e.message??""}`}function Ro(e){return e?.state==="unsupported"}function Jc(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function wS(e){return e.kind==="local"}function Zc(e){return e.trim()}function yS(e){if(Zc(e)==="")return"Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path."}function SS(e){return e.scope==="project"?"Project scope":"User scope"}function xS(e){return e.filtered?"Filtered by current Pi package settings":"Available in this PI WEB process"}function kS(e){return e.installedPath??"Installed path not reported by Pi"}function Xc(e){return e.scope==="user"}function $S(e){if(!Xc(e))return"Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view."}function PS(e){return e.length>0&&e.every(Xc)}function CS(e){if(e.length===0)return"No Pi packages are configured yet.";if(!PS(e))return"Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually."}function Di(e,t,i){return e?.kind!==t?!1:i===void 0||e.source===i}function RS(e,t=Qc()){const i=e==="install"?"installed":e==="remove"?"removed":"updated",s=t.kind==="local"?"":` on ${t.name}`,r=t.kind==="local"?"each idle PI WEB session":`each idle PI WEB session on ${t.name}`,o=t.kind==="local"?"PI WEB browser plugin changes":`PI WEB browser plugin changes served by ${t.name}`;return`Pi package ${i}${s}. Type /reload in ${r} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${o}.`}function Yc(e,t){const i=e.trim();return t.kind!=="remote"?i:IS(i)?Jc(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:i}function IS(e){return e==="Not Found"||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var AS=Object.defineProperty,MS=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?MS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&AS(t,i,r),r};let ne=class extends I{constructor(){super(...arguments),this.loading=!1,this.error="",this.operationMessage="",this.installSource="",this.validationMessage=""}render(){const e=this.packagesResponse?.packages??[],t=this.packageTarget,i=kt(t),s=this.packageManagementUnavailable,r=this.packagesResponse!==void 0&&!s;return l`
|
|
1944
1943
|
<settings-panel-frame
|
|
1945
1944
|
heading="Pi packages"
|
|
1946
|
-
.description=${
|
|
1945
|
+
.description=${TS(i)}
|
|
1947
1946
|
actionLabel="Reload"
|
|
1948
1947
|
actionTitle=${s?this.packageManagementUnavailableMessage(i):`Reload Pi packages from ${i}`}
|
|
1949
1948
|
.actionDisabled=${this.loading||this.isOperating||s}
|
|
@@ -1965,7 +1964,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1965
1964
|
${this.validationMessage===""?null:l`<div class="field-error">${this.validationMessage}</div>`}
|
|
1966
1965
|
<small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install <source></code>. PI WEB does not ask you to choose an install location.</small>
|
|
1967
1966
|
</form>
|
|
1968
|
-
`}renderPackageList(e,t){const i=
|
|
1967
|
+
`}renderPackageList(e,t){const i=kt(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(i):CS(e),o=r!==void 0&&e.length>0;return l`
|
|
1969
1968
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
1970
1969
|
<div class="package-toolbar">
|
|
1971
1970
|
<div>
|
|
@@ -1984,12 +1983,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1984
1983
|
<div class="package-list">
|
|
1985
1984
|
${e.map(i=>this.renderPackage(i))}
|
|
1986
1985
|
</div>
|
|
1987
|
-
`}renderPackage(e){const t=
|
|
1986
|
+
`}renderPackage(e){const t=kt(this.packageTarget),i=this.packageManagementUnavailable,s=i?this.packageManagementUnavailableMessage(t):$S(e),r=i?this.packageManagementUnavailableMessage(t):"Remove this Pi package",o=Di(this.operation,"update",e.source),n=Di(this.operation,"remove",e.source);return l`
|
|
1988
1987
|
<article class=${`package-card${e.filtered?" filtered":""}`}>
|
|
1989
1988
|
<div class="package-main">
|
|
1990
1989
|
<strong>${e.source}</strong>
|
|
1991
|
-
<small>${
|
|
1992
|
-
<small>Installed path: <code>${
|
|
1990
|
+
<small>${SS(e)} · ${xS(e)}</small>
|
|
1991
|
+
<small>Installed path: <code>${kS(e)}</code></small>
|
|
1993
1992
|
${s===void 0?null:l`<small class="action-note">${s}</small>`}
|
|
1994
1993
|
</div>
|
|
1995
1994
|
<div class="package-actions">
|
|
@@ -1997,7 +1996,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
1997
1996
|
<button class="danger" title=${r} ?disabled=${this.isOperating||i} @click=${()=>{this.removePackage(e)}}>${n?"Removing…":"Remove"}</button>
|
|
1998
1997
|
</div>
|
|
1999
1998
|
</article>
|
|
2000
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:"",this.validationMessage=""}async installPackage(e){e.preventDefault();const t
|
|
1999
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:"",this.validationMessage=""}async installPackage(e){e.preventDefault();const t=yS(this.installSource);if(t!==void 0){this.validationMessage=t;return}const i=Zc(this.installSource);try{await this.onInstallPackage?.(i),this.installSource="",this.validationMessage=""}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??Qc()}get packageManagementUnavailable(){return Ro(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}};ne.styles=D`
|
|
2001
2000
|
:host { display: block; }
|
|
2002
2001
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
2003
2002
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -2032,10 +2031,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2032
2031
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
2033
2032
|
.package-main strong, .package-main small { white-space: normal; }
|
|
2034
2033
|
}
|
|
2035
|
-
`;
|
|
2034
|
+
`;me([c({attribute:!1})],ne.prototype,"packagesResponse",2);me([c({type:Boolean})],ne.prototype,"loading",2);me([c({attribute:!1})],ne.prototype,"operation",2);me([c({attribute:!1})],ne.prototype,"targetMachine",2);me([c({attribute:!1})],ne.prototype,"managementSupport",2);me([c()],ne.prototype,"error",2);me([c()],ne.prototype,"operationMessage",2);me([c({attribute:!1})],ne.prototype,"onReload",2);me([c({attribute:!1})],ne.prototype,"onInstallPackage",2);me([c({attribute:!1})],ne.prototype,"onRemovePackage",2);me([c({attribute:!1})],ne.prototype,"onUpdatePackage",2);me([v()],ne.prototype,"installSource",2);me([v()],ne.prototype,"validationMessage",2);ne=me([W("settings-packages-panel")],ne);function TS(e){return l`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEB browser plugins.`}var ES=Object.defineProperty,DS=Object.getOwnPropertyDescriptor,Ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?DS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ES(t,i,r),r};let Te=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}render(){const e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return l`
|
|
2036
2035
|
<settings-panel-frame
|
|
2037
2036
|
heading="PI WEB 插件"
|
|
2038
|
-
.description=${
|
|
2037
|
+
.description=${WS(this.targetLabel)}
|
|
2039
2038
|
actionLabel="重新加载"
|
|
2040
2039
|
actionTitle=${`从 ${this.targetLabel} 重新加载 PI WEB 插件`}
|
|
2041
2040
|
.actionDisabled=${this.loading}
|
|
@@ -2081,10 +2080,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2081
2080
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
2082
2081
|
.toggle { justify-self: start; }
|
|
2083
2082
|
}
|
|
2084
|
-
`;Ze([c({attribute:!1})],Te.prototype,"pluginsResponse",2);Ze([c({attribute:!1})],Te.prototype,"configResponse",2);Ze([c({type:Boolean})],Te.prototype,"loading",2);Ze([c({type:Boolean})],Te.prototype,"saving",2);Ze([c()],Te.prototype,"error",2);Ze([c()],Te.prototype,"savedMessage",2);Ze([c()],Te.prototype,"targetLabel",2);Ze([c({attribute:!1})],Te.prototype,"onReload",2);Ze([c({attribute:!1})],Te.prototype,"onTogglePlugin",2);Te=Ze([W("settings-plugins-panel")],Te);function
|
|
2083
|
+
`;Ze([c({attribute:!1})],Te.prototype,"pluginsResponse",2);Ze([c({attribute:!1})],Te.prototype,"configResponse",2);Ze([c({type:Boolean})],Te.prototype,"loading",2);Ze([c({type:Boolean})],Te.prototype,"saving",2);Ze([c()],Te.prototype,"error",2);Ze([c()],Te.prototype,"savedMessage",2);Ze([c()],Te.prototype,"targetLabel",2);Ze([c({attribute:!1})],Te.prototype,"onReload",2);Ze([c({attribute:!1})],Te.prototype,"onTogglePlugin",2);Te=Ze([W("settings-plugins-panel")],Te);function WS(e){return l`启用或禁用 <strong>${e}</strong> 上发现的 PI WEB 浏览器插件。这与安装 Pi 包相互独立;请重新加载浏览器标签页以应用插件运行时更改。`}var LS=Object.defineProperty,OS=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?OS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&LS(t,i,r),r};const Fa={capture:!0},FS=[{value:"auto",label:"自动/默认",description:"桌面环境按 Enter 发送;移动设备、粗略指针或窄屏环境按 Enter 换行。"},{value:"send",label:"Enter 发送消息",description:"Enter 发送聊天消息;支持时 Shift+Enter 插入新行。"},{value:"newline",label:"Enter 插入新行",description:"Enter 插入换行;支持时 Shift+Enter 发送聊天消息。"}];function _S(){return l`按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按 action id 排序,较短快捷键会遮蔽相同前缀的较长序列。`}let ce=class extends I{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=Ls(),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=Yl(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&&!gi(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=zS(this.actions),t=this.shortcutResolutions();return l`
|
|
2085
2084
|
<settings-panel-frame
|
|
2086
2085
|
heading="键盘快捷键"
|
|
2087
|
-
.description=${
|
|
2086
|
+
.description=${_S()}
|
|
2088
2087
|
actionLabel="重新加载"
|
|
2089
2088
|
.actionDisabled=${this.loading}
|
|
2090
2089
|
.notices=${this.panelNotices()}
|
|
@@ -2115,7 +2114,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2115
2114
|
<p>选择当前浏览器中 Enter 键的行为。支持时 Shift+Enter 执行相反操作;为避免误发送,会忽略触摸键盘的自动大写状态。</p>
|
|
2116
2115
|
</div>
|
|
2117
2116
|
<div class="prompt-enter-options" role="radiogroup" aria-label="聊天输入框中的 Enter 和 Shift Enter 行为">
|
|
2118
|
-
${
|
|
2117
|
+
${FS.map(e=>l`
|
|
2119
2118
|
<label class="prompt-enter-option">
|
|
2120
2119
|
<input
|
|
2121
2120
|
type="radio"
|
|
@@ -2132,8 +2131,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2132
2131
|
`)}
|
|
2133
2132
|
</div>
|
|
2134
2133
|
</section>
|
|
2135
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,
|
|
2136
|
-
<article class=${
|
|
2134
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,Vy(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=ms(e.id,i),r=KS(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:Qs(o),a=n?.ok===!0?n.shortcut:HS(e,i),d=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=BS(t);return l`
|
|
2135
|
+
<article class=${jS(t)}>
|
|
2137
2136
|
<div class="shortcut-main">
|
|
2138
2137
|
<strong>${e.title}</strong>
|
|
2139
2138
|
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
@@ -2143,8 +2142,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2143
2142
|
<div class="shortcut-editor">
|
|
2144
2143
|
<div class="shortcut-status">
|
|
2145
2144
|
${a!==void 0&&a!==""?l`<kbd>${Ni(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
|
|
2146
|
-
<small class=${u}>${
|
|
2147
|
-
${g===void 0?null:l`<small class=${
|
|
2145
|
+
<small class=${u}>${VS(u)}${p?" · 未保存":""}</small>
|
|
2146
|
+
${g===void 0?null:l`<small class=${US(t)}>${g}</small>`}
|
|
2148
2147
|
</div>
|
|
2149
2148
|
<label class="shortcut-input-label">
|
|
2150
2149
|
<span>快捷键</span>
|
|
@@ -2157,7 +2156,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2157
2156
|
autocapitalize="off"
|
|
2158
2157
|
spellcheck="false"
|
|
2159
2158
|
?disabled=${this.saving}
|
|
2160
|
-
@input=${S=>{this.updateDraft(e.id,
|
|
2159
|
+
@input=${S=>{this.updateDraft(e.id,GS(S))}}
|
|
2161
2160
|
>
|
|
2162
2161
|
</label>
|
|
2163
2162
|
${h!==""?l`<small class="recording-hint">${h}</small>`:null}
|
|
@@ -2169,7 +2168,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2169
2168
|
</div>
|
|
2170
2169
|
</div>
|
|
2171
2170
|
</article>
|
|
2172
|
-
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=ms(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=Qs(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??{},r=t===void 0?
|
|
2171
|
+
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=ms(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=Qs(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??{},r=t===void 0?qS(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(so(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 r=Qs(s);r.ok&&(e[t]=r.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()},Zl)}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,Fa),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Fa),this.recordingListenerActive=!1)}};ce.styles=D`
|
|
2173
2172
|
:host { display: block; }
|
|
2174
2173
|
h3, p { margin: 0; }
|
|
2175
2174
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -2225,7 +2224,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2225
2224
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
2226
2225
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
2227
2226
|
}
|
|
2228
|
-
`;xe([c({attribute:!1})],ce.prototype,"actions",2);xe([c({attribute:!1})],ce.prototype,"configResponse",2);xe([c({type:Boolean})],ce.prototype,"loading",2);xe([c({type:Boolean})],ce.prototype,"saving",2);xe([c()],ce.prototype,"error",2);xe([c()],ce.prototype,"savedMessage",2);xe([c({attribute:!1})],ce.prototype,"onReload",2);xe([c({attribute:!1})],ce.prototype,"onSave",2);xe([v()],ce.prototype,"drafts",2);xe([v()],ce.prototype,"localError",2);xe([v()],ce.prototype,"promptEnterPreference",2);xe([v()],ce.prototype,"recording",2);ce=xe([W("settings-shortcuts-panel")],ce);function
|
|
2227
|
+
`;xe([c({attribute:!1})],ce.prototype,"actions",2);xe([c({attribute:!1})],ce.prototype,"configResponse",2);xe([c({type:Boolean})],ce.prototype,"loading",2);xe([c({type:Boolean})],ce.prototype,"saving",2);xe([c()],ce.prototype,"error",2);xe([c()],ce.prototype,"savedMessage",2);xe([c({attribute:!1})],ce.prototype,"onReload",2);xe([c({attribute:!1})],ce.prototype,"onSave",2);xe([v()],ce.prototype,"drafts",2);xe([v()],ce.prototype,"localError",2);xe([v()],ce.prototype,"promptEnterPreference",2);xe([v()],ce.prototype,"recording",2);ce=xe([W("settings-shortcuts-panel")],ce);function jS(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function US(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function BS(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(r=>r.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function zS(e){const t=new Map;for(const i of[...e].sort(NS)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function NS(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function ms(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function qS(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function HS(e,t){const i=ms(e.id,t);if(i!==null)return i??e.shortcut}function KS(e,t){const i=ms(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function VS(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function GS(e){return e.target instanceof HTMLInputElement?e.target.value:""}async function QS(e){const[t,i]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),s={error:""},r=[];return t.status==="fulfilled"?s.config=t.value:r.push(`config: ${Dr(t.reason)}`),i.status==="fulfilled"?s.plugins=i.value:r.push(`PI WEB plugins: ${Dr(i.reason)}`),r.length>0&&(s.error=`Failed to load settings: ${r.join("; ")}`),s}async function JS(e,t,i){if(Ro(i))return{error:i.message??`Pi package management is not available on ${kt(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:""}}catch(s){return{error:`Failed to load Pi packages from ${kt(e)}: ${Yc(Dr(s),e)}`}}}function Dr(e){return e instanceof Error?e.message:String(e)}function ZS(e,t){return{...e,config:_a(e.config,t.config),effectiveConfig:_a(e.effectiveConfig,t.effectiveConfig)}}function _a(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function ja(e){return e!==void 0?{id:e.id,name:e.name,kind:e.kind}:{id:"local",name:"local",kind:"local"}}function Y(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function Ua(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Pe(t,be.selectedMachineSettings)?{state:"supported"}:{state:"unsupported",message:ed(e)}}function Ba(e){return`${e.state}:${e.message??""}`}function Dt(e){return e?.state==="unsupported"}function ed(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEB on that machine, then try again.`}function at(e,t){const i=e.trim();return t.kind!=="remote"?i:XS(i)?ed(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:i}function XS(e){return e==="Not Found"||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function YS(e,t,i){const s=e.plugins??{},r=s[t]??{};return{plugins:{...s,[t]:{...r,enabled:i}}}}function ex(e,t){return{...e,config:za(e.config,t.config),effectiveConfig:za(e.effectiveConfig,t.effectiveConfig)}}function za(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var tx=Object.defineProperty,ix=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?ix(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&tx(t,i,r),r};let L=class extends I{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error="",this.accessError="",this.sessiondError="",this.pluginError="",this.packageError="",this.savedMessage="",this.packageMessage="",this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.loadSessiondConfigForTarget(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){const t=this.settingsTarget();if(e.has("machine")&&ja(e.get("machine")).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has("machineRuntime")&&(this.selectedMachineSettingsSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return l`
|
|
2229
2228
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
2230
2229
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2231
2230
|
<header class="settings-header">
|
|
@@ -2318,7 +2317,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2318
2317
|
<strong>${t}</strong>
|
|
2319
2318
|
<small>${i}</small>
|
|
2320
2319
|
</button>
|
|
2321
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){const e=++this.loadRequestSeq;this.loading=!0,this.error="";try{const t=await
|
|
2320
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){const e=++this.loadRequestSeq;this.loading=!0,this.error="";try{const t=await QS({loadConfig:()=>Ne.config(),loadPlugins:()=>si.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){const t=++this.accessLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Dt(i)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError="";try{const s=await Ne.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=s}catch(s){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${at(Le(s),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async loadSessiondConfigForTarget(e=this.settingsTarget()){const t=++this.sessiondLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Dt(i)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError="";try{const s=await Ne.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=s}catch(s){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${at(Le(s),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){const t=++this.pluginLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Dt(i)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError="";try{const[s,r]=await Promise.allSettled([Ne.config(e.id),si.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;const o=[];s.status==="fulfilled"?this.selectedPluginConfigResponse=s.value:o.push(`config: ${at(Le(s.reason),e)}`),r.status==="fulfilled"?this.selectedPluginsResponse=r.value:o.push(`PI WEB plugins: ${at(Le(r.reason),e)}`),this.pluginError=o.length===0?"":`Failed to load PI WEB plugin settings from ${Y(e)}: ${o.join("; ")}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){const t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError="",this.packageMessage="";try{const i=await JS(e,s=>ri.packages(s),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=i.packagesResponse,this.packageError=i.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;const i=this.settingsTarget(),s=this.selectedMachineSettingsSupport(i);if(Dt(s)){this.pluginError=s.message??`Selected-machine settings are not available on ${Y(i)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(i)}. Reload before changing plugin enablement.`;return}const r=YS(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError="",this.savedMessage="";try{const o=await Ne.saveConfig(r,i.id);if(!this.isCurrentSettingsTarget(i))return;this.selectedPluginConfigResponse=o,i.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=ex(this.configResponse,o),this.onConfigSaved?.(this.configResponse.effectiveConfig));const n=await this.refreshPluginsForTarget(i);if(!this.isCurrentSettingsTarget(i))return;n!==void 0&&(this.pluginError=n),this.showSavedMessage()}catch(o){this.isCurrentSettingsTarget(i)&&(this.pluginError=`Failed to save PI WEB plugin config on ${Y(i)}: ${at(Le(o),i)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Ne.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Le(t)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Dt(i)){this.accessError=i.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError="",this.savedMessage="";try{const s=await Ne.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=ZS(this.configResponse,s),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${at(Le(s),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Dt(i)){this.sessiondError=i.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.sessiondError="",this.savedMessage="";try{const s=await Ne.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=gS(this.configResponse,s)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${at(Le(s),t)}`)}finally{this.saving=!1}}async installPiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation({kind:"install",source:e},"install Pi package",t,()=>ri.install(e,t.id))}async removePiPackage(e,t){const i=this.packageTarget();await this.runPiPackageMutation({kind:"remove",source:e},"remove Pi package",i,()=>ri.remove(e,t,i.id))}async updatePiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:"update-all"}:{kind:"update",source:e},"update Pi packages",t,()=>ri.update(e,t.id))}async runPiPackageMutation(e,t,i,s){const r=this.packageManagementSupport(i);if(Ro(r))throw this.packageError=r.message??`Pi package management is not available on ${kt(i)}.`,new Error(this.packageError);if(this.saving)throw new Error("A settings operation is already running.");const o=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError="",this.packageMessage="";try{const n=await s();if(!this.isCurrentPackageMutation(o,i))return;this.packagesResponse={packages:n.packages};const a=wS(i)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(o,i))return;a!==void 0&&(this.packageError=a),this.packageMessage=RS(n.action,i)}catch(n){throw this.isCurrentPackageMutation(o,i)&&(this.packageError=`Failed to ${t} on ${kt(i)}: ${Yc(Le(n),i)}`),n}finally{this.packageMutationSeq===o&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await si.plugins();return}catch(e){return`刷新网关 PI WEB 插件失败:${Le(e)}`}}async refreshPluginsForTarget(e){try{const t=await si.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEB plugins from ${Y(e)}: ${at(Le(t),e)}`}}settingsTarget(){return ja(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return Ua(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){const i=Ua(t,e),s=this.selectedMachineSettingsSupport(t);return Ba(i)!==Ba(s)}packageManagementSupport(e=this.packageTarget()){return La(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){const i=La(t,e),s=this.packageManagementSupport(t);return Oa(i)===Oa(s)?!1:i.state==="unsupported"||s.state==="unsupported"}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError="",this.accessConfigResponse=void 0,this.savedMessage=""}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError="",this.sessiondConfigResponse=void 0,this.savedMessage=""}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError="",this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=""}resetPackageStateForTargetChange(){const e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage="",this.packageError="",this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};L.styles=D`
|
|
2322
2321
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2323
2322
|
.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; }
|
|
2324
2323
|
.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; }
|
|
@@ -2345,7 +2344,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2345
2344
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
2346
2345
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
2347
2346
|
}
|
|
2348
|
-
`;F([c({attribute:!1})],L.prototype,"section",2);F([c({attribute:!1})],L.prototype,"actions",2);F([c({attribute:!1})],L.prototype,"machine",2);F([c({attribute:!1})],L.prototype,"machineRuntime",2);F([c({attribute:!1})],L.prototype,"onNavigate",2);F([c({attribute:!1})],L.prototype,"onClose",2);F([c({attribute:!1})],L.prototype,"onConfigSaved",2);F([v()],L.prototype,"configResponse",2);F([v()],L.prototype,"accessConfigResponse",2);F([v()],L.prototype,"sessiondConfigResponse",2);F([v()],L.prototype,"pluginsResponse",2);F([v()],L.prototype,"selectedPluginConfigResponse",2);F([v()],L.prototype,"selectedPluginsResponse",2);F([v()],L.prototype,"packagesResponse",2);F([v()],L.prototype,"loading",2);F([v()],L.prototype,"accessLoading",2);F([v()],L.prototype,"sessiondLoading",2);F([v()],L.prototype,"pluginLoading",2);F([v()],L.prototype,"packageLoading",2);F([v()],L.prototype,"saving",2);F([v()],L.prototype,"packageOperation",2);F([v()],L.prototype,"error",2);F([v()],L.prototype,"accessError",2);F([v()],L.prototype,"sessiondError",2);F([v()],L.prototype,"pluginError",2);F([v()],L.prototype,"packageError",2);F([v()],L.prototype,"savedMessage",2);F([v()],L.prototype,"packageMessage",2);L=F([W("settings-dialog")],L);function Le(e){return e instanceof Error?e.message:String(e)}var
|
|
2347
|
+
`;F([c({attribute:!1})],L.prototype,"section",2);F([c({attribute:!1})],L.prototype,"actions",2);F([c({attribute:!1})],L.prototype,"machine",2);F([c({attribute:!1})],L.prototype,"machineRuntime",2);F([c({attribute:!1})],L.prototype,"onNavigate",2);F([c({attribute:!1})],L.prototype,"onClose",2);F([c({attribute:!1})],L.prototype,"onConfigSaved",2);F([v()],L.prototype,"configResponse",2);F([v()],L.prototype,"accessConfigResponse",2);F([v()],L.prototype,"sessiondConfigResponse",2);F([v()],L.prototype,"pluginsResponse",2);F([v()],L.prototype,"selectedPluginConfigResponse",2);F([v()],L.prototype,"selectedPluginsResponse",2);F([v()],L.prototype,"packagesResponse",2);F([v()],L.prototype,"loading",2);F([v()],L.prototype,"accessLoading",2);F([v()],L.prototype,"sessiondLoading",2);F([v()],L.prototype,"pluginLoading",2);F([v()],L.prototype,"packageLoading",2);F([v()],L.prototype,"saving",2);F([v()],L.prototype,"packageOperation",2);F([v()],L.prototype,"error",2);F([v()],L.prototype,"accessError",2);F([v()],L.prototype,"sessiondError",2);F([v()],L.prototype,"pluginError",2);F([v()],L.prototype,"packageError",2);F([v()],L.prototype,"savedMessage",2);F([v()],L.prototype,"packageMessage",2);L=F([W("settings-dialog")],L);function Le(e){return e instanceof Error?e.message:String(e)}var sx=Object.defineProperty,rx=Object.getOwnPropertyDescriptor,Be=(e,t,i,s)=>{for(var r=s>1?void 0:s?rx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&sx(t,i,r),r};const ox=D`
|
|
2349
2348
|
: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; }
|
|
2350
2349
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
2351
2350
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -2434,32 +2433,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2434
2433
|
<h2>${e.title}</h2>
|
|
2435
2434
|
${e.body===void 0?null:l`<p>${e.body}</p>`}
|
|
2436
2435
|
</section>
|
|
2437
|
-
`}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}};ye.styles=
|
|
2436
|
+
`}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}};ye.styles=ox;Be([c({attribute:!1})],ye.prototype,"workspace",2);Be([c({attribute:!1})],ye.prototype,"panelContext",2);Be([c({attribute:!1})],ye.prototype,"emptyState",2);Be([c()],ye.prototype,"tool",2);Be([c({attribute:!1})],ye.prototype,"panels",2);Be([c({type:Boolean})],ye.prototype,"hideToolTabs",2);Be([c({attribute:!1})],ye.prototype,"onSelectTool",2);Be([q(".workspace-header-strip")],ye.prototype,"workspaceHeaderStrip",2);Be([v()],ye.prototype,"workspaceHeaderCanScrollLeft",2);Be([v()],ye.prototype,"workspaceHeaderCanScrollRight",2);ye=Be([W("workspace-panel")],ye);var nx=Object.defineProperty,ax=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var r=s>1?void 0:s?ax(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&nx(t,i,r),r};let fe=class extends I{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=lx(this.machines),t=cx(this.machine),i=px(this.project),s=ux(this.workspace),r=gx(this.session);return l`
|
|
2438
2437
|
<nav class=${this.contextBarClass()} aria-label="当前位置">
|
|
2439
2438
|
<span class="context-bar-label">位置</span>
|
|
2440
2439
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
2441
2440
|
${e?l`
|
|
2442
2441
|
<li class="context-item">
|
|
2443
|
-
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${
|
|
2442
|
+
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${dx(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
|
|
2444
2443
|
<span class="context-kind">机器</span>
|
|
2445
2444
|
<span class="context-value">${t}</span>
|
|
2446
2445
|
</button>
|
|
2447
2446
|
</li>
|
|
2448
2447
|
`:null}
|
|
2449
2448
|
<li class="context-item">
|
|
2450
|
-
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${
|
|
2449
|
+
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${hx(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
|
|
2451
2450
|
<span class="context-kind">项目</span>
|
|
2452
2451
|
<span class="context-value">${i}</span>
|
|
2453
2452
|
</button>
|
|
2454
2453
|
</li>
|
|
2455
2454
|
<li class="context-item">
|
|
2456
|
-
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${
|
|
2455
|
+
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${fx(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
|
|
2457
2456
|
<span class="context-kind">工作区</span>
|
|
2458
2457
|
<span class="context-value">${s}</span>
|
|
2459
2458
|
</button>
|
|
2460
2459
|
</li>
|
|
2461
2460
|
<li class="context-item">
|
|
2462
|
-
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${
|
|
2461
|
+
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${mx(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
|
|
2463
2462
|
<span class="context-kind">会话</span>
|
|
2464
2463
|
<span class="context-value">${r}</span>
|
|
2465
2464
|
</button>
|
|
@@ -2473,7 +2472,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2473
2472
|
<path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
|
|
2474
2473
|
</svg>
|
|
2475
2474
|
</button>
|
|
2476
|
-
`}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}};
|
|
2475
|
+
`}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}};fe.styles=D`
|
|
2477
2476
|
/* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
|
|
2478
2477
|
:host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
|
|
2479
2478
|
.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); }
|
|
@@ -2499,7 +2498,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2499
2498
|
.context-kind { display: none; }
|
|
2500
2499
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
2501
2500
|
button { cursor: pointer; }
|
|
2502
|
-
`;We([c({attribute:!1})],
|
|
2501
|
+
`;We([c({attribute:!1})],fe.prototype,"machines",2);We([c({attribute:!1})],fe.prototype,"machine",2);We([c({attribute:!1})],fe.prototype,"project",2);We([c({attribute:!1})],fe.prototype,"workspace",2);We([c({attribute:!1})],fe.prototype,"session",2);We([c({attribute:!1})],fe.prototype,"refreshControl",2);We([c({attribute:!1})],fe.prototype,"onOpenSection",2);We([c({attribute:!1})],fe.prototype,"onShowActions",2);We([q(".context-items")],fe.prototype,"contextItems",2);We([v()],fe.prototype,"canScrollLeft",2);We([v()],fe.prototype,"canScrollRight",2);fe=We([W("app-context-bar")],fe);function lx(e){return e.length>1}function cx(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function dx(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function px(e){return e?.name??"未选择项目"}function hx(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function ux(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function fx(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function gx(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e===void 0?"未选择会话":$c(e.id)}function mx(e){return e===void 0?"未选择会话":e.path}var vx=Object.defineProperty,bx=Object.getOwnPropertyDescriptor,At=(e,t,i,s)=>{for(var r=s>1?void 0:s?bx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vx(t,i,r),r};let tt=class extends I{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`
|
|
2503
2502
|
<div class=${this.frameClass()}>
|
|
2504
2503
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
2505
2504
|
${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
|
|
@@ -2511,7 +2510,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2511
2510
|
`})}
|
|
2512
2511
|
</div>
|
|
2513
2512
|
</div>
|
|
2514
|
-
`}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>`:
|
|
2513
|
+
`}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>`:hm(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}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}};tt.styles=D`
|
|
2515
2514
|
:host { flex: 0 0 auto; min-width: 0; }
|
|
2516
2515
|
.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); }
|
|
2517
2516
|
.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; }
|
|
@@ -2537,12 +2536,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2537
2536
|
.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; }
|
|
2538
2537
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
2539
2538
|
}
|
|
2540
|
-
`;
|
|
2539
|
+
`;At([c({attribute:!1})],tt.prototype,"tabs",2);At([c({attribute:!1})],tt.prototype,"selectedView",2);At([c({attribute:!1})],tt.prototype,"onSelect",2);At([q(".mobile-tabs")],tt.prototype,"mobileTabs",2);At([v()],tt.prototype,"canScrollLeft",2);At([v()],tt.prototype,"canScrollRight",2);tt=At([W("app-mobile-main-tabs")],tt);var wx=Object.defineProperty,yx=Object.getOwnPropertyDescriptor,ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?yx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&wx(t,i,r),r};let de=class extends I{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=pr(e,this.statuses),i=e.name;return l`
|
|
2541
2540
|
<div class="machine-switcher">
|
|
2542
2541
|
<button
|
|
2543
2542
|
type="button"
|
|
2544
2543
|
class="machine-switcher-button"
|
|
2545
|
-
title=${
|
|
2544
|
+
title=${qa(e)}
|
|
2546
2545
|
aria-label=${`Machine: ${i}. Switch machine.`}
|
|
2547
2546
|
aria-expanded=${String(this.open)}
|
|
2548
2547
|
@click=${s=>{this.toggleMenu(s.currentTarget)}}
|
|
@@ -2553,7 +2552,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2553
2552
|
<span class="machine-switcher-kicker">Machine</span>
|
|
2554
2553
|
<span class="machine-switcher-label">${i}</span>
|
|
2555
2554
|
</span>
|
|
2556
|
-
<span class=${`machine-status ${t}`}>${
|
|
2555
|
+
<span class=${`machine-status ${t}`}>${Na(t)}</span>
|
|
2557
2556
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
2558
2557
|
</button>
|
|
2559
2558
|
${this.open?l`
|
|
@@ -2562,18 +2561,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2562
2561
|
</div>
|
|
2563
2562
|
`:null}
|
|
2564
2563
|
</div>
|
|
2565
|
-
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=pr(e,this.statuses),s=
|
|
2564
|
+
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=pr(e,this.statuses),s=kc(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
|
|
2566
2565
|
<div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
|
|
2567
2566
|
<button
|
|
2568
2567
|
type="button"
|
|
2569
2568
|
class="machine-option-main"
|
|
2570
|
-
title=${
|
|
2569
|
+
title=${qa(e)}
|
|
2571
2570
|
data-machine-id=${e.id}
|
|
2572
2571
|
@click=${()=>{this.select(e)}}
|
|
2573
2572
|
@keydown=${o=>{this.handleMachineOptionKeydown(o)}}
|
|
2574
2573
|
>
|
|
2575
2574
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
2576
|
-
<small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${
|
|
2575
|
+
<small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Na(i)}</small>
|
|
2577
2576
|
</button>
|
|
2578
2577
|
${s?l`
|
|
2579
2578
|
<div class="machine-option-actions">
|
|
@@ -2593,7 +2592,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2593
2592
|
</div>
|
|
2594
2593
|
`:null}
|
|
2595
2594
|
</div>
|
|
2596
|
-
`}renderActivity(e){const t=pr(e,this.statuses);if(t==="offline"||t==="error")return;const i=
|
|
2595
|
+
`}renderActivity(e){const t=pr(e,this.statuses);if(t==="offline"||t==="error")return;const i=fc(this.activities[e.id]);return mc(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=Ha(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=Ha(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 r=s.indexOf(e);r<0||this.focusMachineOptionAt(r+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=vc(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)}};de.styles=D`
|
|
2597
2596
|
:host { min-width: 0; display: block; }
|
|
2598
2597
|
.machine-switcher { min-width: 0; }
|
|
2599
2598
|
.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; }
|
|
@@ -2626,7 +2625,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2626
2625
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
2627
2626
|
.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); }
|
|
2628
2627
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
2629
|
-
`;ke([c({attribute:!1})],de.prototype,"machines",2);ke([c({attribute:!1})],de.prototype,"selected",2);ke([c({attribute:!1})],de.prototype,"statuses",2);ke([c({attribute:!1})],de.prototype,"activities",2);ke([c({attribute:!1})],de.prototype,"onSelect",2);ke([c({attribute:!1})],de.prototype,"onRemove",2);ke([c({attribute:!1})],de.prototype,"onFocusNextSection",2);ke([c({attribute:!1})],de.prototype,"onCancelKeyboardNavigation",2);ke([v()],de.prototype,"open",2);ke([v()],de.prototype,"menuStyle",2);ke([v()],de.prototype,"openActionsMachineId",2);ke([v()],de.prototype,"actionMenuStyle",2);de=ke([W("machine-switcher")],de);function pr(e,t){return t[e.id]?.status??e.status??"unknown"}function
|
|
2628
|
+
`;ke([c({attribute:!1})],de.prototype,"machines",2);ke([c({attribute:!1})],de.prototype,"selected",2);ke([c({attribute:!1})],de.prototype,"statuses",2);ke([c({attribute:!1})],de.prototype,"activities",2);ke([c({attribute:!1})],de.prototype,"onSelect",2);ke([c({attribute:!1})],de.prototype,"onRemove",2);ke([c({attribute:!1})],de.prototype,"onFocusNextSection",2);ke([c({attribute:!1})],de.prototype,"onCancelKeyboardNavigation",2);ke([v()],de.prototype,"open",2);ke([v()],de.prototype,"menuStyle",2);ke([v()],de.prototype,"openActionsMachineId",2);ke([v()],de.prototype,"actionMenuStyle",2);de=ke([W("machine-switcher")],de);function pr(e,t){return t[e.id]?.status??e.status??"unknown"}function Na(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function qa(e){return e.baseUrl??e.name}function Ha(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)),r=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),o=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Wi(t.bottom)};`,`left: ${Wi(r)};`,`width: ${Wi(s)};`,`max-height: ${Wi(o)};`].join(" ")}function Wi(e){return`${String(Math.round(e))}px`}var Sx=Object.defineProperty,xx=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?xx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Sx(t,i,r),r};let x=class extends I{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.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。"}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`
|
|
2630
2629
|
<header>
|
|
2631
2630
|
<strong>PI WEB</strong>
|
|
2632
2631
|
${vs(this.machines)?l`
|
|
@@ -2724,7 +2723,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2724
2723
|
.onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
|
|
2725
2724
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
2726
2725
|
></session-list>
|
|
2727
|
-
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=
|
|
2726
|
+
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=kx(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.($x(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=D`
|
|
2728
2727
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
2729
2728
|
:host([compact]) { flex: 1 1 auto; }
|
|
2730
2729
|
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); }
|
|
@@ -2747,7 +2746,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2747
2746
|
:host([compact]) workspace-list[collapsed],
|
|
2748
2747
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
2749
2748
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
2750
|
-
`;k([c({attribute:!1})],x.prototype,"machines",2);k([c({attribute:!1})],x.prototype,"selectedMachine",2);k([c({attribute:!1})],x.prototype,"machineStatuses",2);k([c({attribute:!1})],x.prototype,"machineActivities",2);k([c({attribute:!1})],x.prototype,"projects",2);k([c({attribute:!1})],x.prototype,"selectedProject",2);k([c({attribute:!1})],x.prototype,"workspaces",2);k([c({attribute:!1})],x.prototype,"selectedWorkspace",2);k([c({attribute:!1})],x.prototype,"sessions",2);k([c({attribute:!1})],x.prototype,"selectedSession",2);k([c({attribute:!1})],x.prototype,"workspaceActivities",2);k([c({attribute:!1})],x.prototype,"sessionActivities",2);k([c({attribute:!1})],x.prototype,"sessionStatuses",2);k([c({attribute:!1})],x.prototype,"sendingPrompts",2);k([c({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([c({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([c({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([c({attribute:!1})],x.prototype,"refreshControl",2);k([c({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([c({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([c({type:Boolean})],x.prototype,"machinesCollapsed",2);k([c({type:Boolean})],x.prototype,"projectsCollapsed",2);k([c({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([c({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([c({type:Number})],x.prototype,"startingSessionCount",2);k([c({type:Boolean})],x.prototype,"canStartSession",2);k([c({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([c({type:Boolean})],x.prototype,"canReloadSessions",2);k([c({type:Boolean})],x.prototype,"canCleanupSessions",2);k([c({type:Boolean})],x.prototype,"authoritativeSessionPersistence",2);k([c({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([c({type:String})],x.prototype,"cleanupUnavailableMessage",2);k([c({attribute:!1})],x.prototype,"onShowActions",2);k([c({attribute:!1})],x.prototype,"onToggleMachines",2);k([c({attribute:!1})],x.prototype,"onToggleProjects",2);k([c({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([c({attribute:!1})],x.prototype,"onToggleSessions",2);k([c({attribute:!1})],x.prototype,"onSelectProject",2);k([c({attribute:!1})],x.prototype,"onCloseProject",2);k([c({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([c({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([c({attribute:!1})],x.prototype,"onStartSession",2);k([c({attribute:!1})],x.prototype,"onSelectSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([c({attribute:!1})],x.prototype,"onArchiveSessions",2);k([c({attribute:!1})],x.prototype,"onRestoreSession",2);k([c({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([c({attribute:!1})],x.prototype,"onDetachParentSession",2);k([c({attribute:!1})],x.prototype,"onReloadSession",2);k([c({attribute:!1})],x.prototype,"onCleanupSessions",2);k([c({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([c({attribute:!1})],x.prototype,"onSelectMachine",2);k([c({attribute:!1})],x.prototype,"onRemoveMachine",2);k([c({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([c({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([q("machine-list")],x.prototype,"machineList",2);k([q("machine-switcher")],x.prototype,"machineSwitcher",2);k([q("project-list")],x.prototype,"projectList",2);k([q("workspace-list")],x.prototype,"workspaceList",2);k([q("session-list")],x.prototype,"sessionList",2);x=k([W("app-navigation-panel")],x);function vs(e){return e.length>1}function
|
|
2749
|
+
`;k([c({attribute:!1})],x.prototype,"machines",2);k([c({attribute:!1})],x.prototype,"selectedMachine",2);k([c({attribute:!1})],x.prototype,"machineStatuses",2);k([c({attribute:!1})],x.prototype,"machineActivities",2);k([c({attribute:!1})],x.prototype,"projects",2);k([c({attribute:!1})],x.prototype,"selectedProject",2);k([c({attribute:!1})],x.prototype,"workspaces",2);k([c({attribute:!1})],x.prototype,"selectedWorkspace",2);k([c({attribute:!1})],x.prototype,"sessions",2);k([c({attribute:!1})],x.prototype,"selectedSession",2);k([c({attribute:!1})],x.prototype,"workspaceActivities",2);k([c({attribute:!1})],x.prototype,"sessionActivities",2);k([c({attribute:!1})],x.prototype,"sessionStatuses",2);k([c({attribute:!1})],x.prototype,"sendingPrompts",2);k([c({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([c({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([c({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([c({attribute:!1})],x.prototype,"refreshControl",2);k([c({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([c({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([c({type:Boolean})],x.prototype,"machinesCollapsed",2);k([c({type:Boolean})],x.prototype,"projectsCollapsed",2);k([c({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([c({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([c({type:Number})],x.prototype,"startingSessionCount",2);k([c({type:Boolean})],x.prototype,"canStartSession",2);k([c({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([c({type:Boolean})],x.prototype,"canReloadSessions",2);k([c({type:Boolean})],x.prototype,"canCleanupSessions",2);k([c({type:Boolean})],x.prototype,"authoritativeSessionPersistence",2);k([c({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([c({type:String})],x.prototype,"cleanupUnavailableMessage",2);k([c({attribute:!1})],x.prototype,"onShowActions",2);k([c({attribute:!1})],x.prototype,"onToggleMachines",2);k([c({attribute:!1})],x.prototype,"onToggleProjects",2);k([c({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([c({attribute:!1})],x.prototype,"onToggleSessions",2);k([c({attribute:!1})],x.prototype,"onSelectProject",2);k([c({attribute:!1})],x.prototype,"onCloseProject",2);k([c({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([c({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([c({attribute:!1})],x.prototype,"onStartSession",2);k([c({attribute:!1})],x.prototype,"onSelectSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([c({attribute:!1})],x.prototype,"onArchiveSessions",2);k([c({attribute:!1})],x.prototype,"onRestoreSession",2);k([c({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([c({attribute:!1})],x.prototype,"onDetachParentSession",2);k([c({attribute:!1})],x.prototype,"onReloadSession",2);k([c({attribute:!1})],x.prototype,"onCleanupSessions",2);k([c({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([c({attribute:!1})],x.prototype,"onSelectMachine",2);k([c({attribute:!1})],x.prototype,"onRemoveMachine",2);k([c({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([c({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([q("machine-list")],x.prototype,"machineList",2);k([q("machine-switcher")],x.prototype,"machineSwitcher",2);k([q("project-list")],x.prototype,"projectList",2);k([q("workspace-list")],x.prototype,"workspaceList",2);k([q("session-list")],x.prototype,"sessionList",2);x=k([W("app-navigation-panel")],x);function vs(e){return e.length>1}function kx(e,t){const i=td(t);return i[i.indexOf(e)-1]}function $x(e,t){const i=td(t);return i[i.indexOf(e)+1]??"chat"}function td(e){return cs.filter(t=>t!=="machines"||vs(e))}var Px=Object.defineProperty,Cx=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Px(t,i,r),r};const Rx=new Set(["ArrowLeft","ArrowRight","Home","End"]),Ix=420,Ax=4;let J=class extends I{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
|
|
2751
2750
|
${this.renderResizeHandle()}
|
|
2752
2751
|
<button
|
|
2753
2752
|
type="button"
|
|
@@ -2777,7 +2776,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2777
2776
|
@dblclick=${t=>{this.onResizeDoubleClick(t)}}
|
|
2778
2777
|
@keydown=${t=>{this.onResizeKeyDown(t)}}
|
|
2779
2778
|
></div>
|
|
2780
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?B: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)<=
|
|
2779
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?B: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)<=Ax)&&(t.moved=!0,this.commitPanelWidth(_v(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||!Rx.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=jv(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<=Ix){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 Ce(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Ce(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=Si(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};J.styles=D`
|
|
2781
2780
|
: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; }
|
|
2782
2781
|
:host([side="navigation"]) { grid-column: 2; }
|
|
2783
2782
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -2796,7 +2795,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2796
2795
|
@media (max-width: 760px) {
|
|
2797
2796
|
:host([side="navigation"]) { display: none; }
|
|
2798
2797
|
}
|
|
2799
|
-
`;ae([c({reflect:!0})],J.prototype,"side",2);ae([c({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([c({type:Boolean})],J.prototype,"resizable",2);ae([c({type:Number})],J.prototype,"panelWidth",2);ae([c({type:Number})],J.prototype,"minWidth",2);ae([c({type:Number})],J.prototype,"maxWidth",2);ae([c()],J.prototype,"controls",2);ae([c()],J.prototype,"resizeLabel",2);ae([c()],J.prototype,"expandLabel",2);ae([c()],J.prototype,"collapseLabel",2);ae([c({attribute:!1})],J.prototype,"onToggle",2);ae([c({attribute:!1})],J.prototype,"onResizeStart",2);ae([c({attribute:!1})],J.prototype,"onResize",2);ae([c({attribute:!1})],J.prototype,"onResizeEnd",2);ae([c({attribute:!1})],J.prototype,"onReset",2);J=ae([W("app-panel-edge-control")],J);var
|
|
2798
|
+
`;ae([c({reflect:!0})],J.prototype,"side",2);ae([c({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([c({type:Boolean})],J.prototype,"resizable",2);ae([c({type:Number})],J.prototype,"panelWidth",2);ae([c({type:Number})],J.prototype,"minWidth",2);ae([c({type:Number})],J.prototype,"maxWidth",2);ae([c()],J.prototype,"controls",2);ae([c()],J.prototype,"resizeLabel",2);ae([c()],J.prototype,"expandLabel",2);ae([c()],J.prototype,"collapseLabel",2);ae([c({attribute:!1})],J.prototype,"onToggle",2);ae([c({attribute:!1})],J.prototype,"onResizeStart",2);ae([c({attribute:!1})],J.prototype,"onResize",2);ae([c({attribute:!1})],J.prototype,"onResizeEnd",2);ae([c({attribute:!1})],J.prototype,"onReset",2);J=ae([W("app-panel-edge-control")],J);var Mx=Object.defineProperty,Tx=Object.getOwnPropertyDescriptor,id=(e,t,i,s)=>{for(var r=s>1?void 0:s?Tx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Mx(t,i,r),r};let bs=class extends I{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
|
|
2800
2799
|
<button
|
|
2801
2800
|
class="app-refresh-button"
|
|
2802
2801
|
title=${e}
|
|
@@ -2815,7 +2814,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2815
2814
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
2816
2815
|
.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; }
|
|
2817
2816
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
2818
|
-
`;
|
|
2817
|
+
`;id([c({attribute:!1})],bs.prototype,"onReload",2);bs=id([W("app-refresh-control")],bs);var Ex=Object.defineProperty,Dx=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dx(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ex(t,i,r),r};const Wx=D`
|
|
2819
2818
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
2820
2819
|
: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; }
|
|
2821
2820
|
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
@@ -2914,7 +2913,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2914
2913
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
2915
2914
|
.empty { margin: auto; color: var(--pi-muted); }
|
|
2916
2915
|
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
2917
|
-
`,jx=900*1e3,Ux=750,Lr=[1e3,3e3,8e3,15e3,3e4],Va={capture:!0},hr="auto:on",Ga="auto:off",Li="theme:",ur=vi("core:workspace.files"),fr=vi("core:workspace.git"),Oi=vi("core:workspace.terminal"),Bx=320,zx=2,Nx="(min-width: 1181px)";let Q=class extends I{constructor(){super(...arguments),this.state=iu(),this.apiScope=Hx(),this.sessions=new Zf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Hf,{socket:new jl(this.apiScope)}),this.activity=new su(()=>this.state,e=>{this.setState(e)}),this.auth=new nu(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new ug(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new pg),this.projects=new yu(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new wu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new fu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new bu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Cg,this.realtime=new kn(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new vg,this.terminalSelection=new $g,this.appShell=new Pv(this),this.panelCollapse=new _v(this),this.panelResize=new Uv(this),this.navigationSections=new Lv(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=qx(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Gg()??Hg,this.activeThemeId=lo,this.isRefreshingApp=!1,this.settingsSection=sa(),this.normalAuthLoading=!0,this.normalAuthError="",this.shortcutConfig={},this.workspaceUploadDefaultFolder=on(void 0),this.appStartupStarted=!1,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.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}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,Va),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth()}startAuthenticatedApp(){this.appStartupStarted||(this.appStartupStarted=!0,this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},jx),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(){if(this.apiScope==="management"){this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError="";try{const e=await Wt.status();this.normalAuthStatus=e,e.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=`检查普通模式密码失败:${ii(e)}`}finally{this.normalAuthLoading=!1}}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,Va),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(!Gx(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),Kx(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=ia();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=Ux){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=f(this.state);try{const t=await kl.piWebStatus(e);f(this.state)===e&&this.setState({piWebStatus:t})}catch(t){f(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=f(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?[f(this.state)]:this.state.machines.filter(t=>ed(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 Ne.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=on(e)}async submitNormalAuth(e){const t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError="";try{t==="setup"?await Wt.setup(e.password):t==="change"?await Wt.changePassword(e.currentPassword??"",e.password):await Wt.login(e.password);const i=await Wt.status();this.normalAuthStatus=i,this.normalAuthDialogMode=void 0,i.authenticated&&this.startAuthenticatedApp()}catch(i){this.normalAuthError=ii(i)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!=="management"&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?"login":"setup"}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(ia(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?Za():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.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:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const d=this.state.projects.find(p=>p.id===e.projectId);if(!d){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(d,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Za():{selectedFilePath:Ns(ur,"file"),selectedDiffPath:Ns(fr,"diff"),selectedTerminalId:Ns(Oi,"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){Xs(e,{replace:!0}),be(ur,"file",void 0,{replace:!0}),be(fr,"diff",void 0,{replace:!0}),be(Oi,"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=Jx(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>=Lr.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",o=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}${o===void 0?"":` ${o}`}`})}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(r=>r.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 gr(),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()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),Xs({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(En(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(En(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Xs(Dn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){be(ur,"file",e.selectedFilePath,{replace:!0}),be(fr,"diff",e.selectedDiffPath,{replace:!0}),be(Oi,"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)??bg(e.id);if(await this.restoreRouteFor(Dn(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=f(this.state)){const i=Xa(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=sb(e,{api:{runTerminalCommand:(o,n)=>Ot.runTerminalCommand(o,n,t),listCommandRuns:o=>Ot.listCommandRuns(o,t),getCommandRun:o=>Ot.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((f(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"),f(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){be(Oi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(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,Ys(e)}closeSettings(){this.settingsSection=void 0,Ys(void 0)}navigateSettings(e){this.settingsSection=e,Ys(e)}restoreSettingsRoute(){this.settingsSection=sa()}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()},f(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 kn(this.apiScope);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=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Vx(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):Qx(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=f(this.state);try{const i=await Ot.terminals(e.projectId,e.id,t);if(f(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=Ja(e),s=Ja(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({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`
|
|
2916
|
+
`,Lx=900*1e3,Ox=750,Wr=[1e3,3e3,8e3,15e3,3e4],Ka={capture:!0},hr="auto:on",Va="auto:off",Li="theme:",ur=vi("core:workspace.files"),fr=vi("core:workspace.git"),Oi=vi("core:workspace.terminal"),Fx=320,_x=2,jx="(min-width: 1181px)";let Q=class extends I{constructor(){super(...arguments),this.state=tu(),this.apiScope=Bx(),this.sessions=new Jf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new qf,{socket:new Nl(this.apiScope)}),this.activity=new iu(()=>this.state,e=>{this.setState(e)}),this.auth=new ou(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new hg(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new dg),this.projects=new wu(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new bu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new uu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new vu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Pg,this.realtime=new xn(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new mg,this.terminalSelection=new kg,this.appShell=new Sv(this),this.panelCollapse=new Wv(this),this.panelResize=new Ov(this),this.navigationSections=new Tv(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=Ux(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=qg()??Bg,this.activeThemeId=oo,this.isRefreshingApp=!1,this.settingsSection=ia(),this.normalAuthLoading=!0,this.normalAuthError="",this.shortcutConfig={},this.workspaceUploadDefaultFolder=rn(void 0),this.appStartupStarted=!1,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.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}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,Ka),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth()}startAuthenticatedApp(){this.appStartupStarted||(this.appStartupStarted=!0,this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Lx),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(){if(this.apiScope==="management"){this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError="";try{const e=await Lt.status();this.normalAuthStatus=e,e.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=`检查普通模式密码失败:${ii(e)}`}finally{this.normalAuthLoading=!1}}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,Ka),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(!qx(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),zx(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=ta();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=Ox){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=f(this.state);try{const t=await Il.piWebStatus(e);f(this.state)===e&&this.setState({piWebStatus:t})}catch(t){f(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=f(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?[f(this.state)]:this.state.machines.filter(t=>sd(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 Ne.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=rn(e)}async submitNormalAuth(e){const t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError="";try{t==="setup"?await Lt.setup(e.password):t==="change"?await Lt.changePassword(e.currentPassword??"",e.password):await Lt.login(e.password);const i=await Lt.status();this.normalAuthStatus=i,this.normalAuthDialogMode=void 0,i.authenticated&&this.startAuthenticatedApp()}catch(i){this.normalAuthError=ii(i)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!=="management"&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?"login":"setup"}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(ta(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?Ja():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.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:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const d=this.state.projects.find(p=>p.id===e.projectId);if(!d){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(d,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Ja():{selectedFilePath:Ns(ur,"file"),selectedDiffPath:Ns(fr,"diff"),selectedTerminalId:Ns(Oi,"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){Xs(e,{replace:!0}),ve(ur,"file",void 0,{replace:!0}),ve(fr,"diff",void 0,{replace:!0}),ve(Oi,"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=Kx(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>=Wr.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",o=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}${o===void 0?"":` ${o}`}`})}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(r=>r.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 gr(),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()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),Xs({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(Tn(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Tn(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Xs(En(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ve(ur,"file",e.selectedFilePath,{replace:!0}),ve(fr,"diff",e.selectedDiffPath,{replace:!0}),ve(Oi,"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)??vg(e.id);if(await this.restoreRouteFor(En(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=f(this.state)){const i=Za(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Yv(e,{api:{runTerminalCommand:(o,n)=>Ot.runTerminalCommand(o,n,t),listCommandRuns:o=>Ot.listCommandRuns(o,t),getCommandRun:o=>Ot.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((f(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"),f(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){ve(Oi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(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,Ys(e)}closeSettings(){this.settingsSection=void 0,Ys(void 0)}navigateSettings(e){this.settingsSection=e,Ys(e)}restoreSettingsRoute(){this.settingsSection=ia()}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()},f(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 xn(this.apiScope);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=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Nx(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):Hx(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=f(this.state);try{const i=await Ot.terminals(e.projectId,e.id,t);if(f(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=Qa(e),s=Qa(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({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`
|
|
2918
2917
|
<workspace-panel
|
|
2919
2918
|
id="workspace-panel"
|
|
2920
2919
|
.workspace=${e}
|
|
@@ -2928,9 +2927,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2928
2927
|
<app-panel-edge-control
|
|
2929
2928
|
side="navigation"
|
|
2930
2929
|
controls="navigation-panel"
|
|
2931
|
-
resizeLabel="
|
|
2932
|
-
expandLabel="
|
|
2933
|
-
collapseLabel="
|
|
2930
|
+
resizeLabel="调整导航面板大小"
|
|
2931
|
+
expandLabel="展开导航面板"
|
|
2932
|
+
collapseLabel="折叠导航面板"
|
|
2934
2933
|
.collapsed=${this.panelCollapse.navigationPanelCollapsed}
|
|
2935
2934
|
.resizable=${!this.appShell.isMobileNavigationLayout}
|
|
2936
2935
|
.panelWidth=${this.panelResize.panelWidth("navigation")}
|
|
@@ -2946,9 +2945,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2946
2945
|
<app-panel-edge-control
|
|
2947
2946
|
side="workspace"
|
|
2948
2947
|
controls="workspace-panel"
|
|
2949
|
-
resizeLabel="
|
|
2950
|
-
expandLabel="
|
|
2951
|
-
collapseLabel="
|
|
2948
|
+
resizeLabel="调整工作区面板大小"
|
|
2949
|
+
expandLabel="展开工作区面板"
|
|
2950
|
+
collapseLabel="折叠工作区面板"
|
|
2952
2951
|
.collapsed=${this.panelCollapse.workspacePanelCollapsed}
|
|
2953
2952
|
.resizable=${!this.appShell.isMobileNavigationLayout}
|
|
2954
2953
|
.panelWidth=${this.panelResize.panelWidth("workspace")}
|
|
@@ -2960,7 +2959,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2960
2959
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
2961
2960
|
.onReset=${()=>{this.resetResizablePanel("workspace")}}
|
|
2962
2961
|
></app-panel-edge-control>
|
|
2963
|
-
`}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),r=Math.floor(i-s-
|
|
2962
|
+
`}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),r=Math.floor(i-s-_x-Fx);return Math.max(t.minWidth,Math.min(t.maxWidth,r))}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(jx).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||Pe(e,be.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Pe(e,be.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Pe(e,be.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Kl(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&Pe(t,be.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return jg(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await wr.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${ii(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||Ut(t.previewRequest)!==Ut(e)){this.sessionCleanupDialog={...t??{},error:"运行清理前请先预览。"};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await wr.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${ii(s)}`})}}renderNavigationPanel(){return l`
|
|
2964
2963
|
<app-navigation-panel
|
|
2965
2964
|
.machines=${this.state.machines}
|
|
2966
2965
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -2976,7 +2975,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
2976
2975
|
.workspacesByProjectId=${this.state.workspacesByProjectId}
|
|
2977
2976
|
.workspaces=${this.state.workspaces}
|
|
2978
2977
|
.selectedWorkspace=${this.state.selectedWorkspace}
|
|
2979
|
-
.deletingWorkspaceIds=${
|
|
2978
|
+
.deletingWorkspaceIds=${rm(this.state.workspaceDeletionRuns)}
|
|
2980
2979
|
.sessions=${this.state.sessions}
|
|
2981
2980
|
.sessionStatuses=${this.state.sessionStatuses}
|
|
2982
2981
|
.sessionActivities=${this.state.sessionActivities}
|
|
@@ -3021,14 +3020,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
3021
3020
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
3022
3021
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
3023
3022
|
></app-navigation-panel>
|
|
3024
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async startSessionFromNavigation(){const e=++this.navigationSelectionSeq,t=()=>e===this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection("sessions"),await this.startSessionAndOpenChat(t)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!vs(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 gr(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gr(),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:"正在加载项目…",body:"正在查找你已添加到 PI WEB 的项目。"}:e===void 0?this.state.projects.length===0?{title:"还没有项目",body:"使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。"}:{title:"选择项目",body:"从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。"}:this.state.isLoadingWorkspaces?{title:"正在加载工作区…",body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:"未找到工作区",body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:"选择工作区",body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"正在加载项目…":this.state.selectedWorkspace!==void 0?"选择或启动会话。":this.state.selectedProject!==void 0?"选择工作区以启动会话。":this.state.projects.length===0?"添加项目以启动会话。":"选择项目和工作区以开始会话。"}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=Qa(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=>Lt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await Lt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await Lt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await Lt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Qa(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return hv({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},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,workspaceUploadDefaultFolder:zh(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return tb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope==="management"?[]:[{id:"app.normal-auth.change-password",title:"修改普通模式密码",description:"更改进入普通模式所需的本地密码",group:"偏好设置",enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode="change",this.normalAuthError=""}}]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Xn())}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}`,()=>Xn(`/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(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>pv({state:this.state,prompt:this.createPromptEditor(),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.startSessionAndOpenChat()),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(!fg(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(sc(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
|
|
3023
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async startSessionFromNavigation(){const e=++this.navigationSelectionSeq,t=()=>e===this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection("sessions"),await this.startSessionAndOpenChat(t)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!vs(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 gr(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gr(),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:"正在加载项目…",body:"正在查找你已添加到 PI WEB 的项目。"}:e===void 0?this.state.projects.length===0?{title:"还没有项目",body:"使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。"}:{title:"选择项目",body:"从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。"}:this.state.isLoadingWorkspaces?{title:"正在加载工作区…",body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:"未找到工作区",body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:"选择工作区",body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"正在加载项目…":this.state.selectedWorkspace!==void 0?"选择或启动会话。":this.state.selectedProject!==void 0?"选择工作区以启动会话。":this.state.projects.length===0?"添加项目以启动会话。":"选择项目和工作区以开始会话。"}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=Ga(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=>bt.workspaceFile(e.projectId,e.id,i,t),readOptionalFile:i=>bt.optionalWorkspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await bt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await bt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await bt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Ga(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return lv({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},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,workspaceUploadDefaultFolder:Bh(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Zv(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope==="management"?[]:[{id:"app.normal-auth.change-password",title:"修改普通模式密码",description:"更改进入普通模式所需的本地密码",group:"偏好设置",enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode="change",this.normalAuthError=""}}]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Zn())}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}`,()=>Zn(`/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(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>av({state:this.state,prompt:this.createPromptEditor(),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.startSessionAndOpenChat()),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(!ug(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(nc(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
|
|
3025
3024
|
|
|
3026
3025
|
This will run git worktree remove and delete:
|
|
3027
3026
|
${e.path}
|
|
3028
3027
|
|
|
3029
|
-
The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await
|
|
3028
|
+
The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await bt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${ii(r)}`})}}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(f(this.state)!==t)return;const i=$r(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=f(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(im(t.id));if(f(this.state)!==e)return;const s=sm(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))as(r)||await this.handleCompletedWorkspaceDeletionRun(r,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(as);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=f(this.state)){if(f(this.state)!==t)return;const i=Za(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=$r(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),f(this.state)!==t)return;this.setState({workspaceDeletionRuns:Vx(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"工作区删除失败。请查看终端输出。"}),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(`移除 ${e.name}?
|
|
3030
3029
|
|
|
3031
|
-
这只会从当前 PI WEB 网关移除它。`))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:`操作失败:${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:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ 当前":""}`,description:r}})}})}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?
|
|
3030
|
+
这只会从当前 PI WEB 网关移除它。`))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:`操作失败:${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:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ 当前":""}`,description:r}})}})}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?Va:hr;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${Li}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${Li}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hr||e===Va){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===hr},this.applyPreferredTheme(!0);return}if(!e.startsWith(Li))return;const t=e.slice(Li.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,Kg(t),e&&Hg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Vg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oc(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"当所选主题有配对主题时,跟随系统明暗偏好。":e.selectedThemePair===void 0?"已开启,但所选主题没有明暗配对,因此会保持当前主题。":`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?"浅色":"深色"}偏好。`}themeOptionLabel(e,t){const i=[...e.id===t?["已选择"]:[],...e.id===this.activeThemeId&&e.id!==t?["生效中"]:[]];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("自动配对"),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:"选择思考级别",selectedValue:t,options:e.map(i=>{const s=Gx(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...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`
|
|
3032
3031
|
<app-context-bar
|
|
3033
3032
|
.machines=${this.state.machines}
|
|
3034
3033
|
.machine=${this.state.selectedMachine}
|
|
@@ -3049,7 +3048,7 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
|
|
|
3049
3048
|
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
|
|
3050
3049
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
3051
3050
|
${this.renderNavigationPanelEdgeControl()}
|
|
3052
|
-
<main class=${
|
|
3051
|
+
<main class=${pc(e.mainView)}>
|
|
3053
3052
|
${this.renderContextBar()}
|
|
3054
3053
|
${this.renderMobileMainTabs()}
|
|
3055
3054
|
${e.error?l`<div class="error">${e.error}</div>`:null}
|
|
@@ -3082,4 +3081,4 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
|
|
|
3082
3081
|
.onSubmit=${t=>{this.submitNormalAuth(t)}}
|
|
3083
3082
|
.onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=""}}
|
|
3084
3083
|
></normal-auth-dialog>
|
|
3085
|
-
`}};Q.styles=
|
|
3084
|
+
`}};Q.styles=Wx;ie([v()],Q.prototype,"state",2);ie([q("chat-view")],Q.prototype,"chatView",2);ie([q("prompt-editor")],Q.prototype,"promptEditor",2);ie([q("app-navigation-panel")],Q.prototype,"navigationPanel",2);ie([q("#navigation-panel")],Q.prototype,"navigationPanelFrame",2);ie([q("#workspace-panel")],Q.prototype,"workspacePanelFrame",2);ie([v()],Q.prototype,"activeThemeId",2);ie([v()],Q.prototype,"isRefreshingApp",2);ie([v()],Q.prototype,"sessionCleanupDialog",2);ie([v()],Q.prototype,"settingsSection",2);ie([v()],Q.prototype,"normalAuthStatus",2);ie([v()],Q.prototype,"normalAuthLoading",2);ie([v()],Q.prototype,"normalAuthError",2);ie([v()],Q.prototype,"normalAuthDialogMode",2);ie([v()],Q.prototype,"shortcutConfig",2);ie([v()],Q.prototype,"workspaceUploadDefaultFolder",2);Q=ie([W("pi-web-app")],Q);function Ux(){const e=new ov;return e.register({id:"core",plugin:zm}),e.register({id:"themes",plugin:Km}),e}function Bx(){const e=ol()?"management":"normal";return Hd(e),e}function Ga(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 zx(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Nx(e,t){return sd(e,t)}function sd(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function qx(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Qa(e){return dt(e.status,e.activity)}function Hx(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Ja(){return{}}function Za(e,t){return JSON.stringify([e,t])}function Kx(e){const t=Math.min(e,Wr.length-1);return Wr[t]??3e4}function ii(e){return e instanceof Error?e.message:String(e)}function Vx(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gr(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Gx(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{D as a,l as b,Ot as c,ak as d,ok as e,q as f,I as i,c as n,v as r,nk as s,W as t};
|